Module 1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 41

PROGRAMMING APPROACHES

There are mainly two approaches


• Procedure oriented Programming(POP)
• Object Oriented Programming (OOP)
Examples of POP – C, COBOL, PASCAL, FORTRAN
Examples of OOP – C++, JAVA, PYTHON, C#

Basic difference in the two approaches is dictated by:


The way the problem is handled.
In POP problem to be solved is broken into a number of distinct
functions.
In OOP the problem to be solved is broken into a number of distinct
objects.
PROCEDURE ORIENTED
PROGRAMMING
In the procedure-oriented approach, the problem is viewed as a sequence of
things to be done such as reading, calculating and printing.
Number of functions are written to accomplish these tasks .
The primary focus is on functions :

• Procedure-oriented programming basically involves writing a list of


instructions for the computer to follow and organizing these instructions
into groups known as functions
TYPICAL
STRUCTURE
OF
PROCEDUR
E-ORIENTED
PROGRAM
CHARACTERISTICS OF
PROCEDURE-ORIENTED
PROGRAMMING
• Emphasis is on doing things.
• Large programs are divided into smaller programs known as
functions.
• Most of the functions share global data.
• Data move openly around the system from function to
function.
• Functions transform data from one form to another.
• Employs top-down approach in program design.
OBJECT  OOP is an approach that attempts to eliminate some of the
pitfalls of conventional programming methods by

ORIENTED incorporating the best of structured programming features


with several new concepts

PROGRAMMING  Programs are divided into what are known as objects.


 Data is hidden and cannot be accessed by external functions.
 It ties data more closely to the functions that operate on it and
protects it from accidental modification from outside
functions.
 Objects may communicate with each by passing messages.
 New data and functions can be easily added whenever
necessary.
 Follows bottom-up approach in program design
CHARACTERISTICS OF OBJECT-ORIENTED
PROGRAMMING  Emphasis is on data rather than procedure.
 Programs are divided into objects.
 Data structures are designed such that they characterize the
objects.
 Functions that operate on the data of an object are tied together
in the data structure.
 Data is hidden and can not be accessed by external functions.
 Objects may communicate with each other through functions.
 New data and functions can be added easily whenever
necessary.
 Follows bottom-up approach in program design.
KEY CONCEPTS OF OOP

 Class
 Object
 Message Passing
 Encapsulation
 Inheritance
 Polymorphism
CLASS AND OBJECT
Class is a template that defines the form of an object.
It specifies both data and code that will operate on that data
Class is essentially a set of plans that specify how to build an object.
Class is a logical abstraction.
Classes are user-defined data types. A class is a collection of objects of similar type.
• The entire set of data and code of an object can be made a user-defined data type with
the help of a class. Objects are variables of the type class.
• Once a class has been defined, we can create any number of objects belonging
to that class.

Class Composition
EXAMPLE 2- BANK ACCOUNT
• The "account" class describes the attributes and
behaviors of bank accounts.

• The “account” class defines two state variables


(account number and balance) and two methods
(deposit and withdraw).
OBJECT
• Object are instance of class.
• Objects are the basic run-time entities in an object-oriented system.
• They may represent a person, a place, a bank account, etc.
• Objects take up space in the memory and have an associated address like a structure in C.
• When a program is executed, the objects interact by sending messages to one another.
ENCAPSULATION
 Encapsulation is programming mechanism that bids together code and data it manipulates and that
keeps both safe from outside interference and misuse.
 The data is not accessible to the outside world, only those function which
are wrapped in can access it.
 These functions provide the interface between the object’s data and the program.
 This insulation of the data from direct access by the program is called data hiding or information
hiding.

 Java’s basic unit of encapsulation is the class


POLYMORHISM
• Polymorphism, a Greek term means to ability to take more than
one form.
• The concept of polymorphism is often expressed by the phrase
“One interface ,multiple methods”
• An operation may exhibits different behaviors in different
instances. The behavior depends upon the type of data used in the
operation.
• For example consider the operation of addition for two numbers;
the operation will generate a sum. If the operands are string then
the operation would produce a third string by concatenation
INHERITANCE
• Inheritance is the process by which objects of one class acquire

the properties of objects of another class.

• In OOP, the concept of inheritance provides the idea of

reusability. This means we can add additional features to

an existing class without modifying it.

• Each derived class shares common characteristics with the class

from which it is derived.


