[Go to site: main page, start]

0% found this document useful (0 votes)
9 views55 pages

Java Object-Oriented Programming Basics

The document outlines the syllabus for an Object Oriented Programming course with Java, covering key concepts such as data types, control statements, and the principles of OOP including encapsulation, inheritance, and polymorphism. It explains the importance of abstraction in programming and provides examples of Java syntax and structure, including comments, class definitions, and control flow mechanisms. Additionally, it discusses Java's primitive types, operators, and lexical issues, emphasizing the language's strong typing and the use of built-in class libraries.

Uploaded by

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

Java Object-Oriented Programming Basics

The document outlines the syllabus for an Object Oriented Programming course with Java, covering key concepts such as data types, control statements, and the principles of OOP including encapsulation, inheritance, and polymorphism. It explains the importance of abstraction in programming and provides examples of Java syntax and structure, including comments, class definitions, and control flow mechanisms. Additionally, it discusses Java's primitive types, operators, and lexical issues, emphasizing the language's strong typing and the use of built-in class libraries.

Uploaded by

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

Object Oriented Programming with JAVA (BCS306A)

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).
Chapter 2, 3, 4, 5

Two Programming Paradigms (methodologies)


● All computer programs consist of two elements: code and data.
● A program can be conceptually organized around its code or around its
data.

1. Process-oriented model.
● This approach characterizes a program as a series of linear steps
(that is, code).
● The process-oriented model can be thought of as code acting on
data.
● Procedural languages such as C use this model to considerable
success.
● This approach cannot be used if programs grow larger and complex.

2. Object-oriented programming.
● Object-oriented programming organizes a program around its data
(that is, objects) and a set of well-defined interfaces to that data.
● An object-oriented program can be characterized as data controlling
access to code.
Abstraction

[Link] R, CSE Dept


1
Object Oriented Programming with JAVA (BCS306A)

Abstraction in Java is the process in which we only show essential details /


functionality to the user. The non-essential implementation details are not
displayed to the user.

For example, people do not think of a car as a set of tens of thousands of


individual parts. They think of it as a well-defined object with its own
unique behaviour. This abstraction allows people to use a car to drive to
the grocery store without being overwhelmed by the complexity of the
individual parts. They can ignore the details of how the engine,
transmission, and braking systems work. Instead, they are free to utilize
the object as a whole.
The Three OOP Principles
● Encapsulation, Inheritance, and Polymorphism
Encapsulation
● Encapsulation is the mechanism that binds together code and the
data and keeps both safe from outside interference and misuse.
● Encapsulation is a protective wrapper that prevents the code and data
from being accessed by other code defined outside the wrapper.
● Access to the code and data inside the wrapper is tightly controlled
through a well-defined interface.
● In Java, encapsulation is achieved by the class.
● A class defines the structure and behaviour (data and code) that will
be shared by a set of objects.
● Each object of a given class contains the structure and behaviour
defined by the class.
● Objects are sometimes referred to as instances of a class.
● The code and data that constitute a class is called members of the
class.
● Data defined by the class are referred to as member variables.
● The code that operates on that data is referred to as methods.
● Data hiding in a class is achieved by marking method or variable by
private or public.
● The public interface of a class represents everything that external
users of the class need to know.
● The private methods and data can only be accessed by code that is a
member of the class.

[Link] R, CSE Dept


