0% found this document useful (0 votes)
203 views

Module - 1

The document provides an overview of the syllabus for an Object Oriented Programming course in Java. It covers topics like data types and variables, operators, control statements, and an introduction to object-oriented programming concepts in Java including abstraction, encapsulation, inheritance, and polymorphism. It also provides a brief example of a simple Java program to print "Hello World" and explains the key terms used in the program.

Uploaded by

Abhinav S Bhat
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
203 views

Module - 1

The document provides an overview of the syllabus for an Object Oriented Programming course in Java. It covers topics like data types and variables, operators, control statements, and an introduction to object-oriented programming concepts in Java including abstraction, encapsulation, inheritance, and polymorphism. It also provides a brief example of a simple Java program to print "Hello World" and explains the key terms used in the program.

Uploaded by

Abhinav S Bhat
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Object Oriented Programming with JAVA(BCS306A) 2023

Module - 1
Syllabus
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 Inference with Local Variables.
Operators: Arithmetic Operators, Relational Operators, Boolean 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 for Loop, Local Variable Type Inference in a for
Loop, Nested Loops), Jump Statements (Using break, Using continue, return).
An Overview of Java
The key features of Java are security and portability (platform-independent nature). When we download
any application from the internet, there is a chance that the downloaded code contain virus. But,
downloading the Java code assures security. Java program can run on any type of system connected to
internet and thus provides portability.
The Platform independent nature can be interpreted by two things:
Operating System Independent: Independent of the operating system on which your source code is
being run.
Hardware Independent: Doesn't depend upon the hardware on which your java code is run upon i.e. it
can run on any hardware configuration.
These two points make it a platform independent language. Hence, the users do not have to change the
syntax of the program according to the operating system and do not have to compile the program again
and again on different operating systems.
The execution of a Java program is controlled by JVM (Java Virtual Machine). The JVM is the Java run-
time system and is the main component of making the java a platform independent language. For
building and running a java application we need JDK (Java Development Kit) which comes bundled with
Java runtime environment (JRE) and JVM. With the help of JDK the user compiles and runs java
program. As the compilation of java program starts the Java Bytecode is created i.e. a .class file is
created by JRE. Bytecode is a highly optimized set of instructions designed to be executed by JVM. Now
the JVM comes into play, which is made to read and execute this bytecode.
The JVM is linked with operating system and runs the bytecode to execute the code depending upon

1|Page
Object Oriented Programming with JAVA(BCS306A) 2023

operating system. Therefore, a user can take this class file (Bytecode file) formed to any operating
system which is having a JVM installed and can run the program easily without changing the syntax of a
program and without actually having the source code. The .class file which consists of bytecode is not
user-understandable and can be interpreted by JVM only to build it into the machine code. Java also has
the standard data size irrespective of operating system or the processor. These features make the java as a
portable (platform-independent) language.
Two Paradigms
All computer programs consist of two elements code and data. The program can be conceptually
organized around its code or around its data. Some programs are written around what is
happening and others are written around who is being affected. These are the two paradigms
that manage how a program is constructed are the process-oriented model & object-oriented
programming.
The process-oriented model approach characterizes a program as a series of linear steps. This
model can be understood of as code acting on data. Procedural languages such as C employ this
model to considerable success.
The object-oriented programming manages increasing complexity. It organizes a program
around its data that is, objects and a set of well-defined interfaces to that data. It can be
characterized as data controlling access to code.
Abstraction
Abstraction can be thought of as hiding the implementation details from the end-user. A
powerful way to manage abstraction is through the use of hierarchical classifications. This
allows us to layer the semantics of complex systems, breaking them into more manageable
pieces. For example, we consider a car as a vehicle and can be thought of as a single object. But,
from inside, car is a collection of several subsystems viz. steering, brakes, sound system, engine
etc. Again, each of these subsystems is a collection of individual parts (Ex. Sound system is a
combination of a radio and CD/tape player). As an owner of the car, we manage it as an
individual entity by achieving hierarchical abstractions.
Hierarchical abstractions of complex systems can also be applied to computer programs. The
data from a traditional process-oriented program can be transformed by abstraction into its
component objects. A sequence of process steps can become a collection of messages between
these objects. Thus, each of these objects describes its own unique behaviour. We can treat these
objects as concrete entities that respond to messages telling them to do something. This is the

2|Page
Object Oriented Programming with JAVA(BCS306A) 2023

essence of object-oriented programming.