MESSAGE PASSING
• In object-oriented programming, communication between objects is a vital aspect of building complex systems. One of
the key mechanisms for achieving this communication is message passing.

• In Java, message passing allows objects to interact with each other by invoking methods and passing data between
them.

• An oop consists of a set of objects that communicate with each other.

• Oop involves the following steps:

• Creating classes that define objects and their behaviour.

• Creating objects from class definitions.

• Establishing communication among objects.

• Objects communicate with one another by sending and receiving information.


MESSAGE PASSING EXAMPLE

• Messages are information/requests that objects


send to other objects (or to themselves).
• Message components include:
• The name of the object to receive the
message.
• The name of the method to perform.
• Any parameters needed for the method.
DIFFERENCE
BETWEEN
OOP & OTHER
CONVENTION
AL
LANGUAGES
• Code Reusability (Faster development): Through inheritance, we can
BENEFITS
eliminate redundant code and extend the use of existing class
OF OOP
• Improved software development productivity : We can build programs
from the standard working modules that communicate with each other,
rather than having to start writing code from scratch. This leads to saving of
development time & higher productivity.
• Data Security : The principle of data hiding helps the programmer to build
& secure programs that cannot be invaded by code in other parts of the
program.
• It is possible to map objects in the problem domain to those in the program
• It is easy to partition the work in a project based on objects
• Object-oriented systems can be easily upgraded from small to large
systems.
• Message passing techniques for communication between objects makes
the interface descriptions with external systems much simpler.
• Software complexity can be easily managed .
OBJECT
ORIENTED
PROGRAMMIN
G
Java Programming Fundamentals
Java programming language was originally developed by Sun Microsystems which was
initiated by James Gosling and released in 1995 as core component of Sun Microsystems’ Java
platform (Java 1.0 [J2SE]). Now it has become the one of the most popular computer
programming language and is now being used by more than 2 billion devices.
 The latest release of the Java is JDK12.
SE: Standard Edition
EE: Enterprise Applications,
ME: Mobile Applications.
 With the advancement of Java and its widespread popularity, multiple configurations were
built to suite various types of platforms.
 Java is guaranteed to be Write Once, Run Anywhere.

JDK(Java Development Kit):


A platform is a software or hardware environment in which a program executes or runs. Some of
the most platforms are Microsoft Windows, Linux, Mac, and Solaris. Java platform is only a
software-based platform that runs on top of other hardware-based platforms such as Microsoft
Windows, Linux, and Mac.
• Java Development Kit (JDK) is a software development environment that is developed and
distributed by Oracle. It is used for building (developing) java software applications.
• In simple words, it is used to write java programs by programmers.
• Java Development Kit has the following components. They are as follows:
Java Runtime Environment (JRE):
• It is an environment that is required for running (executing) a java application.
• It cannot be used for the development of Java applications.
• It is used only for executing the application program.
• Java Runtime Environment is a collection of programs that contain JVM (Java Virtual
Machine), Java APIs (Application Programming Interface), and Java Class Libraries that
help in the development of Java application programs.

• Java Virtual Machine (JVM) in Java is the heart of the entire execution process of the Java
program. It is basically a program that provides the runtime environment necessary for Java
programs to execute.
• The specification of JVM is provided by Sun Microsystem whose implementation provides a
runtime environment to execute our Java applications. JVM implementation is known as
Java Runtime Environment (JRE).
• Since JVM is platform-dependent, therefore, it is available for many hardware and software
platforms.The most popular JVM is HotSpot that is produced by Oracle. It is available for many
operating systems such as Windows, Linux, Solaris, and Mac OS.
• We cannot run the Java program unless JVM is available for the appropriate hardware and
operating system platform.

Java Virtual Machine performs the following operations for execution of the program. They are as
follows:
a) Load the code into memory.
b) Verifies the code.
c) Executes the code
d) Provides runtime environment.

Bytecode in Java:
• Bytecode in Java is a highly optimized set of instructions for the Java Virtual Machine (JVM)
that reads and interprets to run the java program.
• A bytecode is a binary program code that can only run on JVM. In other words, it is a machine
language (code) for JVM in the form of .class file, but it is not machine specific because it is not a
native code.
• Java bytecode has two most important characteristics that are as follows:
• Byte code is independent of processor, i.e., Java program can be executed on any processor
architecture. It does not depend on operating systems such as Windows, Linux, and Mac OS.
How does Bytecode work in Java?
When we write a java program, the source code (in the form of .java file) is compiled by Java compiler
and converted into byte code in the form of a .class file.This compiled byte code is platform
independent code that can be run on any different computer machine on which JVM interpreter is
installed. In simple words, write once, compile and run anywhere (WOCRA).
A compiler in Java is a computer program that is used for compiling Java programs. It is platform-
independent. It converts (translates) source code (.java file) into bytecode (.class file).
Java Interpreter translates (converts) bytecode to machine code(native code) line by line during
runtime.