2
Object Oriented Programming with JAVA (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.
● Knowledge is made manageable by hierarchical (that is, top-down)
classifications.
● For example, a Golden Retriever is part of the classification dog, which
in turn is part of the mammal class, which is under the larger class
animal.

[Link] R, CSE Dept


3
Object Oriented Programming with JAVA (BCS306A)

● Without the use of hierarchies, each object would need to define all its
characteristics explicitly.
● However, by use of inheritance, an object need only define those
qualities that make it unique within its class. It can inherit its general
attributes from its parent.
Polymorphism (many forms)
● Polymorphism is a feature that allows one interface to be used for a
general class of actions.
● The specific action is determined by the exact nature of the situation.
● Extending 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. The difference is what is being smelled, that is,
the type of data being operated upon by the dog’s nose!
● This same general concept can be implemented in Java as it applies to
methods within a Java program.

A First Simple Program

[Link] R, CSE Dept


4
Object Oriented Programming with JAVA (BCS306A)

Comments:
● The contents of a comment are ignored by the compiler.
● A comment describes or explains the operation of the program to
anyone who is reading its source code.
● Example: /* Simple Java Program */

public class Sample


● The keyword class is used to declare that a new class is being defined.
● Sample is an identifier that is the name of the class.
● The entire class definition, including all of its members, will be between
the opening curly brace ({) and the closing curly brace (}).
public static void main(String[] args) {
● This line begins the main( ) method.
● This is the line at which the program will begin executing.
● A Java program begins execution by calling main( ).
● The public keyword is an access modifier, which allows the
programmer to control the visibility of class members.
● When a class member is preceded by public, then that member may
be accessed by code outside the class in which it is declared.
● In this case, main( ) must be declared as public, since it must be
called by code outside of its class when the program is started.
● The keyword static 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.

[Link] R, CSE Dept


5
Object Oriented Programming with JAVA (BCS306A)

● The keyword void simply tells the compiler that main( ) does not
return a value.
● String[ ] args declares a parameter named args, which is an array of
instances of the class String.
[Link]("Hello World");
● This line outputs the string "Hello World." followed by a new line on the
screen. Output is actually accomplished by the built-in println( )
method. In this case, println( ) displays the string which is passed to
it.

A Second Short Program

[Link]("This is num: " + num);


● In this statement, the plus sign causes the value of num to be
appended to the string that precedes it, and then the resulting string is
output.
● Actually, num is first converted from an integer into its string
equivalent and then concatenated with the string that precedes it.

Control Statements

[Link] R, CSE Dept


6
Object Oriented Programming with JAVA (BCS306A)

The if Statement
● The Java if statement determines the flow of execution based on
whether some condition is true or false.
● Its syntax is here:
if (condition) statement;
● Here, condition is a Boolean expression.
● If condition is true, then the statement is executed. If condition is false,
then the statement is bypassed.
● Example:
If (num < 100) [Link]("num is less than 100");
● In this case, if num contains a value that is less than 100, the
conditional expression is true, and println( ) will execute. If num
contains a value greater than or equal to 100, then the println( )
method is bypassed.
Java relational operators which may be used in a conditional
expression.
Operator Meaning
< Less than
> Greater than
== Equal to

[Link] R, CSE Dept


7
Object Oriented Programming with JAVA (BCS306A)

The for Loop


● Loop statements provide a way to repeatedly execute some tasks.
● The syntax of the for loop is here:
for (initialization; condition; iteration)
statement;
● The initialization portion of the loop sets a loop control variable to an
initial value.
● The condition is a Boolean expression that tests the loop control
variable.
● If the outcome of that test is true, statement executes and the for loop
continues to iterate. If it is false, the loop terminates.
● The iteration expression determines how the loop control variable is
changed each time the loop iterates.

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.

[Link] R, CSE Dept


8
Object Oriented Programming with JAVA (BCS306A)

● Once a block of code has been created, it becomes a logical unit that
can be used any place that a single statement can.
● A block can be a target for Java’s if and for statements.
● Block for the if statement:

if(x < y)
{ // begin a block
x = y;
y = 0;
} // end of block

Lexical Issues
● Java programs are a collection of whitespaces, identifiers, literals,
comments, operators, separators, and keywords.
Whitespace
● Java is a free-form language.
● This means that you do not need to follow any special indentation
rules.
● In Java, whitespace includes a space, tab, newline, or form feed.
Identifiers (Variables)
● Identifiers are used to name things, such as classes, variables, and
methods.
● An identifier may be any sequence of uppercase and lowercase letters,
numbers.

[Link] R, CSE Dept


9
Object Oriented Programming with JAVA (BCS306A)

● No special characters except the underscore and dollar-sign


characters.
● They must not begin with a number.
● No keyword
● Java is case-sensitive, so VALUE is a different identifier than Value.

Examples of valid identifiers :


AvgTemp count a4 $test this_is_ok
Examples of Invalid identifiers are :

2count high- Not/ok


temp

Literals (Constants)
● A constant value in Java is created by using a literal representation of
it.
For example:
100 98.6 ‘X’ “This is a test”

Comments in Java
● single-line : // single line comment
● multiline : / * This is multiline comment */
● documentation comment : /** Documentation Comment */
This type of comment is used to produce an HTML file that documents
your program.
Separators
● The most commonly used separator in Java is the semicolon.
● All separators are shown in the following table:

[Link] R, CSE Dept


10
Object Oriented Programming with JAVA (BCS306A)

The Java Keywords


● There are 67 keywords in the Java.
● Keywords cannot be used as identifiers, meaning that they cannot be
used as names for a variable, class, or method.
● The keywords const and goto are reserved but not used.

The Java Class Libraries


● The Java environment depends on several built-in class libraries that
contain many built-in methods that provide support for such things as
I/O, string handling, networking, and graphics.

[Link] R, CSE Dept


11
Object Oriented Programming with JAVA (BCS306A)

● Thus, Java as a totality is a combination of the Java language itself, plus


its standard classes.
● Example : print(), println()
Java Is a Strongly Typed Language
● Every variable has a type, every expression has a type, and every type
is strictly defined.
● All assignments, whether explicit or via parameter passing, are
checked for type compatibility.
● There are no automatic conversions of conflicting types.
● The Java compiler checks all expressions and parameters to ensure
that the types are compatible.
● Any type mismatches are errors that must be corrected before the
compiler will finish compiling the class.
The Primitive Types
● Java defines eight primitive types of data, these can be put in four
groups:
● Integers This group includes byte, short, int, and long, which are for
whole-valued signed numbers.
● Floating-point numbers This group includes float and double,
which represent numbers with fractional precision.
● Characters 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.
Integers
● Java defines four integer types: byte, short, int, and long.
● All of these are signed, positive and negative values.
● Java does not support unsigned, positive-only integers.
● The width and ranges of these integer types vary widely, as shown in
this table:

byte
● The smallest integer type is byte.

[Link] R, CSE Dept


12
Object Oriented Programming with JAVA (BCS306A)

● This is a signed 8-bit type that has a range from –128 to 127.
● Declaration : byte x, y ;

Floating-Point Types
● Floating-point numbers, also known as real numbers,
● Used when evaluating expressions that require fractional precision.
● Width and ranges are shown here:

float
● The type float specifies a single-precision value that uses 32 bits of
storage.
● For example, float can be useful when representing dollars and cents.
● Declaration : float hightemp, lowtemp;

double
● Double precision, uses 64 bits to store a value.
● double is the best choice, when need to maintain accuracy over many
iterative calculations, or manipulate large-valued numbers.

[Link] R, CSE Dept


13
Object Oriented Programming with JAVA (BCS306A)

Characters
● In Java, the data type used to store characters is char.
● Java uses Unicode to represent characters.
● In Java char is a 16-bit type. The range of a char is 0 to 65,535.
● There are no negative chars.

Booleans
● boolean used for logical values.
● It can have only one of two possible values, true or false.

Integer Literals (Integer constant)


● Any whole number is an integer literal.
● Examples are 1, 2, 3, and 42 (decimal values: base 10)
● Two other bases that can be used in integer literals are octal (base 8)
and hexadecimal (base 16).
● Examples : 06 – Octal (Octal values are denoted by a leading zero)
0xA5 – Hexadecimal (hexadecimal constant with a
leading zero-x)

Floating-Point Literals
● Decimal values with a fractional component.
● They can be expressed in either standard or scientific notation.

[Link] R, CSE Dept


14
Object Oriented Programming with JAVA (BCS306A)

● Standard notation consists of a whole number component followed by a


decimal point followed by a fractional component.
o For example, 2.0, 3.14159, and 0.6667
● Scientific notation uses a standard-notation, floating-point number plus
a suffix that specifies a power of 10 by which the number is to be
multiplied.
● The exponent is indicated by an E or e followed by a decimal number,
which can be positive or negative.
o Examples include 6.022E23, 314159E–05, and
2e+100

Boolean Literals
● Only two logical values that a boolean value can have, true and
false.
● The values of true and false do not convert into any numerical
representation.

Character Literals
● Java uses the Unicode character set.
● A literal character is represented inside a pair of single quotes.
● All of the visible ASCII characters can be directly entered inside the
quotes, such as 'a', 'z', and '@'.
● For characters that are impossible to enter directly, there are several
escape sequences that allow you to enter the character you need, such
as ' \' ' for the single-quote character itself and ' \n' for the newline
character.

[Link] R, CSE Dept


15
Object Oriented Programming with JAVA (BCS306A)

String Literals
● String literals are sequence of characters between a pair of double
quotes.
● Examples: "Hello World"
"two\nlines"
“\"This is in quotes\""
Variables
● Variable is a basic unit of storage.
● A variable is defined by the combination of an identifier, a type, and an
optional initializer.
Declaring a variable
● In Java, all variables must be declared before they can be used.
The syntax :
type identifier [ = value ][, identifier [= value ] … ] ;

Examples:
int a, b, c; // declares three ints, a, b, and c.
int d = 3, e, f = 5; // declares three more ints, initializing d and
f.
byte z = 22; // initializes z.
double pi = 3.14159; // declares an approximation of pi.
char x = 'x'; // the variable x has the value 'x'.
Dynamic Initialization
● Java allows variables to be initialized dynamically, using any expression
valid at the time the variable is declared.
● For example, Program to computes the length of the hypotenuse of a
right triangle given the lengths of its two opposing sides:

[Link] R, CSE Dept


16
Object Oriented Programming with JAVA (BCS306A)

The Scope and Lifetime of Variables


● Java allows variables to be declared within any block.
● A block begins with an opening curly brace and ended by a closing
curly brace.
● A block defines a scope.
● A scope determines what objects are visible to other parts of in a
program. It also determines the lifetime of those objects.
● There are two scopes: global and local.
● In Java, the two major scopes are those defined by a class and those
defined by a method.
● The class scope has several unique properties and attributes that do
not apply to the scope 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.
● A variable declared within a block is called a local variable.
● Scopes can be nested. Objects declared in the outer scope will be
visible to code within the inner scope. However, the reverse is not true.
● Objects declared within the inner scope will not be visible outside it.
Example:

[Link] R, CSE Dept


17
Object Oriented Programming with JAVA (BCS306A)

Lifetime of a variable
● Variables are created when their scope is entered, and destroyed when
their scope is left.
● This means that a variable will not hold its value once it has gone out
of scope.
● Also, a variable declared within a block will lose its value when the
block is left.
● Thus, the lifetime of a variable is confined to its scope.
Example:

[Link] R, CSE Dept


18
Object Oriented Programming with JAVA (BCS306A)

Type Conversion and Casting


● Process of converting one data type to another is called type
conversion.
● If the two types are compatible, then Java will perform the conversion
automatically called implicit conversion.
● For example, it is always possible to assign an int value to a long
variable.
● There is no automatic conversion defined from double to byte.
● But it is possible to obtain a conversion between incompatible types
using cast, which performs an explicit conversion.

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 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.

[Link] R, CSE Dept


19
Object Oriented Programming with JAVA (BCS306A)

Casting Incompatible Types


● Automatic type conversions are helpful, they will not fulfil 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.
● A different type of conversion will occur when a floating-point value is
assigned to an integer type: truncation.
● For example, if the value 1.23 is assigned to an integer, the resulting
value will simply be 1. The 0.23 will have been truncated.

Arrays
● An array is a group of data items of same type under 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.
● Arrays helps to group related information.

[Link] R, CSE Dept


20
Object Oriented Programming with JAVA (BCS306A)

One-Dimensional Arrays
● A one-dimensional array is, essentially, a list of data items of same
type.
● Creation of Array in Java is a two steps process as described below:
● Syntax to create an array in java :
type[ ] var-name;
Example :
int[ ] month_days ;
● Above declaration shows the fact that month_days is an array
variable, no array actually exists.
● To link month_days with an actual, physical array of integers, you
must allocate one using new and assign it to month_days.
● new is a special operator that allocates memory.
● The syntax of new as it applies to one-dimensional arrays appears as
follows:
array-var = new type [size];
Example :
month_days = new int[12];
● All elements in the array will be initialized to zero.
● We can access a specific element in the array by specifying its index
within square brackets.
● All array indexes start at zero.
For example, (1) Assign the value 28 to the second element of
month_days:
month_days[1] = 28;
(2) Displays the value stored at index 3:
[Link](month_days[3]);
// Demonstrate a one-dimensional array.
public class Array
{
public static void main(String[] args)
{
int[ ] month_days;
month_days = new int[12];

month_days[0] = 31;
month_days[1] = 28;

[Link] R, CSE Dept


21
Object Oriented Programming with JAVA (BCS306A)

month_days[2] = 31;
month_days[3] = 30;
month_days[4] = 31;
month_days[5] = 30;
month_days[6] = 31;
month_days[7] = 31;
month_days[8] = 30;
month_days[9] = 31;
month_days[10] = 30;
month_days[11] = 31;
[Link]("April has " + month_days[3] + " days.");
}
}

Array Initialisation:

● Arrays can be initialized when they are declared.


● There is no need to use new operator here.

// An improved version of the previous program.


public 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.");


}
}