The Three OOP Principles
Encapsulation, Inheritance and Polymorphism are the basic principles of any object oriented
programming language.
Encapsulation: It is the mechanism to bind the data and code working on that data into a single
entity. It provides the security for the data by avoiding outside manipulations. In Java,
encapsulation is achieved using classes. A class is a
collection of data and code. An object is an instance
of a class. That is, several objects share a common
structure (data) and behaviour (code) defined by that
class. The elements inside the class are known as
members. Specifically, the data or variables inside
the class are called as member variables or instance
variables or data members. The code that operates
on these data is referred to as member methods or
methods. The method operating on data will define the behaviour and interface of a class.
Another purpose of the class is to hide the information from outside manipulation. Class uses
public and private interfaces. The members declared as private can only be accessed by the
members of that class, whereas, the public members can be accessed from outside the class.
Inheritance: It is the process by which one object acquires the properties of another object &
supports the concept of hierarchical
classification. Use of inheritance, an object
will only define those qualities that make it
unique within its class. It can inherit its
general attributes from its parent. Inheritance
interacts with encapsulation also. If a given
class encapsulates some attributes, then any
subclass will have the same attributes plus any that it adds as part of its specialization. A new
subclass inherits all of the attributes of all of its ancestors. For example, a Doberman is part of
the classification dog, which in turn is part of the mammal class, which is under the class
animal.
Polymorphism: The ability of a message to be displayed in more than one form. It is possible
3|Page
Object Oriented Programming with JAVA(BCS306A) 2023

to design a generic interface to a group of related activities. This helps to reduce complexity by
allowing the same interface to be used to specify a general class of action.
Considering the dog analogy, a dog’s sense of smell is polymorphic. If the dog smells a cat, it
will bark and run after it. If the dog smells its food, it will salivate and run to its bowl. The same
sense of smell is at work in both situations. This same general concept can be implemented in
Java as it applies to methods within a Java program.
A First Simple Program
Here, we will discuss the working of a Java program by taking an example –
class Prg1 {
public static void main(String args[ ]) {
System.out.println(“Hello World!!!”); }
}
Terminologies used in the above program now –
class is the keyword to declare a class.
Prg1 is the name of the class. You can use any valid identifier for a class name.
main() is name of the method from which the program execution starts.
public is a keyword indicating the access specifier of the method. The public members can be
accessed from outside the class in which they have been declared. The main() function must be
declared as public as it needs to be called from outside the class.
static is a keyword allows main() to be called without having to instantiate a particular instance
of the class. This is necessary since main() is called by the Java Virtual Machine before any
objects are made. void indicates that main() method is not returning anything.
String args[ ]: The main() method takes an array of String objects as a command-line argument.
System is a predefined class (present in java.lang package) which gives access to the system. It
contains pre-defined methods and fields, which provides facilities like standard input, output,
etc.
out is a static final (means not inheritable) field (ie, variable)in System class which is of the type
PrintStream (a built-in class, contains methods to print the different data values). Static fields
and methods must be accessed by using the class name, so we need to use
System.out.println is a public method in PrintStream class to print the data values. After
printing the data, the cursor will be pushed to the next line (or we can say that, the data is
followed by a new line).

4|Page
Object Oriented Programming with JAVA(BCS306A) 2023

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. Once a
block of code has been created, it becomes a logical unit and can be used any place that a single
statement can. For example, a block can be a target for Java’s if and for statements.
Consider this if statement:
if(x < y) { // begin a block
x = y;
y = 0;
} // end of block
Here, if x is less than y, then both statements inside the block will be executed. The two
statements inside the block form a logical unit. By creating a block two or more statements can
be logically linked.
Example : Demonstrate a block of code.
class BlockTest {
public static void main(String args[]) {
int x, y;
y = 6;
// the target of this loop is a block
for(x = 0; x<3; x++) {
System.out.println("This is x: " + x);
System.out.println("This is y: " + y);
y = y - 2;
}
}
}
Lexical Issues
Java programs are a collection of whitespace, identifiers, literals, comments, operators,
separators, and keywords.
Whitespace: In Java, whitespace is a space, tab or newline. Usually, a space is used to separate
tokens; tab and newline are used for indentation.
Identifiers: Identifiers are used for class names, method names, and variable names. An
identifier may be any sequence of uppercase and lowercase letters, numbers, or the underscore
and dollar-sign characters. They must not begin with a number. As Java is case-sensitive, Avg is
a different identifier than avg.
Examples of valid identifiers: Avg, sum1, $x, sum_sq etc.
5|Page
Object Oriented Programming with JAVA(BCS306A) 2023

Examples of invalid identifiers: 2sum, sum-sq, x/y etc.literal. Again, Java is case-sensitive, so
VALUE is a different identifier than Value.
Literals: A constant value in Java is created by using a literal representation of it. For example,
25-an integer literal, 4.5- floating point value, ‘p’- character constant, “Hello”- string value.
Comments: Java supports 3 styles of comments
Multiline comment: this type of comment begins with /* and ends with */
Ex: /* Welcome to
Java Programming */
Single line comments: this type of comment begins with // and ends at the end of current line
Ex: // Welcome to java Programming
Documentation Comment: This type of comment is used to produce an HTML file that
documents your program. The documentation comment begins with /** and ends with */
Separators: In Java, there are a few characters that are used as separators. The most commonly
used separator in Java is the semicolon which is used to terminate statements. The separators are
shown in the following table:

Keywords: There are 50 keywords currently defined in the Java language as shown in the
following table. These keywords, combined with the syntax of the operators and separators,
form the foundation of the Java language. These keywords cannot be used as names for a
variable, class, or method.

Data Types
Java defines eight primitive (or simple) data types. They are as follows:

6|Page
Object Oriented Programming with JAVA(BCS306A) 2023

byte, short, int, long : belonging to Integers group involving whole-valued signed numbers.
char: belonging to Character group representing symbols in character set like alphabets, digits,
special characters etc.
float, double : belonging to Floating-point group involving numbers with fractional part.
boolean : belonging to Boolean group, a special way to represent true/false values.
These types can be used as primitive types, derived types (arrays) and as member of user-
defined types (classes). All these types have specific range of values irrespective of the platform
in which the program being run. In C and C++ the size of integer may vary (2 bytes or 4 bytes)
based on the platform. Because of platform-independent nature of Java, such variation in size of
data types is not found in Java.
Integers: Java defines four integer data type. byte, short, int and long. All these are signed
numbers and Java does not support unsigned numbers. The width of an integer type should not
be thought of as the amount of storage it consumes, but rather as the behavior it defines for
variables and expressions of that type. The Java run-time environment is free to use whatever
size it wants, as long as the types behave as declared them. The width and ranges of these integer
types vary widely, as shown in this table:

byte: This is the smallest integer type. Variables of type byte are especially useful when
working with a stream of data from a network or file. They are also useful for raw binary data
that may not be directly compatible with Java’s other built-in types. Byte variables are declared
by use of the byte keyword. For example: byte b, c;
short: It is probably the least-used Java type. Here are some examples of short variable
declarations: short s;
int: The most commonly used integer type is int. For example: int x;
long: It is useful for those occasions where an int type is not large enough to hold the desired
value. For example: long x;

7|Page
Object Oriented Programming with JAVA(BCS306A) 2023

Floating –Point Types


Floating-point (or real) numbers are used when evaluating expressions that require fractional
precision. Java implements the standard (IEEE–754) set of floating-point types and operators.
There are two kinds of floating-point types, float and double, which represent single and double
precision numbers, respectively. Their width and ranges are shown here:

float: The type float specifies a single-precision value that uses 32 bits of storage. Single
precision is faster on some processors and takes half as much space as double precision, but will
become imprecise when the values are either very large or very small. Variables of type float are
useful when a fractional component is needed. For example: float hightemp, lowtemp;
double: Double precision is actually faster than single precision on some modern processors that
have been optimized for high-speed mathematical calculations. All transcendental math
functions, such as sin( ), cos( ), and sqrt( ), return double values. To maintain accuracy over
many iterative calculations, or are manipulating large-valued numbers, double is the best choice.
Program: Finding area of a cirlce
class Area {
public static void main(String args[]) {
double pi, r, a;
r = 10.8;
pi = 3.1416;
a = pi * r * r;
System.out.println("Area of circle is " + a);
}
}
The output would be Area of circle is 366.436224
Characters
In Java, char is the data type used to store characters. In C or C++, char is of 8 bits, whereas in
Java it requires 16 bits. Java uses Unicode to represent characters. Unicode is a computing
industry standard for the consistent encoding, representation and handling of text expressed in
many languages of the world. The range of a char is 0 to 65,536. Though, char is designed to
store Unicode characters, we can perform arithmetic operations on them.
For example, we can add two characters (but, not char variables!!), increment/decrement
8|Page
Object Oriented Programming with JAVA(BCS306A) 2023

character variable etc.


For example: char ch1=88, ch2=’Y’;
Booleans
For storing logical values (true and false), Java provides this primitive data type. Boolean is the
output of any expression involving relational operators. For control structures (like if, for, while
etc.) we need to give boolean type. Size of a Boolean data type is JVM dependent. But, when
Boolean variable appears in an expression, Java uses 32-bit space (as int) for Boolean to
evaluate expression. For example: boolean b = false;
Variables
The variable is the basic unit of storage. A variable is defined by the combination of an
identifier, a type, and an optional initializer. In addition, all variables have a scope, which
defines their visibility, and a lifetime.
Declaring a Variable
In Java, all variables must be declared before they can be used. The basic form of a variable
declaration is shown here:
type identifier [ = value][, identifier [= value] ...] ;
The type is any of primitive data type or class or interface. The identifier is the name of the
variable. We can initialize the variable at the time of variable declaration. To declare more than
one variable of the specified type, use a comma-separated list. Examples of variable declarations
along with initialization are
int a, b=5, c;
byte z = 22;
double pi = 3.1416;
char x = '$';
Dynamic Initialization
Although the preceding examples have used only constants as initializers, Java allows variables
to be initialized dynamically, using any expression valid at the time the variable is declared. For
example: int a=5, b=4;
int c=a*2+b; //variable declaration and dynamic initialization
The key point here is that the initialization expression may use any element valid at the time of
the initialization, including calls to methods, other variables, or literals.
Type Conversion and Casting
It is quite common in a program to assign value of one type to a variable of another type. If two
9|Page
Object Oriented Programming with JAVA(BCS306A) 2023

