0% found this document useful (0 votes)
11 views30 pages

Java Programming Basics Overview

Module 1 of the Object-Oriented Programming with Java course provides an overview of Java, covering its principles, data types, operators, control statements, and the Java Development Kit (JDK). It discusses key concepts of object-oriented programming such as abstraction, encapsulation, inheritance, and polymorphism, along with Java's features and history. The module also includes practical examples of Java programming, including variable declaration, bytecode, and the execution of a simple Java program.

Uploaded by

24i37.ise
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views30 pages

Java Programming Basics Overview

Module 1 of the Object-Oriented Programming with Java course provides an overview of Java, covering its principles, data types, operators, control statements, and the Java Development Kit (JDK). It discusses key concepts of object-oriented programming such as abstraction, encapsulation, inheritance, and polymorphism, along with Java's features and history. The module also includes practical examples of Java programming, including variable declaration, bytecode, and the execution of a simple Java program.

Uploaded by

24i37.ise
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

MODULE 1 24CS36A

III Semester

Course: OBJECT ORIENTED PROGRAMMING WITH JAVA


Course Code: BCS306A
Credits: 03 & 2022 Scheme

Module I: Overview of JAVA

Course Instructor
Mrs. Revathi K
Assistant Professor,
Dept. of CSE, EPCET
MODULE 1 24CS36A

MODULE - 1

An Overview of Java: Object-oriented programming (Two Paradigms, Abstraction, The Three OOP
Principles), Using Blocks of Code, Lexical Issues (Whitespace, Identifiers, Literals, Comments,
Separators, The Java Keywords).

Data Types, Variables, and Arrays: The Primitive Types (Integers, Floating-Point Types, Characters,
Booleans), Variables, Type Conversion and Casting, Automatic Type Promotion in Expressions,
Arrays, Introducing Type Interference with Local Variables.

Operators: Arithmetic Operators, Relational Operators, Boolean Operators, Logical Operators, The
Assignment Operator, The? Operator, Operator Precedence, Using Parentheses.

Control Statements: Java’s Selection Statements (if, The Traditional Switch), Iteration Statements
(while, do-while, for, The For-Each Version of the Loop, Local Variable Type Inference in a for Loop,
Nested Loops), Jump Statements (Using break, Using continue, return).

Text book: Ch 2, 3, 4, 5
MODULE 1 24CS36A

Java Byte Code


Byte code is a highly optimized set of instructions designed to be executed by the Java run-time
system, which is called the Java Virtual Machine (JVM).
Translating a Java program into bytecode makes it much easier to run a program in a wide variety of
environments because only the JVM needs to be implemented for each platform.

Bytecode is the compiled format for Java programs. Once a Java program has been converted
to bytecode, it can be transferred across a network and executed, which makes JAVA a
platform Independent Language.
Java Development Kit (JDK):
Java Development Kit contains two parts.
One part contains the utilities like javac, debugger, jar which helps in compiling the
source code (.java files) into byte code (.class files) and debug the programs.
The other part is the JRE, which contains the utilities like java which help in
running/executing the byte code.

Java Run-time Environment (JRE):

Java Run-time Environment helps in running the programs. JRE contains the JVM, the java
classes/packages and the run-time libraries. If we do not want to write programs, but only
execute the programs written by others, then JRE alone will be sufficient.

Java Virtual Machine (JVM):

Java Virtual Machine is important part of the JRE, which actually runs the programs (.class
files), it uses the java class libraries and the run-time libraries to execute those programs. Every
operating system (OS) or platform will have a different JVM.
MODULE 1
OOP-BCS306A

Just In Time Compiler (JIT):

JIT is a module inside the JVM which helps in compiling certain parts of byte code
into the machine code for higher performance. Note that only certain parts of byte
code will be compiled to the machine code, the other parts are usually interpreted
and executed.

Write Once and Run Anywhere (WORA) / CORA (Compile Once and run
anywhere)
Java allows run Java bytecode on any machine irrespective of the machine or the
hardware, using JVM (Java Virtual Machine). The bytecode generated by the compiler
is not platform-specific and hence takes help of JVM to run on a wide range of machines.
So we can call Java programs as a write once and run on any machine residing anywhere.
Features of JAVA
Simple
Secure
Portable
Object-oriented
Robust
Multithreaded
Architecture-neutral
Interpreted
High performance
Distributed
Dynamic