//Another Example:
// Program to find the average of a set of numbers.
public class Average
{
public static void main(String[] args)
{
double[ ] nums = {10.1, 11.2, 12.3, 13.4, 14.5};
double result = 0;
int i;

for(i=0; i<5; i++)


result = result + nums[i];
[Link]("Average is " + result / 5);
}
}

Multidimensional Arrays:

[Link] R, CSE Dept


22
Object Oriented Programming with JAVA (BCS306A)

● In Java, multidimensional arrays are implemented as arrays of arrays

Example for declaration of a two-dimensional array called twoD:

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

● This allocates a 4 by 5 array and assigns it to twoD. Internally, this


matrix is implemented as an array of arrays of int.

// Demonstrate a two-dimensional array.


public 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] + " ");
[Link]();
}
}

[Link] R, CSE Dept


23
Object Oriented Programming with JAVA (BCS306A)

Output :

0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
15 16 17 18 19

Two Dimensional Array Initialisation:

// Initialize a two-dimensional array.


public class Matrix
{
public static void main(String[] args)
{
double[ ][ ] m = {
{ 0*0, 1*0, 2*0, 3*0 },
{ 0*1, 1*1, 2*1, 3*1 },
{ 0*2, 1*2, 2*2, 3*2 },
{ 0*3, 1*3, 2*3, 3*3 }
};
int i, j;

for(i=0; i<4; i++)


{
for(j=0; j<4; j++)
[Link](m[i][j] + " ");
[Link]();
}
}
}