types are compatible, Java performs implicit type conversion. For example, int to long is always
possible. But, whenever the types at two sides of an assignment operator are not compatible,
then Java will not do the conversion implicitly. For that, we need to go for explicit type
conversion or type casting.
Java’s Automatic Conversions
When one type of data is assigned to another type of variable, an automatic type conversion will
take place if the following two conditions are met:
• The two types are compatible.
• The destination type is larger than the source type.
When these two conditions are met, a widening conversion takes place. For example, the int
type is always large enough to hold all valid byte values, so no explicit cast statement is
required. For widening conversions, the numeric types, including integer and floating-point
types, are compatible with each other. However, there are no automatic conversions from the
numeric types to char or boolean. Also, char and boolean are not compatible with each other. As
mentioned earlier, Java also performs an automatic type conversion when storing a literal integer
constant into variables of type byte, short, long, or char.
Casting Incompatible Types
Although the automatic type conversions are helpful, they will not fulfill all needs. For example,
what if you want to assign an int value to a byte variable? This conversion will not be performed
automatically, because a byte is smaller than an int. This kind of conversion is sometimes called
a narrowing conversion, since you are explicitly making the value narrower so that it will fit into
the target type. To create a conversion between two incompatible types, we must use a cast. A
cast is simply an explicit type conversion. It has this general form:
(target-type) value
Here, target-type specifies the desired type to convert the specified value to. For example,
int a;
byte b;
b = (byte) a;
When a floating-point value is assigned to an integer type, the fractional component is lost. And
such conversion is called as truncation (narrowing). If the size of the whole number component
is too large to fit into the target integer type, then that value will be reduced modulo the target
type’s range.
10 | P a g e
Object Oriented Programming with JAVA(BCS306A) 2023

Automatic Type promotion in Expression


Apart from assignments, type conversion may happen in expressions also. In an arithmetic
expression involving more than one operator, some intermediate operation may exceed the size
of either of the operands. For example: byte x=25, y=80, z=50;
int p= x*y/z ;
Type Promotion Rules
Java defines several type promotion rules that apply to expressions. They are as follows:
• All byte, short, and char values are promoted to int.
• If one operand is a long, the whole expression is promoted to long.
• If one operand is a float, the entire expression is promoted to float.
• If any of the operands is double, the result is double.
Arrays
Array is a collection of related items of same data type. Many items of an array share common
name and are accessed using index. Array can be one dimensional or multi-dimensional.
One Dimensional Array
It is a list of related items. To create 1-d array, it should be declared as –
type arr_name[];
Here, type determines the data type of elements of arr_name. In Java, the above declaration will
not allocate any memory. That is, there is no physical existence for the array now. To allocate
memory, we should use new operator as follows:
arr_name=new type[size];
Here, size indicates number of elements in an array. The new keyword is used because, in Java
array requires dynamic memory allocation. The above two statements can be merged as –
type arr_name[]=new type[size];
For example, following statement create an array of 10 integers –
int arr[ ]=new int[10];
Array index starts with 0 and we can assign values to array elements as –
arr[0]=25;
arr[1]=32; and so on.
Arrays can be initialized at the time of declaration. An array initializer is a list of comma-
separated expressions surrounded by curly braces. The commas separate the values of the array
elements. The array will automatically be created large enough to hold the number of elements
11 | P a g e
Object Oriented Programming with JAVA(BCS306A) 2023