Dept. of CSE, EPCET 4


MODULE 1
OOP-BCS306A
History of Java

James Gosling initiated Java language project in June 1991 for use in one of his many
set-top box projects. The language, initially called ‗Oak‘ after an oak tree that stood
outside Gosling's office, also went by the name ‗Green‘ and ended up later being
renamed as Java, from a list of random words.

Sun released the first public implementation as Java 1.0 in 1995. It promised
Write Once, Run Anywhere (WORA), providing no-cost run-times on popular
platforms.
On 13 November, 2006, Sun released much of Java as free and open source software
under the terms of the GNU General Public License (GPL).
On 8 May, 2007, Sun finished the process, making all of Java's core code free and
open-source, aside from a small portion of code to which Sun did not hold the
copyright.
Two Paradigms of Programming
All computer programs consist of two elements: code and data.

 process oriented Programming -- characterizes a program as a series of linear


steps (that is, code). In this method code is acting on data Example: C

 object-oriented programming-- organizes a program around its data. In this


method data controlling access to code Example: JAVA

Abstraction
An essential element of object-oriented programming is abstraction. It focuses on
hiding the implementation details of an object and exposing only the essential
features.
Three OO Concepts:
Encapsulation
Inheritance
Polymorphism

Encapsulation
It is one of the core concepts of Object Oriented Programming (OOP) in which we
bind the data members and methods into a single unit .Specifically, the data defined
by the class are referred to as member variables or instance variables. The code
that operates on that data is referred to as member methods or just methods.

Each method or variable in a class may be marked private or public.


The public interface of a class represents everything that external users of
the class need to know, or may know.
The private methods and data can only be accessed by code that is a member
of the class.

Dept. of CSE, EPCET 5


MODULE 1
OOP-BCS306A

Inheritance
Inheritance is the process by which one object acquires the properties of another
object. This is important because it supports the concept of hierarchical classification.
The class which inherits the properties of other is known as subclass (derived class,
child class) and the class whose properties are inherited is known as superclass (base
class, parent class).

Polymorphism

It is a feature that allows one interface to be used for a general class of actions.
Polymorphism in java is a concept by which we can perform a single action by
different ways. Polymorphism is derived from 2 Greek words: poly and morphs. The
word "poly" means many and "morphs" means forms.
There are two types of polymorphism in java:

compile time polymorphism and


Runtime polymorphism.

Java Basics
 Object - Objects have states and behaviours. An object is an instance of
a class. Example: A dog has states - colour, name, breed as well as
behaviour such as wagging their tail, barking, eating.

 Class - A class can be defined as a template/blueprint that describes the


behaviour/state that the object of its type supports.

Dept. of CSE, EPCET 6


MODULE 1
OOP-BCS306A
 Methods - A method is basically behaviour. A class can contain many
methods. It is in methods where the logics are written, data is manipulated
and all the actions are executed.

 Instance Variables - Each object has its unique set of instance variables.
An object's state is created by the values assigned to these instance
variables.

First Java Program


Let us look at a simple code that will print the words Hello World.

public class MyFirstJavaProgram {


/* This is my first java program.
This will print 'Hello World' as the output */

public static void main(String []args)


{
[Link]("Hello World"); // prints Hello World
}
}

C:\> javac [Link] C:\>


java MyFirstJavaProgram
Hello World

Compiling a Java Program


o Javac Compiler is used to compile JAVA Program
C:\> javac [Link]
o The javac compiler creates file called [Link] that contains the bytecode
version of the program.
Executing a Java Program
 Java application launcher, called java is used to run JAVA program.
 java is interpreter of Java Programming Language
 To do so, pass the class name Example as a command-line argument.
 C:\> java Example
 When the program is run, the following output is displayed.
 This is a simple Java program.