Output:

0.0 0.0 0.0 0.0


0.0 1.0 2.0 3.0
0.0 2.0 4.0 6.0
0.0 3.0 6.0 9.0

Alternative Array Declaration Syntax

● There is a second form that may be used to declare an array:

type var-name[ ];

[Link] R, CSE Dept


24
Object Oriented Programming with JAVA (BCS306A)

● Here, the square brackets follow the array variable name, and not the
type specifier.
● For example, the following two declarations are equivalent:

int a[ ] = new int[3];


int[ ] b = new int[3];

● The following declarations are also equivalent:

char x[ ][ ] = new char[3][4];


char[ ][ ] y = new char[3][4];
Java Strings:

● String is neither a primitive data-type nor simply an array of


characters.
● String defines an object.
● The String type is used to declare string variables.
● You can also declare arrays of strings.
● A quoted string constant can be assigned to a String variable.
● A variable of type String can be assigned to another variable of type
String.

Example:

String str = "this is a test";


[Link](str);

Here, str is an object of type String. It is assigned the string "this is a


test". This string is displayed by the println( ) statement.

Operators

Most of java’s operators can be divided into the following four groups:
arithmetic, bitwise, relational, and logical.

Arithmetic Operators

[Link] R, CSE Dept


25
Object Oriented Programming with JAVA (BCS306A)

Example:

// Demonstrate the basic arithmetic operators.


class BasicMath
{
public static void main(String[] args)
{
[Link]("Integer Arithmetic");
int a = 1 + 1;
int b = a * 3;
int c = b / 4;
int d = c - a;
int e = -d;
[Link]("a = " + a);
[Link]("b = " + b);
[Link]("c = " + c);
[Link]("d = " + d);
[Link]("e = " + e);

[Link]("Floating Point Arithmetic");


double da = 1 + 1;
double db = da * 3;
double dc = db / 4;
double dd = dc - a;
double de = -dd;
[Link]("da = " + da);
[Link]("db = " + db);

[Link] R, CSE Dept


26
Object Oriented Programming with JAVA (BCS306A)

[Link]("dc = " + dc);


[Link]("dd = " + dd);
[Link]("de = " + de);
}
}

Output:
Integer Arithmetic
a=2
b=6
c=1
d = -1
e=1
Floating Point Arithmetic
da = 2.0
db = 6.0
dc = 1.5
dd = -0.5
de = 0.5

The Modulus Operator


● The modulus operator, %, returns the remainder of a division
operation.
● It can be applied to floating-point types as well as integer types.

// Demonstrate the % operator.


class Modulus
{
public static void main(String[] args)
{
int x = 42;
double y = 42.25;
[Link]("x mod 10 = " + x % 10);
[Link]("y mod 10 = " + y % 10);
}
}

Output:
x mod 10 = 2
y mod 10 = 2.25

Arithmetic Compound Assignment Operators