Characteristics of Java(Java Buzz words) :


 Object Oriented: In Java, everything is an Object. Java can be easily extended since it is
based on the Object model.
 Platform independent: Unlike many other programming languages including C and
C++, when Java is compiled, it is not compiled into platform specific machine, rather into
platform independent byte code. This byte code is distributed over the web and
interpreted by virtual Machine (JVM) on whichever platform it is being run.
 Simple: Java is designed to be easy to learn. If you understand the basic concept of OOP,
Java would be easy to master.
 Secure: With Java's secure feature, it enables to develop virus-free, tamper-free systems.
Authentication techniques are based on public-key encryption.
 Architectural-neutral: Java compiler generates an architecture-neutral object file
format, which makes the compiled code to be executable on many processors, with the
presence of Java runtime system.
 Portable: Being architectural-neutral and having no implementation dependent aspects
of the specification makes Java portable. Compiler in Java is written in ANSI C with a
clean portability boundary which is a POSIX subset.

 Robust: Java makes an effort to eliminate error prone situations by emphasizing mainly
on compile time error checking and runtime checking.
 Multithreaded: With Java's multithreaded feature, it is possible to write programs that
can do many tasks simultaneously. This design feature allows developers to construct
smoothly running interactive applications.
 Interpreted: Java byte code is translated on the fly to native machine instructions and is
not stored anywhere. The development process is more rapid and analytical since the
linking is an incremental and lightweight process.
 High Performance: With the use of Just-In-Time compilers, Java enables high
performance.
 Distributed: Java is designed for the distributed environment of the internet.
 Dynamic: Java is considered to be more dynamic than C or C++ since it is designed to
adapt to an evolving environment. Java programs can carry extensive amount of run-time
information that can be used to verify and resolve accesses to objects on run-time.
Java Basic Syntax
When we consider a Java program, it can be defined as a collection of objects that
communicate via invoking each other's methods. Let us now briefly look into what do class,
object, methods and instance variables mean.
 Object – Objects have states and behaviors. Example: A dog has states-color, name, and
breed as well as behaviors -wagging, barking, and eating. An object is an instance of a
class.
 Class – A class can be defined as a template/blue print that describes the behaviors/states
that object of its type support.
 Methods – A method is basically a behavior. A class can contain many methods. It is in
methods where the logics are written, data is manipulated and all the actions are
executed.
 Instance Variables – Each object has its unique set of instance variables. An object's
state is created by the values assigned to these instance variables

First Java Program:


· Let us look at a simple code that would print the words "Hello World".

/* This is my first java program. This will print 'Hello World' as the output */
public class MyFirstJavaProgram
{
public static void main(String[]args)
{
System.out.println("Hello World"); // prints Hello World
}
}
Basic Syntax:
About Java programs, it is very important to keep in mind the following points.
 Case Sensitivity – Java is case sensitive, which means identifier Hello and hello would
have different meaning in Java.
 Class Names – For all class names, the first letter should be in Upper Case. If several
words are used to form a name of the class, each inner word's first letter should be in
Upper Case. Example class MyFirstJavaClass.
 Method Names – All method names should start with a Lower Case letter. If several
words are used to form the name of the method, then each inner word's first letter should
be in Upper Case. Example public void myMethodName().
 Program File Name – Name of the program file should exactly match the class name.
When saving the file, you should save it using the class name (Remember Java is case
sensitive) and append '.java' to the end of the name (if the file name and the class name
do not match your program will not compile).
Example: Assume 'MyFirstJavaProgram' is the class name, then the file should be
saved as 'MyFirstJavaProgram.java'
 public static void main(String args[]) – Java program processing starts from the main()
method, which is a mandatory part of every Java program.
/*Here is another short example. Call this file "Example2.java".*/
class Example2 {
public static void main(String args[]) {
int num; // this declares a variable called num
num = 100; // this assigns num the value 100
System.out.println("This is num: " + num);
num = num * 2;
System.out.print("The value of num * 2 is ");
System.out.println(num);
}
}