public static void main(String args[]) {
 All Java applications begin execution by calling main( ).
 When a class member is preceded by public, then that member may be
accessed by code outside the class in which it is declared.
 The keyword static allows main( ) to be called without having to instantiate a

Dept. of CSE, EPCET 7


MODULE 1
OOP-BCS306A
particular instance of the class. This is necessary since main( ) is called by the
Java Virtual Machine before any objects are made.
 The keyword void simply tells the compiler that main( ) does not return a
value.
 Strings arg[] declares a parameter named args, which is an array of instances
of the class String.
[Link]("This is a simple Java program.");

This line outputs the string ―This is a simple Java program.‖ followed by a new line
on the
screen. In this case, println( )displays the string which is passed to it.
System is a predefined class that provides access to the system, and out is the output
stream that is connected to the console.

USING BLOCKS OF CODE:


Java allows two or more statements to be grouped into blocks of code, also called
code blocks. This is done by enclosing the statements between opening and closing
curly braces.
if(x < y)
{
// begin a block
x = y;
y = 0;
} // end of block
Example:
class BlockTest
{
public static void main(String args[ ])
{
int x, y;
y = 10;
// the target of this loop is a block
for(x = 5; x<10; x++)
{
[Link]("This is x: " + x);
[Link]("This is y: " + y);
y = y - 2;
}
}
}

Dept. of CSE, EPCET 8


MODULE 1
OOP-BCS306A

Output:

The output generated by this program is shown here:


This is x: 5
This is y: 10
This is x: 6
This is y: 8
This is x: 7
This is y: 6
This is x: 8
This is y: 4
This is x: 9
This is y: 2
LEXICAL ISSUES:

Java programs are a collection of whitespace, identifiers, literals, comments,


operators, separators, and keywords (These are called as Lexical Issues). In C
programming it is called Tokens.

1. Whitespace: Java is a free-form language. This means that you do not need to
follow any special indentation rules. In Java, whitespace is a space, tab, or
newline.

2. Identifiers: Identifiers are used for class names, method names, and variable
names. An identifier may be any descriptive sequence of uppercase and lowercase
letters, numbers, or the underscore and dollar-sign characters.
They must not begin with a number, lest they be confused with a numeric literal.
Again, Java is case-sensitive, so VALUE is a different identifier than Value.

3. Literals: A constant value in Java is created by using a literal representation of it.

4. Comments: As mentioned, there are three types of comments defined by Java.


single-line and multiline. The third type is called a documentation comment.

5. Separators: In Java, there are a few characters that are used as separators. The
most commonly used separator in Java is the semicolon. Other separators are (),
{},[], etc

6. Keywords: There are 67 keywords currently defined in the Java language. keywords
cannot be used as identifiers

Dept. of CSE, EPCET 9


MODULE 1
OOP-BCS306A
DATA TYPES
Java Is a Strongly Typed Language. Datatype is defined as a type of data stored in the
variable.
There are eight primitive datatypes supported by Java.

Data Default
Type Range size
Boolean False/ true 1 bit
Char 0-65536 2 byte
Byte –128 to 127 1 byte
Short –32,768 to 32,767 2 byte
Int –2,147,483,648 to 2,147,483,647 4 byte
–9,223,372,036,854,775,808 to
Long 9,223,372,036,854,775,807 8 byte

Float 1.4e–045 to 3.4e+038 4 byte


Double 4.9e–324 to 1.8e+308 8 byte

Integers: This group includes byte, short, int, and long, which are for whole valued signed
numbers. All of these are signed, positive and negative values. Java does not support
unsigned, positive-only integers.
Floating point: This group includes float and double, which represent numbers with
fractional precision.
Char: This group includes char, which represents symbols in a character set, like
letters and numbers.
Boolean This group includes boolean, which is a special type for representing
true/false values.

BYTE: The smallest integer type is byte. This is a signed 8-bit type that has a range
from –128 to 127. Variables of type byte are especially useful when you’re working
with a stream of data from a network or file. They are also useful when you’re
working with raw binary data that may not be directly compatible with Java’s other
built-in types.
SHORT: short is a signed 16-bit type. It has a range from –32,768 to 32,767. It is probably
the least used Java type.

Dept. of CSE, EPCET 10


MODULE 1
OOP-BCS306A
public class JavaCharExample {

public static void main(String[] args) { char


ch1 = 'a';
char ch2 = 65; /* ASCII code of 'A'*/

[Link]("Value of char variable ch1 is :" +


ch1);
[Link]("Value of char variable ch2 is :" +
ch2);
}
}

Output would be
Value of char variable ch1 is :a
Value of char variable ch2 is :A

VARIABLES
The variable is the basic unit of storage in a Java program. A variable is defined by
the combination of an identifier, a type, and an optional initializer.

Declaring a Variable

data type variable [ = value][, variable [= value] ...] ;

Following are valid examples of variable declaration and initialization in Java:

int a, b, c; // Declares three ints, a, b,


and c.
int a = 10, b = 10; // Example of initialization
byte B = 22; // initializes a byte type variable B.
double pi = 3.14159; // declares and assigns a value of PI.
char a = 'a'; // the char variable a is initialized with value 'a'
There are three kinds of variables in Java:
Local variables
Instance variables
Class/Static variables

Local Variables

Dept. of CSE, EPCET 11


MODULE 1
OOP-BCS306A
Local variables are declared in methods, constructors, or blocks.
Local variables are implemented at stack level internally.
Access modifiers cannot be used for local variables.
Instance Variables
Instance variables are declared in a class, but outside a method, constructor
or any block.
When a space is allocated for an object in the heap, a slot for each instance
variable value is created.
Access modifiers can be given for instance variables.
Class/static Variables
Class variables also known as static variables are declared with the static
keyword in a class, but outside a method, constructor or a block.
There would only be one copy of each class variable per class, regardless of
how many objects are created from it.
Static variables are stored in the static memory. It is rare to use static variables
other than declared final and used as either public or private constants.

Dynamic Initialization
Java allows variables to be initialized dynamically, using any expression valid
at the time the variable is declared.
Ex:
class dyn {
public static void main(String args[]) {
double a = 3.0, b = 4.0;
// c is dynamically initialized
double c = [Link](a * a + b * b);
[Link]("Hypotenuse is " + c);
}
}

Here, three local variables—a, b, and c—are declared. The first two, a and b, are
initialized by constants. However, c is initialized dynamically to the length of the
hypotenuse

The Scope and Lifetime of Variables

Java allows variables to be declared within any block. A block defines a scope.
Thus, each time you start a new block, you are creating a new scope. A scope
determines what objects are visible to other parts of your program. It also determines
the lifetime of those objects.
In Java, there are two major scopes
1. defined by a class

Dept. of CSE, EPCET 12


MODULE 1
OOP-BCS306A
2. defined by a method.
As a general rule, variables declared inside a scope are not visible (that is, accessible) to
code that is defined outside that scope. Thus, when you declare a variable within a scope,
you are localizing that variable and protecting it from unauthorized access and/or
modification.

Example:
class Scope {
public static void main(String args[]) { int x; //
known to all code within main x = 10;
if(x == 10) { // start new scope
int y = 20; // known only to this block
// x and y both known here. [Link]("x and y:
" + x + " " + y); x = y * 2;
}
// y = 100; // Error! y not known here
// x is still known here.
[Link]("x is " + x);
}
}

Output

x and y: 10 20
x is 22

Type Conversion and Casting


It’s a Process to assign a value of one type to a variable of another type

1. Java’s Automatic Conversions / Widening conversion / Implicit


If the two types are compatible, then Java will perform the conversion automatically. The
destination type is larger than the source type.

2. Casting Incompatible Types / Narrowing Conversion / Explicit

Dept. of CSE, EPCET 13


MODULE 1
OOP-BCS306A

To create a conversion between two incompatible types, you must use a cast. A cast is simply an
explicit type conversion.
Syntax :
(target-type) value
Example:
int a;
byte b;
// …
b = (byte) a

Example:

public class Test


{
public static void main(String[] args)
{
double d = 100.04;
long l = (long)d; //explicit type casting required int i =
(int)l; //explicit type casting required

[Link]("Double value "+d);


[Link]("Long value "+l);
[Link]("Int value "+i);

Output :
Double value 100.04
Long value 100
Int value 100

Automatic Type Promotion in Expressions


Automatic type promotion in expressions in Java refers to the implicit conversion of smaller
primitive data types to larger ones during the evaluation of an expression. This process is
handled by the Java compiler to prevent data loss and ensure consistent data types within
calculations.

Dept. of CSE, EPCET 14


MODULE 1
OOP-BCS306A

public class PromotionExample {


public static void main(String[] args) {
byte b = 10;
int i = 20;
float f = 5.5f;
double d = 10.2;

// In (b + i), 'b' is promoted to 'int', result is 'int'


// In (int_result + f), 'int_result' is promoted to 'float', result is 'float'
// In (float_result + d), 'float_result' is promoted to 'double', result is 'double'
double result = b + i + f + d;

[Link]("Result: " + result); // Output: Result: 45.7


}
}

Type Promotion Rules


1. All byte, short and char values are promoted to int.
2. If one operand is a long, the whole expression is promoted to long.
3. If one operand is a float, the entire expression is promoted to float.
4. If any of the operands is double, the result is double.

ARRAYS

An array is a group of similar data-items that are referred to by a common name.


Arrays of any type can be created and may have one or more dimensions. A specific
element in an array is accessed by its index.

One-Dimensional Arrays
A one-dimensional array is essentially, a list of like-typed variables. To create an
array, you first must create an array variable of the desired type. The general form of
a one-dimensional
array declaration is:

datatype identifier [ ];
Or
datatype[ ] identifier;

Ex: int month_days[];

Dept. of CSE, EPCET 15


MODULE 1
OOP-BCS306A
It declares an array variable but do not allocate any memory. New is a special
operator that allocates memory.
array-var = new type[size]; // (new will automatically be initialized to zero )
OR
dataType[] arrayVar = new dataType[arraySize];
Arrays can be initialized when they are declared. There is no need to use new.
class AutoArray {
public static void main(String args[]) {
int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
[Link]("April has " + month_days[3] + " days.");
}
}
Output:
April has 30 days

Multidimensional Arrays

In Java, multidimensional arrays are actually arrays of arrays.

int twoD[][] = new int[4][5];

EX: Lab program 1 Addition of Two matrices


Ex:
class TwoDArray {
public static void main(String args[]) { int
twoD[][]= new int[4][5];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<5; j++) {
twoD[i][j] = k; k++;
}
for(i=0; i<4; i++) {
for(j=0; j<5; j++)
[Link](twoD[i][j] + " ");

Dept. of CSE, EPCET 16


MODULE 1
OOP-BCS306A
[Link]();
}
}
}

This program generates the following output: 0 1 2 3 4


56789
10 11 12 13 14
15 16 17 18 19

Operators In Java

Java provides a rich operator environment. Java provides a rich set of operators to
manipulate variables. Operators in Java are special symbols that perform operations
on variables and [Link] can divide all the Java operators into the following
groups:

 Arithmetic Operators
 Relational Operators
 Bitwise Operators
 Logical Operators
 Ternary Operator
 Assignment Operator

Operators Precedence
Postfix expr++ expr--
Unary ++expr --expr +expr -expr ~ !
Multiplicative */%
Additive +-
Shift << >> >>>
Relational < > <= >= instance of
Equality == !=
bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
logical OR ||
Ternary ?:

Dept. of CSE, EPCET 17


MODULE 1
OOP-BCS306A
Assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=

Arithmetic Operators
The basic arithmetic operations—addition, subtraction, multiplication, and
division—all behave as you would expect for all numeric types.
The unary minus operator negates its single operand.
The unary plus operator simply returns the value of its operand.

class OperatorExample{
public static void main(String args[]){ int a=10;
int b=5;
[Link](a+b);//15
[Link](a-b);//5
[Link](a*b);//50
[Link](a/b);//2
[Link](a%b);//0
}}

Arithmetic Compound Assignment Operators [Shorthand assignment]

Java provides special operators that can be used to combine an arithmetic operation
with an assignment.

var op= expression;

class OperatorExample{
public static void main(String args[]){
int a=10;
int b=20;
a+=4; //a=a+4 (a=10+4)
b-=4; //b=b-4
(b=20-4)
[Link](a);
[Link](b);
}}

The Relational Operators


The relational operators determine the relationship that one operand has to the other.
The outcome of these operations is a boolean value. The relational operators are most
frequently used in the expressions that control the if statement and the various loop
statements.

Dept. of CSE, EPCET 18


MODULE 1
OOP-BCS306A

operator Description
== Check if two operands are equal
!= Check if two operands are not equal.
> Check if operand on the left is greater than operand on the right
< Check operand on the left is smaller than right operand
>= check left operand is greater than or equal to right operand
<= Check if operand on left is smaller than or equal to right operand

Boolean Logical Operators

The Boolean logical operators shown here operate only on boolean operands and
relational expressions. All of the binary logical operators combine two boolean
values to form a resultant boolean value. The logical Boolean operators, &, |, and ^,
operate on boolean values in the same way that they operate on the bits of an integer.

Short-Circuit Logical Operators

Java provides two interesting Boolean operators called short circuit operator.
They are called short-circuit because they do not always evaluate both operands—
evaluation stops as soon as the result is determined.

1) && (Short-Circuit AND)

 If the first condition is false, Java does not evaluate the second condition because the
result will always be false.

2) || (Short-Circuit OR)

 If the first condition is true, Java does not evaluate the second condition because the