● It’s a combination of an arithmetic operation with an assignment.

Following two statements are equal:

[Link] R, CSE Dept


27
Object Oriented Programming with JAVA (BCS306A)

a = a + 4;
a += 4;

● Advantages : They save you a bit of typing, and in some cases, they
are more efficient than are their equivalent long forms.

// Demonstrate several assignment operators.


class OpEquals
{
public static void main(String[] args)
{
int a = 1;
int b = 2;
int c = 3;
a += 5;
b *= 4;
c += a * b;
c %= 6;
[Link]("a = " + a);
[Link]("b = " + b);
[Link]("c = " + c);
}
}
Output:
a=6
b=8
c=3

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.

Example:
x = x + 1;
can be rewritten like this by use of the increment operator:
x++;

Similarly, this statement:


x = x - 1;
is equivalent to
x--;

● These operators can appear both in postfix form and prefix form.

// Demonstrate ++.

[Link] R, CSE Dept


28
Object Oriented Programming with JAVA (BCS306A)

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
The Bitwise Operators

● 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.

[Link] R, CSE Dept


29
Object Oriented Programming with JAVA (BCS306A)

The Bitwise Logical Operators

● The following table shows the outcome of Bitwise each operation.


● The bitwise operators are applied to each individual bit within each
operand.

The Bitwise NOT

For example, the number 42, which has the following bit pattern:
00101010
becomes
11010101
after the NOT operator is applied
The Bitwise AND:

The Bitwise OR:

The Bitwise XOR:

[Link] R, CSE Dept


30
Object Oriented Programming with JAVA (BCS306A)

// Demonstrate the bitwise logical operators.


class BitLogic
{
public static void main(String[] args)
{
int a = 3; // 0011 in binary
int b = 6; // 0110 in binary
int c = a | b;
int d = a & b;
int e = a ^ b;
int f = (~a & b)|(a & ~b);
int g = ~a & 0x0f;
[Link](" a = " + a);
[Link](" b = " + b);
[Link](" c = " + c);
[Link](" d = " + d);
[Link](" e = " + e);
[Link](" f = " + f);
[Link](" g = " + g);
}
}

The Left Shift:

● The left shift operator, <<, shifts all of the bits in a value to the left a
specified number of times.
● Each left shift has the effect of doubling the original value

// Left shifting a byte value.


class ByteShift
{
public static void main(String[] args)
{
byte a = 64, b;
int i;
i = a << 2;
b = (byte) (a << 2);
[Link]("Original value of a: " + a);
[Link]("i and b: " + i + " " + b);
}
}

Output:
Original value of a: 64
i and b: 256 0

[Link] R, CSE Dept


31
Object Oriented Programming with JAVA (BCS306A)

Since a is promoted to int for the purposes of evaluation, left-shifting the


value 64 (0100 0000) twice results in i containing the value 256 (1 0000
0000). However, the value in b contains 0 because after the shift, the low-
order byte is now zero. Its only 1 bit has been shifted out.

The Right Shift:


● The right shift operator, >>, shifts all of the bits in a value to the right
a specified number of times.
● Each time you shift a value to the right, it divides that value by two

// Right shifting
class RightShift
{
public static void main(String[] args)
{
int a = 32; // 0010 0000
a = a >> 2; // 0000 1000
[Link](a);

a= 35; // 0010 0011


a = a >> 2; // 0000 1000
[Link](a);
}
}
Output:
8
8

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 used in the expressions that contains
control and loop statements.

[Link] R, CSE Dept


32
Object Oriented Programming with JAVA (BCS306A)

Boolean Logical Operators:

● The Boolean logical operators shown here operate only on boolean


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

// Demonstrate the boolean logical operators.


class BoolLogic
{
public static void main(String[] args)
{
boolean a = true;
boolean b = false;
boolean c = a | b;
boolean d = a & b;
boolean e = a ^ b;
boolean f = (!a & b) | (a & !b);
boolean g = !a;
[Link](" a = " + a);
[Link](" b = " + b);
[Link](" a|b = " + c);
[Link](" a&b = " + d);
[Link](" a^b = " + e);
[Link]("!a&b|a&!b = " + f);
[Link](" !a = " + g);
}
}

[Link] R, CSE Dept


33
Object Oriented Programming with JAVA (BCS306A)

Output:

The Assignment Operator:

● The assignment operator is the single equal sign, =.


Syntax:
var = expression;
Here, the type of var must be compatible with the type of
expression.

Example :
int x, y, z;
x = 100;
y = z = 100; // set x, y, and z to 100

The ? Operator

● It is a ternary (three-way) operator that can replace certain types of if-


else
statements.
Syntax:

expression1 ? expression2 : expression3

● expression1 can be any expression that evaluates to a Boolean value.


● If expression1 is true, then expression2 is evaluated; otherwise,
expression3 is evaluated.

Example :
x = (y == 0) ? 0 : y / 2;

// Demonstrate ?.
class Ternary
{
public static void main(String[] args)
{
int i, k;
i = 10;
k =( i < 0 ) ? -i : i;
[Link]("Absolute value of "+ i + " is " + k);

[Link] R, CSE Dept


34
Object Oriented Programming with JAVA (BCS306A)

}
}

Output:

Absolute value of 10 is 10

Operator Precedence

● Operator precedence refers to the rules that control the order in which
operations are performed in an expression without parentheses.
● Parentheses raise the precedence of the operations that are inside
them. This is often necessary to obtain the result you desire.

Control Statements

● Control statements are used to specify the order of execution of