The output of the program is:

This is num: 100


The value of num * 2 is 200

Java Basic Data Types


The Variables are nothing but reserved memory locations to store values. This means that
when you create a variable you reserve some space in memory.
Based on the data type of a variable, the operating system allocates memory and decides what
can be stored in the reserved memory. Therefore, by assigning different data types to variables, you
can store integers, decimals, or characters in these variables.
There are two data types available in Java:
 Primitive Data Types
 Reference/Object Data Types
Primitive Data Types:
There are eight primitive data types supported by Java. Primitive data types are predefined by the
language and named by a keyword. Let us now look into detail about the eight primitive data types.
byte:
 Byte data type is an 8-bit signed two's complement integer.
 Minimum value is -128 (-2^7)
 Maximum value is 127 (inclusive)(2^7 -1)
 Default value is 0
 Byte data type is used to save space in large arrays, mainly in place of integers, since a
byte is four times smaller than an int.
Example: byte a = 100, byte b = -50

Short:
 Short data type is a 16-bit signed two's complement integer.
 Minimum value is -32,768 (-2^15)
 Maximum value is 32,767(inclusive) (2^15 -1)
 Short data type can also be used to save memory as byte data type. A short is 2 times
smaller than an int.
 Default value is 0.
 Example: short s= 10000, short r = -20000

int:
 int data type is a 32-bit signed two's complement integer.
 Minimum value is – 2,147,483,648.(-2^31).
 Maximum value is 2,147,483,647(inclusive).(2^31 -1).
 int is generally used as the default data type for integral values unless there is a concern
about memory.
 The default value is 0.
Example: int a = 100000, int b = -200000

long:
 Long data type is a 64-bit signed two's complement integer.
 Minimum value is -9,223,372,036,854,775,808.(-2^63)
 Maximum value is 9,223,372,036,854,775,807 (inclusive). (2^63 -1)
 This type is used when a wider range than int is needed.
 Default value is 0L.
Example: int a = 100000L, int b = -200000L
float:
 Float data type is a single-precision 32-bit IEEE 754 floating point.
 Float is mainly used to save memory in large arrays of floating point numbers.
 Default value is 0.0f.
 Float data type is never used for precise values such as currency.

Double:
 double data type is a double-precision 64-bit IEEE 754 floating point.
 This data type is generally used as the default data type for decimal values, generally the
default choice.
 Double data type should never be used for precise values such as currency.
 Default value is 0.0d.
Example: double d1 = 123.4

Here is a short program that uses double variables to compute the area of a circle:

// Compute the area of a circle.


class Area {
public static void main(String args[]) {
double pi, r, a;
r = 10.8; // radius of circle
pi = 3.1416; // pi, approximately
a = pi * r * r; // compute area
System.out.println("Area of circle is " + a);
}
}

boolean:
 boolean data type represents one bit of information.
 There are only two possible values: true and false.
 This data type is used for simple flags that track true/false conditions.
 Default value is false.
Example: boolean one = true
Here is a program that demonstrates the boolean type:

// Demonstrate boolean values.


class BoolTest {
public static void main(String args[]) {
boolean b;
b = false;
System.out.println("b is " + b);
b = true;
System.out.println("b is " + b);

// a boolean value can control the if statement


if(b)
System.out.println("This is executed.");
b = false;
if(b)
System.out.println("This is not executed.")
// outcome of a relational operator is a boolean value
System.out.println("10 > 9 is " + (10 > 9));
}
}

The output generated by this program is shown here:

b is false
b is true
This is executed.
10 > 9 is true

char:

 char data type is a single 16-bit Unicode character.


 Minimum value is '\u0000' (or 0).
 Maximum value is '\uffff' (or 65,535 inclusive).
 Char data type is used to store any character.
 Example: char letter A ='A';
Here is a program that demonstrates char variables:

// Demonstrate char data type.


class CharDemo
{
public static void main(String args[])
{
char ch1, ch2;
ch1 = 88; // code for X
ch2 = 'Y';
System.out.print("ch1 and ch2: ");
System.out.println(ch1 + " " + ch2);
}
}
This program displays the following output:

ch1 and ch2: X Y

Literals
• Literals represent fixed values in a source code. These are similar
to standard variables with the difference that these are constant.

• These can be classified as an integer literal, a string literal, a boolean etc.