result will always be true.

Example:

Dept. of CSE, EPCET 19


MODULE 1
OOP-BCS306A
public class ShortCircuitSimple {

public static void main(String[] args) {

int a = 5;

int b = 10;

// Short-circuit AND (&&)

if (a > 0 && b > 5) {

[Link]("Both conditions are true");

// Short-circuit OR (||)

if (a < 0 || b > 5) {

[Link]("At least one condition is true");

} }}
The Bitwise Operators
Java defines several bitwise operators that can be applied to the integer types: long,
int, short, char, and byte. These operators act upon the individual bits of their
operands. bitwise operators work on the binary representation (bits) of integers
They are summarized in the following table:

Operator Description
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
<< left shift
>> right shift
>>> Right Shift zero fill

A B ~A A&B A|B A^B

1 1 0 1 1 0

1 0 0 0 1 1

Dept. of CSE, EPCET 20


MODULE 1
OOP-BCS306A

0 1 1 0 1 1

0 0 1 0 0 0

public class BitwiseOperators {


public static void main(String[] args) {
int a = 5; // binary: 0101
int b = 3; // binary: 0011

[Link]("a & b = " + (a & b)); // AND → 1


[Link]("a | b = " + (a | b)); // OR → 7
[Link]("a ^ b = " + (a ^ b)); // XOR → 6
[Link]("~a = " + (~a)); // NOT → -6
[Link]("a << 1 = " + (a << 1)); // Left shift → 10
[Link]("a >> 1 = " + (a >> 1)); // Right shift → 2
[Link]("a >>> 1 = " + (a >>> 1)); // Unsigned right shift → 2
}
}

Unsigned Right Shift Operator(>>>)


The unsigned right shift operator in Java is written as >>>. It shifts bits to the right and
fills the leftmost bits with zeros, regardless of the sign of the number. This is different from the
signed right shift >>, which preserves the sign bit (i.e., fills with 1 for negative numbers).

Example:
public class UnsignedShiftExample {
public static void main(String[] args) {
int positive = 40; // Binary: 00000000 00000000 00000000 00101000
int negative = -40; // Binary: 11111111 11111111 11111111 11011000

[Link]("positive >>> 2 = " + (positive >>> 2)); // Output: 10


[Link]("negative >>> 2 = " + (negative >>> 2)); // Output: large
positive number
}
}

Java Ternary Operator


Java includes a special ternary (three-way) operator that can replace certain types of
if-then else statements. This operator is the ?. It can seem somewhat confusing at
first, but the ? can be used very effectively once mastered.
Syntax:

Dept. of CSE, EPCET 21


MODULE 1
OOP-BCS306A
expression1 ? expression2 : expression3
Here, expression1 can be any expression that Here, expression1 can be any
expression that evaluates to a boolean value. If expression1 is true, then expression2
is evaluated; otherwise, expression3 is evaluated.

class OperatorExample{
public static void main(String args[]){ int
a=2;
int b=5;
int min=(a<b)?a:b;
[Link](min);
}}

Output:

Increment and Decrement


The ++ and the – – are Java‘s increment and decrement operators. The increment
operator increases its operand by one. The decrement operator decreases its operand
by one.
class IncDec {
public static void main(String args[]) {
int a = 1;
int b = 2;
int c;
int d;
c = ++b;
d=a++;
c++;
[Link]("a = " + a);
[Link]("b = " + b);
[Link]("c = " + c);
[Link]("d = " + d);
}
}
Output
a=2
b=3
c=4
d=1

CONTROL STATEMENTS

Dept. of CSE, EPCET 22


MODULE 1
OOP-BCS306A
Java control statements are the backbone of decision-making and flow control in your programs. They
allow you to make choices, repeat actions, and jump between parts of code based on conditions.

Category 🔧 Statement Types 📌 Purpose


if, if-else, if-else-if, Execute code based on specific
Conditional switch conditions
Looping
for, while, do-while Repeat a block of code multiple times
(Iteration)
Alter the normal flow of loops or
Jumping break, continue, return
methods

If- else:
The if statement is Java‘s conditional branch statement. It can be used to route
program execution through two different paths. Here is the general form of the if
statement:
if (condition)
statement1;
else
statement2;

public class IfExample {


public static void main(String[]
args) { int age=20;
if(age>18)
{
[Link]("Eligible to vote");
}
}}
Nested ifs
A nested if is an if statement that is the target of another if or else. Nested ifs are very
common in programming. When you nest ifs, the main thing to remember is that an
else statement always refers to the nearest if statement that is within the same block
as the else and that is not already associated with an else.
Syntax :
if (condition)
{
if (condition){
//Do something
}
//Do something
}

Dept. of CSE, EPCET 23


MODULE 1
OOP-BCS306A
The if-else-if Ladder
A common programming construct that is based upon a sequence of nested ifs is the
if-elseif
ladder. It looks like this:

Syntax:
if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
.
.
.else statement;

public class ControlFlowDemo


{
public static void main(String[] args)
{
char ch = 'o';
if (ch == 'a' || ch == 'A') [Link](ch + "
is vowel.");
else if (ch == 'e' || ch == 'E') [Link](ch
+ " is vowel.");
else if (ch == 'i' || ch == 'I') [Link](ch +
" is vowel.");
else if (ch == 'o' || ch == 'O') [Link](ch
+ " is vowel.");
else if (ch == 'u' || ch == 'U') [Link](ch
+ " is vowel.");
else
[Link](ch + " is a consonant.");
}
}

Dept. of CSE, EPCET 24


MODULE 1
OOP-BCS306A
Switch
The switch statement is Java‘s multiway branch statement. It provides an easy way
to dispatch execution to different parts of your code based on the value of an
expression. As such, it often provides a better alternative than a large series of if-else-
if statements. Here is the general form of a switch statement:
Syntax: switch (expression)
{
case value1:
// statement
sequence
break;
case value2:
// statement
sequence
break;
.
.
.
case valueN :
// statement
sequence
break;
default:
// default statement sequence
}

Dept. of CSE, EPCET 25


MODULE 1
OOP-BCS306A
class StringSwitch {
public static void main(String args[]) {
String str = "two";
switch(str)
{
case "one":
[Link]("one");
break;
case "two":
[Link]("two");
break;
case "three":
[Link]("three");
break;
default:
[Link]("no match");
break;
}}}

Output : two

Iteration Statements
Java‘s iteration statements are for, while, and do-while. These statements create what
we commonly call loops. As you probably know, a loop repeatedly executes the same
set of instructions until a termination condition is met. As you will see, Java has a
loop to fit any programming need.

while
The while loop is Java‘s most fundamental loop statement. It repeats a statement or
block
while its controlling expression is true. It is also called as Entry Controlled Loop. Here is its
general form:

while(condition)
{
// body of loop
}
The condition can be any Boolean expression. The body of the loop will be
executed as long
as the conditional expression is true. When condition becomes false, control passes
to the next line of code immediately following the loop.

Dept. of CSE, EPCET 26


MODULE 1
OOP-BCS306A
Example:

class WhileLoopExample{
public static void main(String[]
args){ int num=0;
while(num<=5){
[Link](""+n
um); num++;
}
}
}

do-while
The do-while loop always executes its body at least once, because its conditional
expression is at the bottom of the loop. It is also called as Exit Controlled Loop. Its
general form is

do {

// body of loop

} while (condition);
For:
There are two forms of the for loop.
The first is the traditional form that has been in use since the original version of
Java. The second is the newer ―for-each‖ form.

1) Here is the general form of the traditional for statement:


for(initialization; condition; iteration)
{
// body
}
Ex : int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;
for(int i=0; i < 10;
i++) sum
+=
nums[i];

2) For-Each Version of the for Loop:


The general form of the for-each version of the for is shown here:

for(type itr-var : collection) statement-block

Dept. of CSE, EPCET 27


MODULE 1
OOP-BCS306A

Here, type specifies the type and itr-var specifies the name of an iteration
variable that will receive the elements from a collection(array), one at a time,
from beginning to end. The collection being cycled through is specified by
collection.

public class Test {


public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};

for(int x : numbers ) {
[Link]( x );
[Link](",");
}
[Link]("\n");
String [] names = {"James", "Larry", "Tom", "Lacy"};

for( String name : names ) {


[Link]( name );
[Link](",");
}}}
10, 20, 30, 40, 50,
James, Larry, Tom, Lacy,

Jump Statements

Using break
In Java, the break statement has three uses. First, as you have seen, it terminates a
statement sequence in a switch statement. Second, it can be used to exit a loop.
Third, it can be used as a ―civilized‖ form of goto.
1) Using break to Exit a Loop
2) Using break as a Form of Goto:
Java does not have a goto statement because it provides a way to branch in an
arbitrary and unstructured manner. This usually makes goto-ridden code hard
to understand and hard to maintain.

Dept. of CSE, EPCET 28


MODULE 1
OOP-BCS306A
public class BreakDemo
{
public static void main(String[] args)
{
for (int i = 1; i <= 10; i++)
{
if (i == 5)
{
break; // terminate loop if i is 5
}
[Link](i + " ");
}
[Link]("Thank you.");
}
}
Output 1 2 3 4 Thank you