instructions in a program.

[Link] R, CSE Dept


35
Object Oriented Programming with JAVA (BCS306A)

● Control statements are used to create special feature like logical tests,
loops and branching.
● Java has 3 types of control statements: selection, iteration, and jump.
● Selection (Conditional) statements allow your program to choose
different paths of execution based upon the outcome of an expression.
● Iteration(Looping) statements enable program execution to repeat one
or more statements. (loop)
● Jump statements allow your program to execute in a nonlinear fashion.

Selection Statements

if , if-else, switch
if

● Used to route program execution through two different paths.

Syntax:
if (condition)
statement1;
else
statement2;
● Here, each statement may be a single statement, or a compound
statement enclosed in curly braces (that is, a block).
● The condition is any expression that returns a Boolean value.
● The else clause is optional.
● If the condition is true, then statement1 is executed. Otherwise,
statement2 (if it exists) is executed.

Nested ifs

● A nested if is an if statement that is the within another if or else.

Example:
if(i == 10)
{
if(j < 20)
a = b;
if(k > 100)
c = d;
else
a = c;
}
else
a = d;

The if-else-if Ladder

[Link] R, CSE Dept


36
Object Oriented Programming with JAVA (BCS306A)

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

// Demonstrate if-else-if statements.


class IfElse
{
public static void main(String[] args)
{
int month = 4;
String season;
if(month == 12 || month == 1 || month == 2)
season = "Winter";
else if(month == 3 || month == 4 || month == 5)
season = "Spring";
else if(month == 6 || month == 7 || month == 8)
season = "Summer";
else if(month == 9 || month == 10 || month ==
11)
season = "Autumn";
else
season = "Bogus Month";
[Link]("April is in the " + season + ".");
}
}

Output:
April is in the Spring.

The switch statement:

● The switch statement is a multiway branch statement.


● It provides an alternative for a large series of if-else-if statements.

Syntax:
switch (expression)
{
case value1:

[Link] R, CSE Dept


37
Object Oriented Programming with JAVA (BCS306A)

// statement sequence
break;
case value2:
// statement sequence
break;
.
.
.
case valueN :
// statement sequence
break;
default:
// default statement sequence
}

The switch statement works like this: The value of the expression is
compared
with each of the 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.

● The break statement is used inside the switch to terminate a