• The user defines these mainly to define constants.

• There are five types of literals in Java:

• Integer

• Floating Point
• Boolean
• Character
• String
Example:
public class JavaIntegerLiterals {
public static void main (String[]args){
//initialize variables with integer literals
int decimalNum = 25;
int hexaNum = 0xa5;
int binaryNum = 0b1101;
int octalNum = 0172;
//print out the values of the literal
System.out.println("Decimal Integer: " + decimalNum);
System.out.println("Octal Integer: " + octalNum);
System.out.println("Hexadecimal Integer: " + hexaNum);
System.out.println("Binary Integer: " + binaryNum);
}
}

Output
Decimal Integer: 25
Octal Integer: 122
Hexadecimal Integer: 165
Binary Integer: 13

Java Variable Types


A variable provides us with named storage that our programs can manipulate. Each
variable in Java has a specific type, which determines the size and layout of the variable's
memory the range of values that can be stored within that memory and the set of operations that
can be applied to the variable.
You must declare all variables before they can be used. The basic form of a variable
declaration is shown here:
data type variable [ = value][, variable [= value] …] ;

Here data type is one of Java's data types and variable is the name of the variable. To declare
more than one variable of the specified type, you can use a comma-separated list.
Following are valid examples of variable declaration and initialization in Java:
int a, b, c; // Declares three ints, a, b and c.
int a = 10, b = 10;
// Example of initialization
byte B = 22; // initializes a byte type variable B.
double pi = 3.14159; // declares and assigns a value of PI.
char a = 'a'; // the char variable a is initialized with value 'a'

There are three kinds of variables in Java:


 Local variables
 Instance variables / Reference variables
 Class/static variables
Local variables:
 Local variables are declared in methods, constructors, or blocks.
 Local variables are created when the method, constructor or block is entered and the
variable will be destroyed once it exits the method, constructor or block.
 Access modifiers cannot be used for local variables.

Dynamic Initialization
 Java allows variables to be initialized dynamically, using any expression valid at the time
the variable is declared.
 For example, here is a short program that computes the length of the hypotenuse of a
right triangle given the lengths of its two opposing sides:

// Demonstrate dynamic initialization.


class DynInit {
public static void main(String args[]) {
double a = 3.0, b = 4.0;
// c is dynamically initialized
double c = Math.sqrt(a * a + b * b);
System.out.println("Hypotenuse is " + c);
}
}
Scope and Lifetime of Variables
Java allows variables to be declared within any block. Scope and Lifetime of variable is
determined how and where those variables are defined.

 In Java, the two major scopes are those defined by a class and those defined by a method.
 A block is begun with an opening curly brace and ended by a closing curly brace. A block
defines a scope. Thus, each time you start a new block, you are creating a new scope. As
cope determines what objects are visible to other parts of your program, it also determines
the lifetime of those objects.
 Variables defined inside scope can't be accessed outside the scope of that variable.
 Thus, when you declare a variable within a scope, you are localizing that variable and
protecting it from unauthorized access and/or modification.
 Indeed, the scope rules provide the foundation for encapsulation.

To understand the effect of nested scopes, consider the following program:

// Demonstrate block scope.


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

x and y: 10 20
x is 40

 Here is another important point to remember: 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.
 If a variable declaration includes an initializer, then that variable will be reinitialized each
time the block in which it is declared is entered.
For example, consider the next program.

// Demonstrate lifetime of a variable.


class LifeTime {
public static void main(String args[]) {
int x;
for(x = 0; x < 3; x++) {
int y = -1; // y is initialized each time block is entered
System.out.println("y is: " +y); // this always prints -1
y = 100;
System.out.println("y is now: " + y);
}
}
}
The output generated by this program is shown here:

y is: -1
y is now: 100
y is: -1
y is now: 100
y is: -1
y is now: 100

Type Conversion and Casting


Assigning a value of one type to a variable of another type is known as Type Casting.

 Java’s Automatic Conversions


o 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. char and boolean are
not compatible with each other.
o 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.

 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, you must use a cast. A cast is
simply an explicit type conversion. It has this general form: 
(target_type) value
Example:

int a;
byte b;
// ...
b = (byte) a;

The following program demonstrates some type conversions that require casts:

// Demonstrate casts.
class Conversion {
public static void main(String args[]) {
byte b;
int i = 257;
double d = 323.142;
System.out.println("\nConversion of int to byte.");
b = (byte) i;
System.out.println("i and b " + i + " " + b);
System.out.println("Conversion of double to int");
i = (int) d;
System.out.println("d and i " + d + " " + i);
System.out.println("Conversion of double to byte");
b = (byte) d;
System.out.println("d and b " + d + " " + b);
}
}
This program generates the following output:
Conversion of int to byte.
i and b 257 1
Conversion of double to int.
d and i 323.142 323
Conversion of double to byte.
d and b 323.142 67

Automatic Type Promotion in Expressions


 Example
byte a = 40;
byte b = 50;
byte c = 100;
int d = a * b / c;
 Another example
byte b = 50;
b = b * 2; // Error! Cannot assign an int to a byte!
 Solution
byte b = 50;
b = (byte)(b * 2);//which yields the correct value of 100.

Java Operators
Like other programming languages, there are arithmetic operators, bitwise operators and logical
operators in Java.

Arithmetic Operators
Arithmetic operators are used in mathematical expressions in the same way that they are used in
algebra. The following table lists all the arithmetic operators in Java.
The following program illustrates the increment operator.

// Demonstrate ++.
class IncDec {
public static void main(String args[]) {
int a = 1;
int b = 2;
int c;
int d;
c = ++b;
d = a++;
c++;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
}

The output of this program follows:

a=2
b=3
c=4
d=1

The Bitwise Operators


Java defines several bitwise operators that can be applied to the integer types, long, int, short,
char, and byte. These operators act upon the individual bits of their operands.
The Bitwise Logical Operators
The bitwise logical operators are &, |, ^, and ~. The following table shows the outcome of each
operation. In the discussion that follows, keep in mind that the bitwise operators are applied to
each individual bit within each operand.

The Left Shift


The left shift operator, <<, shifts all of the bits in a value to the left a specified number of times.
It has this general form:
value << num
Here, num specifies the number of positions to left-shift the value in value. That is, the << moves
all of the bits in the specified value to the left by the number of bit positions specified by num.

The following program illustrates the explanation more clearly.

// 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);
System.out.println("Original value of a: " + a);
System.out.println("i and b: " + i + " " + b);
}
}

The output generated by this program is shown here:

Original value of a: 64
i and b: 256 0
The Right Shift
The right shift operator, >>, shifts all of the bits in a value to the right a specified number of
times. Its general form is shown here:
value >> num
Here, num specifies the number of positions to right-shift the value in value. That is, the >>
moves all of the bits in the specified value to the right the number of bit positions specified
by num.
The following code fragment shifts the value 32 to the right by two positions, resulting in a being
set to 8:

int a = 32;
a = a >> 2; // a now contains 8

When a value has bits that are ―shifted off, those bits are lost. For example, the next code
fragment shifts the value 35 to the right two positions, which causes the two low-order bits to be
lost, resulting again in a being set to 8.
int a = 35;
a = a >> 2; // a still contains 8
Looking at the same operation in binary shows more clearly how this happens:

00100011 35 >> 2
1000

Bitwise Operator Compound Assignments

a = a >> 4;
a >>= 4;

The following two statements, which result in a being assigned the bitwise expression a OR b,
are equivalent:

a = a | b;
a |= b;

Relational Operators
The relational operators determine the relationship that one operand has to the
other. Specifically, they determine equality and ordering.
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.

Here is a program that is almost the same as the BitLogic example shown earlier, but it operates
on Boolean logical values instead of binary bits:

// 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;
System.out.println(" a = " + a);
System.out.println(" b = " + b);
System.out.println(" a|b = " + c);
System.out.println(" a&b = " + d);
System.out.println(" a^b = " + e);
System.out.println("!a&b|a&!b = " + f);
System.out.println(" !a = " + g);
}
}
The output of the program is:

a = true
b = false
a|b = true
a&b = false
a^b = true
a&b|a&!b = true
!a = false

After running this program, you will see that the same logical rules apply to Boolean values as
they did to bits. As you can see from the following output, the string representation of a
Java Boolean value is one of the literal values true or false.

The ? Operator
Java includes a special ternary (three-way) operator that can replace certain types of if-then-else
statements. This operator is the? Operator. The ? has this general form:

expression1 ? expression2 : expression3

Here, expression1 can be any expression that evaluates to a boolean value. If expression1 is true,
then expression2 is evaluated; otherwise, expression3 is evaluated.

You might also like