Using continue
In while and do-while loops, a continue statement causes control to be transferred
directly to the conditional expression that controls the loop. In a for loop, control goes
first to the iteration portion of the for statement and then to
the conditional expression. For all three loops, any intermediate code is bypassed.

public class ContinueDemo


{
public static void main(String[] args)
{
for (int i = 1; i <= 10; i++)
{
if (i % 2 == 0)
{
continue; // skip next statement if i is even
}
[Link](i + " ");
}
}
}
13579

Dept. of CSE, EPCET 29


MODULE 1
OOP-BCS306A
Break Continue
The break statement results in the The continue statement stops the current
termination of the loop, it will come out of execution of the iteration and proceeds to the
the loop and stops further next iteration
iterations.
The break statement has two forms: labelled The continue statement skips the current
and iteration of a for, while , or do- while loop. The
unlabelled. unlabelled form skips to the end of the
An unlabelled break statement terminates the innermost loop's body and evaluates the
innermost switch, for, while, or do-while Boolean expression that controls the loop.
statement, but a labelled break terminates an A labelled continue statement skips the
outer statement. current iteration of an outer loop marked with
the given label.

The general form of the labelled break The general form of the labelled
statement is shown here: continue statement is shown here:
break label; continue label;

Return
The last control statement is return. The return statement is used to explicitly return from a
method. That is, it causes program control to transfer back to the caller of the method. As such,
it is categorized as a jump statement.
At any time in a method, the return statement can be used to cause execution to branch
back to the caller of the method. Thus, the return statement immediately terminates the method
in which it is executed.

class Return {
public static void main(String args[])
{
boolean t = true;
[Link]("Before the return.");
if(t)
return; // return to caller
[Link]("This won't execute.");
}
}
The output from this program is shown here:
Before the return.
Here, return causes execution to return to the Java run-time system, since it is the
run-time system that call main ( ):

Dept. of CSE, EPCET 30

You might also like