statement sequence.
// A simple example of the switch.
class SampleSwitch
{
public static void main(String[] args)
{
for(int i=0; i<6; i++)
{
switch(i)
{
case 0:
[Link]("i is zero.");
break;
case 1:
[Link]("i is one.");
break;
case 2:
[Link]("i is two.");
break;
case 3:
[Link]("i is three.");
break;
default:
[Link]("i is greater than
3.");

[Link] R, CSE Dept


38
Object Oriented Programming with JAVA (BCS306A)

}
}
}
}

Output:

i is zero.
i is one.
i is two.
i is three.
i is greater than 3.
i is greater than 3.

// An improved version of the season program.


class Switch
{
public static void main(String[] args)
{
int month =4;
String season;
switch (month)
{
case 12:
case 1:
case 2:
season = "Winter";
break;
case 3:
case 4:
case 5:
season = "Spring";
break;
case 6:

[Link] R, CSE Dept


39
Object Oriented Programming with JAVA (BCS306A)

case 7:
case 8:
season = "Summer";
break;
case 9:
case 10:
case 11:
season = "Autumn";
break;
default:
season = "Bogus Month";
}
[Link]("April is in the " + season + ".");
}
}

Iteration Statements (loop statements)

● Java’s iteration statements are for, while, and do-while.


● A loop repeatedly executes the set of instructions until a termination
condition is met.

While
● It repeats a statement or block while its controlling expression is true.

Syntax:

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.

// Demonstrate the while loop.


class While

[Link] R, CSE Dept


40
Object Oriented Programming with JAVA (BCS306A)

{
public static void main(String[] args)
{
int n = 10;
while(n > 0)
{
[Link]("tick " + n);
n--;
}

}
}

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

do-while

● It is a bottom tested loop.


● Sometimes it is desirable to execute the body of a loop at least once,
even if the conditional expression is false to begin with.
● The do-while loop always executes its body at least once, because its
conditional expression is at the bottom of the loop.

● The do-while loop is especially useful when you process a menu


selection, because you will usually want the body of a menu loop to
execute at least once.

Syntax:
do {
// body of loop
} while (condition);

// Using a do-while to process a menu


import [Link];

[Link] R, CSE Dept


41
Object Oriented Programming with JAVA (BCS306A)

class Menu
{
public static void main(String[] args)
{
int choice;
Scanner sc = new Scanner([Link]);
do
{
[Link]("Help on:....... ");
[Link](" 1. Withdraw Money");
[Link](" 2. Deposit Money");
[Link](" 3. Balance Print");
[Link](" 4. New Account");
[Link](" 5. Update Account");
[Link]("ENTER YOUR CHOICE:");
choice = [Link]();
} while( choice < 1 || choice > 5);

switch(choice)
{
case 1:
[Link]("Spend your money wisely");
break;
case 2:
[Link]("Good Job, save your money\
n");
break;
case 3:
[Link]("Take a print\n");
break;
case 4:
[Link]("Visit the Bank to open new
account");
break;
case 5:
[Link]("Visit the Bank to upadte ");
break;
}
}
}

for

Syntax:

for(initialization; condition; iteration)


{

[Link] R, CSE Dept


42
Object Oriented Programming with JAVA (BCS306A)

// body
}

The for loop operates as follows.


● When the loop first starts, the initialization expression of the loop is
executed.
● Initialization expression that sets the value of the loop control variable,
which acts as a counter that controls the loop.
● The initialization expression is executed only once.
● Next, condition is evaluated. This must be a Boolean expression.
● If this expression is true, then the body of the loop is executed. If it is
false, the loop terminates.
● Next, the iteration 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.

// Demonstrate the for loop.


class ForTick
{
public static void main(String[] args)
{
int n;
for(n=10; n>0; n--)
[Link]("tick " + n);
}
}

// Test for primes.


class FindPrime
{
public static void main(String[] args)
{
int num;
boolean isPrime;
num = 14;
if(num < 2)
isPrime = false;
else
isPrime = true;

for(int i=2; i <= num/i; i++)


{
if((num % i) == 0)

[Link] R, CSE Dept


43
Object Oriented Programming with JAVA (BCS306A)

{
isPrime = false;
break;
}
}
if(isPrime)
[Link]("Prime");
else
[Link]("Not Prime");
}
}

for Loop Variations

Using the Comma


● There will be times when you will want to include more than one
statement in the initialization and iteration portions of the for loop.

For example

// Using the comma.


class Comma
{
public static void main(String[] args)
{
int a, b;
for(a=1, b=4; a<b; a++, b--)
{
[Link]("a = " + a);
[Link]("b = " + b);
}
}
}

In the example below, the for loop continues to run until the boolean
variable done is set to true. It does not test the value of i.

boolean done = false;


for(int i=1; !done; i++)
{
// ...
if(interrupted())
done = true;
}

Another for loop variation.

[Link] R, CSE Dept


44
Object Oriented Programming with JAVA (BCS306A)

● Either the initialization or the iteration expression or both may be


absent

// Parts of the for loop can be empty.


class ForVar
{
public static void main(String[] args)
{
int i;
boolean done = false;
i = 0;
for( ; !done; )
{
[Link]("i is " + i);
if(i == 10)
done = true;
i++;
}
}
}

One more for loop variation.


● You can intentionally create an infinite loop, if you leave all three parts
of the for empty.
Syntax:

for( ; ; )
{
// ...
}

The For-Each Version of the for Loop

● Also called as enhanced for loop.


● A for-each style loop is designed to cycle through a collection of
objects, such as an array, in strictly sequential fashion, from start to
finish.

Syntax:

for(type itr-var : collection)


statement-block

● The following fragment uses a traditional for loop to compute the sum
of the values in an array:

[Link] R, CSE Dept


45
Object Oriented Programming with JAVA (BCS306A)

int[ ] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,11 };


int sum = 0;
for(int i=0; i < 10; i++)
sum += nums[i];

The above fragment rewritten using a for-each version of the for:

int[ ] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;
for(int x: nums)
sum += x;

// Use a for-each style for loop.


class ForEach
{
public static void main(String[] args)
{
int[ ] nums = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;

for(int x : nums)
{
[Link]("Value is: " + x);
sum += x;
}
[Link]("Summation: " + sum);
}
}

The output from the program is shown here:


Value is: 1
Value is: 2
Value is: 3
Value is: 4
Value is: 5
Value is: 6
Value is: 7
Value is: 8
Value is: 9
Value is: 10
Summation: 55

// Use for-each style for on a two-dimensional array.

[Link] R, CSE Dept


46
Object Oriented Programming with JAVA (BCS306A)

class ForEach3
{
public static void main(String[] args)
{
int sum = 0;
int[ ][ ] nums = new int[3][5];

for(int i = 0; i < 3; i++)


for(int j = 0; j < 5; j++)
nums[i][j] = (i+1)*(j+1);

for(int[ ] x : nums)
{
for(int y : x)
{
[Link]("Value is: " + y);
sum += y;
}
}
[Link]("Summation: " + sum);
}
}

Output:

Value is: 1
Value is: 2
Value is: 3
Value is: 4
Value is: 5
Value is: 2
Value is: 4
Value is: 6
Value is: 8
Value is: 10
Value is: 3
Value is: 6
Value is: 9
Value is: 12
Value is: 15
Summation: 90

// Search an array using for-each style for.


class Search
{
public static void main(String[] args)

[Link] R, CSE Dept


47
Object Oriented Programming with JAVA (BCS306A)

{
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)
[Link]("Value found!");

}
}
------

Nested Loops

● Nested loop means one loop may be inside another.

// Loops may be nested.


class Nested
{
public static void main(String[] args)
{
int i, j;
for(i=0; i<10; i++)
{
for(j=i; j<10; j++)
[Link](".");
[Link]();
}
}
}

Output:

[Link] R, CSE Dept


48
Object Oriented Programming with JAVA (BCS306A)

Jump Statements

● Java supports three jump statements: break, continue, and return.


● These statements transfer control to another part of the program.

The break statement has three uses.


1) Used to exit a switch statement.
2) It can be used to exit a loop.
3) It can be used as form of goto.

Using break to Exit a switch : See the switch statement example.

Using break to Exit a Loop:

● When a break statement is encountered inside a loop, the loop is


terminated and program control resumes at the next statement
following the loop.

// Using break to exit a loop.


class BreakLoop
{
public static void main(String[] args)
{
for(int i=0; i<100; i++)
{
if(i == 10)
break; // terminate loop if i is 10
[Link]("i: " + i);
}
[Link]("Loop complete.");
}
}