we specify in the array initializer. There is no need to use new. For example –
int arr[ ] ={1, 2, 3, 4};
The above statement creates an integer array of 4 elements.
Java strictly checks to make sure you do not accidentally try to store or reference values outside
of the range of the array. The Java run-time system will check to be sure that all array indexes
are in the correct range. If you try to access elements outside the range of the array (negative
numbers or numbers greater than the length of the array), you will get a run-time error.
Multidimensional Array
Multidimensional arrays are arrays of arrays. Here, we will discuss two dimensional arrays in
Java. The declaration of 2-d array is as follows –
type arr_name[][]=new type[row_size][col_size];
here, row_size and col_size indicates number of rows and columns of 2-d arrays. In other words,
rowsize indicates number of 1-d arrays and col_size indicates size of each of such 1-d array.
Example: Demonstration of 2-d array
class TwoDArray {
public static void main(String args[]) {
int twoD[][]= new int[3][4];
int i, j;
for(i=0; i<3; i++)
for(j=0; j<4; j++)
twoD[i][j] = i+j;
for(i=0; i<3; i++)
{
for(j=0; j<4; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}}
output
0123
1234
2345
12 | P a g e
Object Oriented Programming with JAVA(BCS306A) 2023

Instead of allocating memory for 2-day as shown in the above program, we can even do it in a
different way. We can first mention row_size and then using different statements, mention
col_size as shown below –
int twoD[][]= new int[3][];
twoD[0]=new int[4] ;
twoD[1]=new int[4] ;
twoD[2]=new int[4] ;
But, above type of allocation is not having any advantage unless we need uneven or irregular
multidimensional array. In Java, it is possible to have different number of columns for each row
in a 2-d array.
Example: Demonstration of irregular arrays
class UnevenArr {
public static void main(String args[]){
int twoD[][] = new int[3][];
twoD[0] = new int[3];
twoD[1] = new int[1];
twoD[2] = new int[5];
int i, j, k = 0;
for(i=0; i<3; i++)
for(j=0; j<twoD[i].length; j++, k++)
twoD[i][j] = k;
for(i=0; i<3; i++)
{
for(j=0; j<twoD[i].length; j++)
System.out.print(twoD[i][j] + " ");
System.out.println(); }
}
}
Here, we have declared a 2-d array with 3 rows. But, number of columns for each row varies.
The first 1-d array has 3 elements, second 1-d array as a single element and the third 1-d array
has 5 elements.

13 | P a g e
Object Oriented Programming with JAVA(BCS306A) 2023

Two dimension array can be initialized at the time of declaration as follows –


int a[ ][ ]={{1,2},{3,4} };
We can have more than 2 dimensions as –
int a[ ][ ][ ]=new int[3][2][4];
Here, the array elements can be accessed using 3 indices like a[i][ j][k].
Alternative Array Declaration Syntax
There is another way of array declaration as given below –
type[] arr_name;
That is, following two declarations are same –
int a[ ]=new int[3];
int[ ] a= new int[3];
Both the declarations will create an integer array of 3 elements. Such declarations are useful
when we have multiple array declarations of same type. For example,
int [ ] a, b, c;
will declare three arrays viz. a, b and c of type integer. This declaration is same as –
int a[ ], b[ ], c[ ];
The alternative declaration form is also useful when specifying an array as a return type for a
method.
A few words about Strings
In Java, String is a class but not array of characters. So, the features of String class can be better
understood after learning about the concepts of classes in further chapters. For the time-being,
we will glance at String type.
• We can have array of strings.
• A set of characters enclosed within double quotes can be assigned to a String variable.
• One variable of type String can be assigned another String variable.
• Object of type String can be used as an argument to println as –
String str=”Hello”;
System.out.println(str);
Introducing Type Inference with Local Variables
Java 10 introduced the concept of 'var', which allows the compiler to infer the data type of a
local variable.
var name = "John Doe"; // Compiler infers the type as String
14 | P a g e
Object Oriented Programming with JAVA(BCS306A) 2023

var age = 30; // Compiler infers the type as int


Operators
Java provides rich set of operators, mainly divided into four groups and is arithmetic, bitwise,
relational and logical.
The operands of the arithmetic operators
must be of a numeric type. We cannot use
them on Boolean types, but we can use them
on char types, since the char type in Java is a
subset of int.
• Basic arithmetic operators like +, -, *
and / behave as expected for numeric
data.
• The – symbol can be used as unary
operator to negate a variable.
• If / is operated on two integer operands, then we will get only integral part of the result
by truncating the fractional part.
• The % operator returns the remainder after division. It can be applied on integer and
floating-point types. For example,
int x=57;
double y= 32.8;
System.out.println(“on integer “ + x%10); //prints 7
System.out.println(“on double “ + y%10); //prints 2.8
• Compound assignment operators like += will perform arithmetic operation with
assignment. a+=2; a=a+2;
• Increment/decrement operators (++ and -- ) will increase/decrease the operand by 1.
a++; a=a+1; b--; b=b-1;
• The ++ and -- operators can be used either as pre-increment/decrement or postincrement/
decrement operator. For example, x= 5;
y=x++; //post increment
Now, value of x (that is 5) is assigned to y first, and x is then incremented to become 6.
x= 5;
y=++x; //pre-increment
15 | P a g e
Object Oriented Programming with JAVA(BCS306A) 2023

Now, x is incremented to 6 and then 6 is assigned to y.


NOTE that in C/C++, the % operator cannot be used on float or double and should be used only
on integer variable.
Bitwise Operators: Java defines several bitwise operators that can be applied to long, int, short,
char, and byte. These operators act upon the individual bits of their operands. They are
summarized in the following table:

Since bitwise operators manipulate the bits within the integer.


Bitwise Logical Operators: The bitwise logical operators are &, |, ^ and ~. Following table
shows the result of each operation.

Bitwise NOT: A unary NOT operator ~, also called as bitwise complement inverts all the bits of
the operand. For example, the number 42, which has the following bit pattern: 00101010
become 11010101 after the NOT operator is applied.
Bitwise AND: As the name suggests, initially, operands are converted into binary-format. Then,
the AND (&) operation is performed on the corresponding bits of operands. For example
int x=5, y=6,z;
z= x & y;

16 | P a g e
Object Oriented Programming with JAVA(BCS306A) 2023

Bitwise OR: Here, the OR (|) operations is performed on individual bit of operands. For
example
int x=5, y=6,z;
z= x | y;
Bitwise XOR:In XOR operation, if both bits are same (either both are 1 or both 0), then the
resulting bit will be 0 (false). Otherwise, the resulting bit is 1 (true). For example
int x=5, y=6,z;
z= x ^ y;

Left Shift: The left shift operator, <<, shifts all of the bits in a value to the left by a specified
number of times. It has this general form: value << num
For each shift, one higher order bit is shifted out (or lost) and extra zero is appended as the lower
order bit. Thus, for int, after 31 shifts, all the bits will be lost and result will be 0, whereas for
long, after 63 shifts, all bits will be lost.
Java’s automatic type promotions produce unexpected results when we are shifting byte and
short values. The result of such an expression is also an int. This means that the outcome of a
left shift on a byte or short value will be an int, and the bits shifted left will not be lost until they
shifted for 31 times. To avoid this problem, we should use type-casting. For example
byte a = 64, b;
int i;
i = a << 2;
b = (byte) (a << 2);// type casting
Right Shift: The right shift operator, >> shifts all of the bits in a value to the right by a specified
number of times. It has this general form: value >> num
For each shift, one lower order bit is shifted out (or lost) and extra zero is appended as the higher
order bit. For example,
int a = 35; //00100011 is the binary equivalent
a = a >> 2; // now, a contains 8
Each right shift can be thought of as dividing the number by 2. When we are shifting right, the
top (leftmost) bit is filled with the previous content of the top bit. This is called sign extension
and is needed to preserve the sign of negative numbers when you shift them right.
Unsigned Right Shift: To ignore the signbit, we can use unsigned right shift. The following
code fragment demonstrates the >>>. Here, a is set to –1, which sets all 32 bits to 1 in binary.
17 | P a g e
Object Oriented Programming with JAVA(BCS306A) 2023

This value is then shifted right 24 bits, filling the top 24 bits with zeros, ignoring normal sign
extension. This sets a to 255.
int a = -1;
a = a >>> 24;
Bitwise Operator Compound Assignment: We can use compound assignment even with
bitwise operators. That is,
a<<=2; implies a=a<<2;
a^=3; implies a=a^3; and so on.
Relational Operators
The relational operators determine the relationship that one operand has to the other.
Specifically, they determine equality and ordering. The relational operators are shown here:

The relational operators determine the relationship between two operands. Specifically, they
determine equality and ordering among operands. The outcome of these operations is a Boolean
value. Any type in Java, including integers, floating-point numbers, characters, and Booleans
can be compared using the equality test, ==, and the inequality test, !=. Only numeric types can
be compared using the ordering operators. That is, only integer, floating point, and character
operands may be compared to see which is greater or less than the other. For example, the
following code fragment is perfectly valid:
int a = 4;
int b = 1;
boolean c = a < b;
In this case, the result of a<b (which is false) is stored in c.
int flag;
………..
if(flag==1) //do some thing
Boolean Logical Operators: The Boolean logical operators shown here operate only on
18 | P a g e
Object Oriented Programming with JAVA(BCS306A) 2023

boolean operands. All of the binary logical operators combine two boolean values to form a
resultant boolean value.

The truth table is given below for few operations:

Short-Circuit Logical Operators: The short circuit AND (&&) and OR (||) operators will not
evaluate the second operand if the first is decisive. For example,
int x=0, n=5;
……..
if(x!=0 && n/x > 0)
//do something
Here, the first operand x!= 0 is false. If we use logical AND (&) then the second operand n/x>0
will be evaluated and we will get DivisionByZero Exception. So, to avoid this problem we use
&& operator which will never evaluated second operand if the first operand results into false.
It is standard practice to use the short-circuit forms of AND and OR in cases involving Boolean
logic, leaving the single-character versions exclusively for bitwise operations. However, there
are exceptions to this rule. For example, consider the following statement:
if(c==1 & e++ < 100)
d = 100;
19 | P a g e
Object Oriented Programming with JAVA(BCS306A) 2023

Here, using a single & ensures that the increment operation will be applied to e whether c is
equal to 1 or not.
Assignment operator: The assignment operator is the single equal sign, =. It has this general
form: var = expression;
Here, the type of var must be compatible with the type of expression. It allows to create a chain
of assignments. For example int x, y, z;
x = y = z = 100; // set x, y, and z to 100
The ?: Operator: Java supports ternary operator which sometimes can be used as an alternative
for if-then-else statement. The general form: var = expression1 ? expression2 : expression3;
Here, expression1 is evaluated first and it must return Boolean type. If it results true, then value
of expression2 is assigned to var, otherwise value of expression3 is assigned to var. For example
int a, b, c ;
---------
c= (a>b)?a:b; //c will be assigned with biggest among a and b
Operator Precedence: Following table describes the precedence of operators. Though
parenthesis, square brackets etc. are separators, they do behave like operators in expressions.
Operators at same precedence level will be evaluated from left to right, whichever comes first.

Control Statements
A programming language uses control statements to cause the flow of execution to advance and
branch based on changes to the state of a program. Java’s program control statements can be put
into the following categories: selection, iteration, and jump. Selection statements allow
program to choose different paths of execution based upon the outcome of an expression or the
state of a variable. Iteration statements enable program execution to repeat one or more
statements (form loops). Jump statements allow program to execute in a nonlinear fashion.
20 | P a g e
Object Oriented Programming with JAVA(BCS306A) 2023

Java’s Selection Statements


Java supports two selection statements: if and switch. These statements allow controlling the
flow of program’s execution based upon conditions known only during run time.
if Statement: The general form is
if (condition)
{
//true block
}
else
{
//false block
}
If the condition is true, then the statements written within true block will be executed, otherwise
false block will be executed. The condition should result into Boolean type. For example,
int a, b, max;
…………
if(a>b)
max=a;
else
max=b;
Nested-if Statement: A nested if is an if statement that is the target of another if or else. For
example,
if(i == 10)
{
if(j < 20)
a = b;
if(k > 100)
c = d;
else
a = c;
}
else
a = d;
The if-else-if Statement: The general form is –
if(condition1)
block1;
else if(condition2)
block2;
…………..
21 | P a g e
Object Oriented Programming with JAVA(BCS306A) 2023

else
blockn
if statements are executed from the top down. As soon as one of the conditions controlling if is
true, the block associated with that if is executed, and the rest of the ladder is bypassed. The
final else acts as a default condition; that is, if all other conditional tests fail, then the last else
statement is performed.
switch Statement: The switch statement is Java’s multi-way 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:
switch (expression)
{
case value1:
// statement sequence
break;
case value2:
// statement sequence
break;
…………....
case valueN:
// statement sequence
break;
default:
// default statement sequence
}
The expression must be of type byte, short, int, or char; each of the values specified in the case
statements must be of a type compatible with the expression. The switch statement works like
this:
The value of the expression is compared with each of the literal values in the case statements. If
a match is found, the code sequence following that case statement is executed. If none of the
constants matches the value of the expression, then the default statement is executed. However,
the default statement is optional. If no case matches and no default is present, then no further
action is taken. The break statement is used inside the switch to terminate a statement sequence.
When a break statement is encountered, execution branches to the first line of code that follows
the entire switch statement. This has the effect of jumping out of the switch. The break
statement is optional. If we omit the break, execution will continue on into the next case.
22 | P a g e
Object Oriented Programming with JAVA(BCS306A) 2023

Iteration Statements: Java’s iteration statements are for, while, and do-while.
while Loop: The general form is
while(condition)
{
//body of the 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.
do- while Loop: The general form is
do
{
//body of the loop
} while(condition);
do-while loop first executes the body of the loop and then evaluates the conditional expression.
If this expression is true, the loop will repeat. Otherwise, the loop terminates. As with all of
Java’s loops, condition must be a Boolean expression.
for Loop: The general form is
for(initialization; condition; updation)
{
// body of loop
}
When the loop first starts, the initialization portion of the loop is executed. Generally, this is an
expression that sets the value of the loop control variable, which acts as a counter that controls
the loop. It is important to understand that the initialization expression is only executed once.
Next, condition is evaluated. This must be a Boolean expression. It usually tests the loop control
variable against a target value. If this expression is true, then the body of the loop is executed. If
it is false, the loop terminates. Next, the updating portion of the loop is executed. This is usually
an expression that increments or decrements the loop control variable. The loop then iterates,
first evaluating the conditional expression, then executing the body of the loop, and then
executing the iteration expression with each pass. This process repeats until the controlling
expression is false.
for-each Loop: The for-each style of for is also referred to as the enhanced for loop. The
general form of the for-each version of the for is shown here:
for(type itr-var : collection)

23 | P a g e
Object Oriented Programming with JAVA(BCS306A) 2023

statement-block
Here, type specifies the type and itr-var specifies the name of an iteration variable that will
receive the elements from a collection, one at a time, from beginning to end. The collection
being cycled through is specified by collection. With each iteration of the loop, the next element
in the collection is retrieved and stored in itr-var. The loop repeats until all elements in the
collection have been obtained. Because the iteration variable receives values from the collection,
type must be the same as (or compatible with) the elements stored in the collection. Thus, when
iterating over arrays, type must be compatible with the base type of the array.
Consider an example –
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];
The above set of statements can be optimized as follows –
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;
for(int x: nums)
sum += x;
With each pass through the loop, x is automatically given a value equal to the next element in
nums.
Thus, on the first iteration, x contains 1; on the second iteration, x contains 2; and so on. Not
only is the syntax streamlined, but it also prevents boundary errors.
For multi-dimensional arrays:
The for-each version also works for multi-dimensional arrays. Since a 2-d array is an array of 1-
d array, the iteration variable must be a reference to 1-d array. In general, when using the for
each for to iterate over an array of N dimensions, the objects obtained will be arrays of N–1
dimensions.
Example: Demonstration of for-each version of for loop
class ForEach {
public static void main(String args[]) {
int sum = 0;
int nums[][] = new int[2][3];
// give nums some values
for(int i = 0; i < 2; i++)
for(int j=0; j < 3; j++)
nums[i][j] = (i+1)*(j+1);
24 | P a g e
Object Oriented Programming with JAVA(BCS306A) 2023

for(int x[ ] : nums) //nums is a 2-d array and x is 1-d array


{
for(int y : x) // y refers elements in 1-d array x
{
System.out.println("Value is: " +y);
sum += y;
}
}
System.out.println("Summation: " + sum);
}
}
The output would be –
Value is: 1
Value is: 2
Value is: 3
Value is: 2
Value is: 4
Value is: 6
Summation: 18
Example: Linear/Sequential Search
class SeqSearch
{
public static void main(String args[])
{
int nums[] = { 6, 8, 3, 7, 5, 6, 1, 4 };
int val = 5;
boolean found = false;
for(int x : nums)
{
if(x == val)
{
found = true;
break;
}
}
if(found)
System.out.println("Value found!");
}
}
The output would be –
Value found !
Jump Statements: Java supports three jump statements: break, continue, and return. These
25 | P a g e
Object Oriented Programming with JAVA(BCS306A) 2023

statements transfer control to another part of your program.


Using break
In java, break can be used in 3 different situations:
• To terminate statement sequence in switch
• To exit from a loop
• Can be used as a civilized version of goto
Following is an example showing terminating a loop using break.
for (int i=0;i<20;i++)
if(i==5)
break;
else
System.out.println(“ i= “ + i);
The above code extract prints value from 0 to 4 and when i become 5, the loop is terminated.
Using break as a form of goto: Java does not have a goto statement because it is an un-
conditional jump and may end up with an infinite loop. But in some situations, goto will be
useful. For example, the goto can be useful when we are exiting from a deeply nested set of
loops. To handle such situations, Java defines an expanded form of the break statement. By
using this form of break, we can, for example, break out of one or more blocks of code. These
blocks need not be part of a loop or a switch. They can be any block. Break gives the benefits of
a goto without its problems. The general form of labeled break is:
break label;
Example: Illustration of break statement with labels
class Break {
public static void main(String args[]) {
boolean t = true;
first:
{
second:
{
third:
{
System.out.println("Before the break.");
if(t)
break second; // break out of second block
System.out.println("This won't execute");
26 | P a g e
Object Oriented Programming with JAVA(BCS306A) 2023

}
System.out.println("This won't execute");
}
System.out.println("This is after second block.");
}
}
}
The output would be
Before the break
This is after second block
In the above program, the usage of break with a label takes the control out of the second block
directly.
Using continue: Sometimes, we may need to proceed towards next iteration in the loop by
leaving some statements. In such situations, we can use continue statement within for, while and
do-while. For example
for (int i=1; i<20;i++)
if (i%2 == 0)
continue;
else
System.out.println(“i = “ + i);
The above code extract prints only the odd numbers in the range of 1 to 20.
Using return: The return statement is used to explicitly return the method. Based on some
condition, we may need to go back to the calling method sometimes. So, we can use return in
such situations.

Question Bank:
1. Explain key attributes of Java programming language.
2. What is JVM? Why do we need it?
3. Briefly explain JRE and JDK.
4. Explain three OOPs principles.
5. What are Keywords and Identifiers? List the rules to write an identifier.
6. Discuss various data types used in Java.
7. What is type Conversion and Casting? Explain automatic type promotion in expressions

27 | P a g e
Object Oriented Programming with JAVA(BCS306A) 2023

with rules and a demo program.


8. Explain scope and lifetime of variables with suitable examples.
9. Java is a strongly typed language - Justify this statement.
10. Write a note on
a. Java class libraries
b. Literals
11. Explain array declaration and initialization in Java with suitable examples.
12. What are multi-dimensional arrays? Explain with examples.
13. What are irregular arrays in Java? Write a program to find biggest of numbers in an
irregular array with at least three rows.
14. What are different types of operators in Java? Explain any two of them.
15. Discuss ternary operator with examples.
16. Differentiate >> and >>> with suitable examples.
17. Briefly explain short-circuit logical operators with examples.
18. Explain different types of iteration statements with examples.
19. Discuss various selective control structures.
20. Write a note on jump statements in Java.
21. Discuss different versions of for - loop with examples.
22. Write a program to illustrate break statement with labels.

28 | P a g e

You might also like