Output:
i: 0
i: 1
i: 2
i: 3
i: 4
i: 5
i: 6
i: 7
i: 8
i: 9

[Link] R, CSE Dept


49
Object Oriented Programming with JAVA (BCS306A)

Loop complete.

● When used inside a set of nested loops, the break statement will only
break out of the innermost loop.
● Java does not have a goto statement, but the goto can be useful when
you are exiting from a deeply nested set of loops. To handle such
situations, Java defines an expanded form of the break statement
called labelled break. By using this form of break, you can, break
out of one or more blocks of code.
● We can specify precisely where execution will resume, because this
form of break works with a label.

Syntax:
break label;

label is the name of a label that identifies a block of code.

// Using break to exit from nested loops


class BreakLoop4
{
public static void main(String[] args)
{
outer: for(int i=0; i<3; i++)
{
[Link]("Pass " + i + ": ");
for(int j=0; j<100; j++)
{
if(j == 10)
break outer; // exit both loops
[Link](j + " ");
}
[Link]("This will not print");
}
[Link]("Loops complete.");
}
}

Output:

Pass 0: 0 1 2 3 4 5 6 7 8 9 Loops complete.

Using continue
● Continue is used to continue running the loop but stop processing the
remainder of the code in its body for this particular iteration.
● In while and do-while loops, a continue statement causes control to be
transferred directly to the conditional expression that controls the loop.

[Link] R, CSE Dept


50
Object Oriented Programming with JAVA (BCS306A)

● 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.

// Demonstrate continue.
class Continue
{
public static void main(String[] args)
{
for(int i=0; i<10; i++)
{
[Link](i + " ");
if (i%2 == 0)
continue;
[Link]("");
}
}
}

Output:

0 1
2 3
4 5
6 7
8 9

● continue may specify a label to describe which enclosing loop to


continue.

// Using continue with a label.


class ContinueLabel
{
public static void main(String[] args)
{
outer: for (int i=0; i<10; i++)
{
for(int j=0; j<10; j++)
{
if(j > i)
{
[Link]();
continue outer; // continue with label

[Link] R, CSE Dept


51
Object Oriented Programming with JAVA (BCS306A)

}
[Link](" " + (i * j));
}
}
[Link]();
}
}

Output:

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.

// Demonstrate return.
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.");
}
}

Output:

Before the return.

Review Questions:

1) Differentiate between two programming paradigms.


2) Explain the three OOP principles.
3) What Is meant by block of code. How to define a block in java.
4) What is an identifier? What are the rules of defining a variable.
5) Explain the different types of comments of java
6) What are java class libraries.
7) Explain the primitive data types of java

[Link] R, CSE Dept


52
Object Oriented Programming with JAVA (BCS306A)

8) Explain the width and ranges of primitive data types.


9) What are escape sequence in java.
10) Explain the Scope and Lifetime of Variables
11) Explain the type casting mechanism in java
12) What is an array? How to declare and initialize the 2D array.
13) Explain the different types of java operators
14) Explain the logical and bitwise operators of java
15) What are the different types of control statements.
16) Explain ? operator
17) Explain the conditional or selection statements of java
18) Explain the iterative statements of java
19) Explain continue and break statements of java.
20) Practice all Java program of this module.

Important programs
Develop java programs to convert celcius temperature to
fahrenheit

F=(C×59)+32

import [Link];

public class CelsiusToFahrenheit


{
public static void main(String[] args)
{
Scanner scanner = new Scanner([Link]);

[Link]("Enter temperature in Celsius: ");

double celsius = [Link]();

double fahrenheit = (celsius * 9/5) + 32;

[Link](celsius + " Celsius is equal to " + fahrenheit + "


Fahrenheit.");
[Link]();
}
}

[Link] R, CSE Dept


53
Object Oriented Programming with JAVA (BCS306A)

Output:

Enter temperature in Celsius: 25


25.0 Celsius is equal to 77.0 Fahrenheit.

Develop a java program to add two matrices using command line


arguments

public class MatrixAddition


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

if ([Link] < 3)
{
[Link]("Usage: java MatrixAddition <rows> <cols>
<matrix1 elements> <matrix2 elements>");

return;
}

int rows = [Link](args[0]);


int cols = [Link](args[1]);

int totalElements = rows * cols;

if ([Link] != 2 + 2 * totalElements)

[Link]("Error: Expected " + (2 + 2 * totalElements) + "


arguments but got " + [Link]);

return;
}

int[][] matrix1 = new int[rows][cols];


int[][] matrix2 = new int[rows][cols];
int[][] sum = new int[rows][cols];

int index = 2; // Start reading from third argument


for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)

[Link] R, CSE Dept


54
Object Oriented Programming with JAVA (BCS306A)

{
matrix1[i][j] = [Link](args[index++]);
}
}

for (int i = 0; i < rows; i++)


{
for (int j = 0; j < cols; j++)
{
matrix2[i][j] = [Link](args[index++]);
}
}

for (int i = 0; i < rows; i++)


{
for (int j = 0; j < cols; j++)
{
sum[i][j] = matrix1[i][j] + matrix2[i][j];
}
}

[Link]("Resultant Matrix after Addition:");

for (int i = 0; i < rows; i++)


{
for (int j = 0; j < cols; j++)
{
[Link](sum[i][j] + "\t");
}

[Link]();
}
}
}

Output

Matrix 1 = [1, 2, 3, 4]
Matrix 2 = [5, 6, 7, 8]

Resultant Matrix after Addition:


6 8
10 12

[Link] R, CSE Dept


55

You might also like