0% found this document useful (0 votes)
3 views74 pages

Java Unit 1

Uploaded by

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

Java Unit 1

Uploaded by

larsenphilip476
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 74

Java

Programming
UNIT-1
Unit I :Java Language: Creation of JAVA, Java Buzzwords, Java magic
code; Object-oriented programming. Data types, Variables & Arrays: The
primitive types; Floating-point types; Characters; Booleans; Variables;
Type conversion and casting; Arrays. Operators: Arithmetic operators;
Bitwise operators; Relational operators; Boolean logical operators;
Assignment operator; Conditional operator; Control Statements:
Selection statements; Iteration statements; Jump statements.

Java Language:
Computer language innovation and development occurs for two fundamental reasons:

• To adapt to changing environments and uses

• To implement refinements and improvements in the art of programming


Creation of Java

Java was conceived by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan at Sun Microsystems,
Inc. in 1991

This language was initially called “Oak,” but was renamed “Java” in 1995.

Bill Joy, Arthur van Hoff, Jonathan Payne, Frank Yellin, and Tim Lindholm were key contributors to the maturing of the
original prototype.

the primary motivation was the need for a platform-independent (that is, architecture-neutral)

used to create software to be embedded in various consumer electronic devices, such as microwave ovens, washing
machines and remote controls

The trouble with C and C++ (and most other languages) is that they are designed to be compiled for a specific target.

This second force was, of course, the World Wide Web,more important emerging factor that would play a crucial role in the
future of Java
How Java Changed the Internet?

Java Applets:

1. Java innovated a new type of networked program called the applet that changed the way the online world thought
about content
2. Java also addressed some of the thorniest issues associated with the Internet: portability and security
3. An applet is a special kind of Java program that is designed to be transmitted over the Internet and automatically
executed by a Java-compatible web browser
4. They are typically used to display data provided by the server, handle user input, or provide simple functions, such as
a loan calculator, that execute locally, rather than on the server
5. the applet allows some functionality to be moved from the server to the client
6. Applet gives Security and Portability

Security:Java achieved this protection by confining an applet to the Java execution environment and not allowing it access to
other parts of the computer

Portability: The same applet must be able to be downloaded and executed by the wide variety of CPUs, operating systems,
and browsers connected to the Internet.
Java’s Magic: The Bytecode

The key that allows Java to solve both the security and the portability problems just described is that the output of a Java
compiler is not executable code

Rather, it is bytecode. Bytecode is a highly optimized set of instructions designed to be executed by the Java run-time
system, which is called the Java Virtual Machine (JVM)

In essence, the original JVM was designed as an interpreter for bytecode


The Java Buzzwords

● Simple
● Secure
● Portable
● Object-oriented
● Robust
● Multithreaded
● Architecture-neutral
● Interpreted
● High performance
● Distributed
● Dynamic
Object-Oriented Programming

Object-Oriented Programming or OOPs refers to languages that uses objects in programming.The main aim
of OOP is to bind together the data and the functions that operate on them so that no other part of the code
can access this data except that function.
Two Paradigms

All computer programs consist of two elements: code and data

some programs are written around “what is happening” (process oriented model or code acting on data) and others are
written around “who is being affected.”( object oriented model or data controlling access to the code)

Abstraction

Abstraction is the concept of object-oriented programming that "shows" only essential attributes and "hides"
unnecessary information. The main purpose of abstraction is hiding the unnecessary details from the users.

The elements of OOPS are:

1. Encapsulation
2. Inheritance
3. Polymorphism
Data Types

a particular kind of data item, as defined by the values it can take, the programming language used, or the operations that can be
performed on it.

Java Is a Strongly Typed Language

First, every variable has a type, every expression has a type, and every type is strictly defined.

Second, all assignments, whether explicit or via parameter passing in method calls, are checked for type compatibility

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: byte, short, int, long, char, float, double, and boolean. The primitive types are also
commonly referred to as simple types, and both terms will be used in this book. 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. Many other computer languages support both signed and unsigned
integers
byte

The smallest integer type is byte. This is a signed 8-bit type that has a range from –128 to 127. Variables of type byte are
especially useful when you’re working with a stream of data from a network or file. Eg. byte b, c;

short

short is a signed 16-bit type. It has a range from –32,768 to 32,767. It is probably the least used Java type. Here are some
examples of short variable declarations: eg. short s; short t;

int

The most commonly used integer type is int. It is a signed 32-bit type that has a range from –2,147,483,648 to 2,147,483,647. In
addition to other uses, variables of type int are commonly employed to control loops and to index arrays. Eg int i,x,y;

long

long is a signed 64-bit type and is useful for those occasions where an int type is not large enough to hold the desired value. The
range of a long is quite large. This makes it useful when big, whole numbers are needed. Eg. long distance;
Example Program:

// Compute distance light travels using long variables.


class Light {
public static void main(String args[]) {
int lightspeed; long days; long seconds; long distance;
// approximate speed of light in miles per second lightspeed = 186000;
days = 1000; // specify number of days here
seconds = days * 24 * 60 * 60; // convert to seconds
distance = lightspeed * seconds; // compute distance
System.out.print("In " + days);
System.out.print(" days light will travel about ");
System.out.println(distance + " miles."); } }

This program generates the following output: In 1000 days light will travel about 16070400000000 miles.

Clearly, the result could not have been held in an int variable
Floating-Point Types
Floating-point numbers, also known as real numbers, are used when evaluating expressions that require
fractional precision.
For example, calculations such as square root, or transcendentals such as sine and cosine, result in a value
whose precision requires a floating point type.
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
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. Eg. float hightemp, lowtemp;

double

Double precision, as denoted by the double keyword, uses 64 bits to store a value. 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

// 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);
}
}
Characters
In Java, the data type used to store characters is char. However, C/C++ programmers beware: char in Java is not the same as
char in C or C++. In C/C++, char is 8 bits wide. This is not the case in Java. Instead, Java uses Unicode to represent
characters. Unicode defines a fully international character set that can represent all of the characters found in all human
languages. It is a unification of dozens of character sets, such as Latin, Greek, Arabic, Cyrillic, Hebrew, Katakana, Hangul,
and many more. At the time of Java's creation, Unicode required 16 bits. Thus, in Java char is a 16-bit type
// 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
Booleans
Java has a primitive type, called boolean, for logical values.
It can have only one of two possible values, true or false.
This is the type returned by all relational operators, as in the case of a < b.
boolean is also the type required by the conditional expressions that govern the control statements such as if
and for.
Here is a program that demonstrates the boolean type:
if(b) System.out.println("This is not
// Demonstrate boolean values.
executed.");
class BoolTest {
// outcome of a relational operator is a
public static void main(String args[]) { boolean value
boolean b; System.out.println("10 > 9 is " + (10 > 9));
b = false; }
System.out.println("b is " + b); }
b = true; The output generated by this program is
System.out.println("b is " + b); shown here:
// a boolean value can control the if statement b is false
if(b) System.out.println("This is executed."); b is true
b = false; This is executed.
10 > 9 is true
Literals (Constants in C)

A constant value in Java is created by using a literal representation of it. For example, here are some literals:

100 98.6 ‘X’ “This is a test”

Left to right, the first literal specifies an integer, the next is a floating-point value, the third is a character constant, and
the last is a string. A literal can be used anywhere a value of its type is allowed.

Integer Literals

Integers are probably the most commonly used type in the typical program. Any whole number value is an integer
literal. Examples are 1, 2, 3, and 42
Octal Numbers - with a leading 0, eg. 03,07 but not 08 because it is not octal
Hexa Decimal Numbers - with a leading 0x or 0X, eg. 0x123F, 0Xabcd(remember Hexa decimal numbers can have
A,B,C,D,E,F)
Decimal Numbers- cannot have a leading 0, Eg. x=08 is invalid in java

Integer literals create an int value, which in Java is a 32-bit integer value, When a literal value is assigned to a byte or
short variable, no error is generated if the literal value is within the range of the target type. However, to specify a
long literal, you will need to explicitly tell the compiler that the literal value is of type long. You do this by appending
an upper- or lowercase L to the literal. For example, 0x7ffffffffffffffL
Literals (Constants in C)

Beginning with JDK 7, you can also specify integer literals using binary. To do so, prefix the value with 0b or 0B.
For example, this specifies the decimal value 10 using a binary literal: int x = 0b1010;

Also beginning with JDK 7, you can embed one or more underscores in an integer literal. Doing so makes it
easier to read large integer literals. When the literal is compiled, the underscores are discarded. For example,
given int x = 123_456_789; the value given to x will be 123,456,789.

Floating-Point Literals

Floating-point numbers represent decimal values with a fractional component. They can be expressed in either
standard or scientific notation.

Standard notation consists of a whole number component followed by a decimal point followed by a fractional
component. For example, 2.0, 3.14159, and 0.6667 represent valid standard-notation floating-point numbers.

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. Examples include 6.022E23, 314159E–05, and 2e+100
Floating-Point Literals Hexadecimal floating-point literals are also supported, but they are rarely used. They must be in a
form similar to scientific notation, but a P or p, rather than an E or e, is used. For example, 0x12.2P2 is a valid floating-point
literal. The value following the P, called the binary exponent, indicates the power-of-two by which the number is multiplied.
Therefore, 0x12.2P2 represents 72.5.

Beginning with JDK 7, you can embed one or more underscores in a floating-point literal. This feature works the same as it
does for integer literals, which were just described. Its purpose is to make it easier to read large floating-point literals. When
the literal is compiled, the underscores are discarded. For example, given double num = 9_423_497_862.0; the value given
to num will be 9,423,497,862.0. The underscores will be ignored

Boolean Literals

Boolean literals are simple. There are 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. The true literal in Java does not equal 1, nor does the false
literal equal 0. In Java, the Boolean literals can only be assigned to variables declared as boolean or used in expressions with
Boolean operators.
Character Literals

Characters in Java are indices into the Unicode character set. They are 16-bit values that can be converted into
integers and manipulated with the integer operators, such as the addition and subtraction operators.

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
String Literals

String literals in Java are specified like they are in most other languages—by enclosing a sequence of characters between a
pair of double quotes.

Examples of string literals are "Hello World" "two\nlines" "\"This is in quotes\""

The escape sequences and octal/hexadecimal notations that were defined for character literals work the same way inside of
string literals. One important thing to note about Java strings is that they must begin and end on the same line. There is no
line-continuation escape sequence as there is in some other languages.

NOTE As you may know, in some other languages, including C/C++, strings are implemented as arrays of characters.
However, this is not the case in Java. Strings are actually object types.
Variables

The variable is the basic unit of storage in a Java program. A variable is defined by the combination of an identifier, a type,
and an optional initializer. 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 ] …]; Here, type is one of Java’s atomic types, or the name of a class or interface

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

lthough 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, 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);
}
}
Here, three local variables—a, b, and c—are declared. The first two, a and b, are initialized by constants. However, c is
initialized dynamically to the length of the hypotenuse
The Scope and Lifetime of Variables
So far, all of the variables used have been declared at the start of the main( ) method. However, Java allows variables to be
declared within any block.
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. A scope determines what objects are visible to other parts of your
program. It also determines the lifetime of those objects
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. Indeed, the scope rules provide the foundation for encapsulation.
// Demonstrate block scope.
// Demonstrate lifetime of a variable.
class Scope { class LifeTime {
public static void main(String args[]) { public static void main(String args[]) {
int x; // known to all code within main int x;
x = 10; for(x = 0; x < 3; x++) {
if(x == 10) { // start new scope int y = -1; // y is initialized each time block is entered
int y = 20; // known only to this block System.out.println("y is: " + y); // this always prints -1
// x and y both known here. y = 100;
System.out.println("x and y: " + x + " " + y); System.out.println("y is now: " + y);
x = y * 2; }
}
}
}
// y = 100; // Error! y not known here
The output generated by this program is shown here:
// x is still known here. y is: -1
System.out.println("x is " + x); y is now: 100
} y is: -1
} y is now: 100
y is: -1
y is now: 100
Type Conversion and Casting

If the two types are compatible, then Java will perform the conversion automatically. For example, it is always possible to
assign an int value to a long variable. However, not all types are compatible, and thus, not all type conversions are implicitly
allowed. For instance, there is no automatic conversion defined from double to byte. Fortunately, it is still possible to obtain
a conversion between incompatible types. To do so, you must use a cast, which performs an explicit conversion between
incompatible types.

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

Here, target-type specifies the desired type to convert the specified value to. For example, the following fragment casts an int
to a byte. If the integer’s value is larger than the range of a byte, it will be reduced modulo (the remainder of an integer
division by the) byte’s range. Example.
int a; byte b;
b = (byte) a;
A different type of conversion will occur when a floating-point value is assigned to an integer type: truncation.
The following program demonstrates some type conversions b = (byte) d;
that require casts:
System.out.println("d and b " + d + " " + b);
// Demonstrate casts.
}
class Conversion {
}
public static void main(String args[]) {
This program generates the following output:
byte b;
Conversion of int to byte.
int i = 257;
i and b 257 1
double d = 323.142;
Conversion of double to int.
System.out.println("\nConversion of int to byte.");
d and i 323.142 323
b = (byte) i;
Conversion of double to byte.
System.out.println("i and b " + i + " " + b);
d and b 323.142 67
System.out.println("\nConversion of double to int.");
i = (int) d;
System.out.println("d and i " + d + " " + i);
System.out.println("\nConversion of double to byte.");
Arrays

An array is a group of like-typed (similar data type)variables that are referred to by a common name. Arrays of any type can
be created and may have one or more dimensions. A specific element in an array is accessed by its index. Arrays offer a
convenient means of grouping related information.

ONE DIMENSIONAL ARRAYS

MULTI DIMENSIONAL ARRAYS


One-Dimensional Arrays
A one-dimensional array is, essentially, a list of like-typed variables. To create an array, you first must create an array
variable of the desired type.
The general form of a one-dimensional array declaration has two things to do,
type array_var[ ]; and then, array-var = new type [size];

You can combine both in one statement like below,

type array_var[ ] = new type [size];

Here, type declares the element type (also called the base type) of the array. The element type determines the data type of
each element that comprises the array. Thus, the element type for the array determines what type of data the array will hold.
For example, the following declares an array named month_days with the type “array of int”:

1.First Step is declaration

int month_days[];

2.Next Step is to initialize/assign

Month_days = new int[12];


Arrays can be initialized when they are declared. . 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 you specify in the array initializer. There is no need to use new

class Main {
public static void main(String args[]) {
int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31,
30, 31 };
double reg_no[] = new double[50];
reg_no[0]= 1901721033035.0;
System.out.println("April has " + month_days[3] + " days.");
System.out.println("reg_no[0] is " +reg_no[0]);

}
}
Multidimensional Arrays

In Java, multidimensional arrays are actually arrays of arrays. These, as you might expect, look and act like regular
multidimensional arrays. However, as you will see, there are a couple of subtle differences. To declare a multidimensional
array variable, specify each additional index using another set of square brackets. For example, the following declares a two
dimensional array variable 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.
class TwoDArray {
public static void main(String args[]) {
int twoD[][]= new int[4][5];
OUTPUT
int i, j, k = 0; This program generates the following output:
for(i=0; i<4; i++) 01234
for(j=0; j<5; j++) { 56789
twoD[i][j] = k; 10 11 12 13 14
k++; 15 16 17 18 19
}
for(i=0; i<4; i++) {
for(j=0; j<5; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}
When you allocate memory for a multidimensional array, you need only specify the memory for the first (leftmost)
dimension. You can allocate the remaining dimensions

separately. For example, this following code allocates memory for the first dimension of twoD when it is declared. It
allocates the second dimension manually.

int twoD[][] = new int[4][]; // Manually allocate differing size for(i=0; i<4; i++) {
second dimensions. for(j=0; j<i+1; j++)
twoD[0] = new int[5]; class TwoDAgain { System.out.print(twoD[i][j] + " ");
public static void main(String args[]) { System.out.println();
twoD[1] = new int[5]; int twoD[][] = new int[4][]; }
twoD[0] = new int[1]; }
twoD[2] = new int[5]; twoD[1] = new int[2]; }
twoD[2] = new int[3]; This program generates the
twoD[3] = new int[5]; twoD[3] = new int[4]; following output:
int i, j, k = 0; 0
for(i=0; i<4; i++) 12
for(j=0; j<i+1; j++) { 345
twoD[i][j] = k; 6789
k++;
}
Alternative Array Declaration Syntax
There is a second form that may be used to declare an array:
type[ ] var-name;
Here, the square brackets follow the type specifier, and not the name of the array variable.
For example, the following two declarations are equivalent:
int al[] = new int[3];
int[] a2 = new int[3];
The following declarations are also equivalent:
char twod1[][] = new char[3][4];
char[][] twod2 = new char[3][4];
This alternative declaration form offers convenience when declaring several arrays at the
same time. For example,
int[] nums, nums2, nums3; // create three arrays
creates three array variables of type int. It is the same as writing
int nums[], nums2[], nums3[]; // create three arrays
The alternative declaration form is also useful when specifying an array as a return type for
a method
Operators
Java provides a rich operator environment. Most of its operators can be divided into the following four groups:
arithmetic, bitwise, relational, and logical. Java also defines some additional operators that handle certain
special situations
Some special operators are, instance of and (->) will be seen later.
Arithmetic Operators Arithmetic operators are used in mathematical expressions in the same way that they are
used in algebra. The following table lists the arithmetic operators:
Arithmetic Operators:
The operands of the arithmetic operators must be of a numeric type. You cannot use them on boolean types, but you can use
them on char types, since the char type in Java is, essentially, a subset of int.
The Basic Arithmetic Operators
The basic arithmetic operations—addition, subtraction, multiplication, and division—all behave as you would expect for all
numeric types. The unary minus operator negates its single operand. The unary plus operator simply returns the value of its
operand. Remember that when the division operator is applied to an integer type, there will be no fractional component
attached to the result.

// Demonstrate the basic arithmetic System.out.println("\nFloating Point


operators. Arithmetic"); When you run this program, you will see
class BasicMath { double da = 1 + 1; the following output:
public static void main(String args[]) { double db = da * 3; Integer Arithmetic
// arithmetic using integers double dc = db / 4; a=2
System.out.println("Integer Arithmetic"); double dd = dc - a; b=6
int a = 1 + 1; double de = -dd; c=1
int b = a * 3; System.out.println("da = " + da); d = -1
int c = b / 4; System.out.println("db = " + db); e=1
int d = c - a; System.out.println("dc = " + dc); Floating Point Arithmetic
int e = -d; System.out.println("dd = " + dd); da = 2.0
System.out.println("a = " + a); System.out.println("de = " + de); db = 6.0
System.out.println("b = " + b); } dc = 1.5
System.out.println("c = " + c); } dd = -0.5
System.out.println("d = " + d); de = 0.5
System.out.println("e = " + e);
// arithmetic using doubles
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. The following example program
demonstrates the %:
// Demonstrate the % operator.
class Modulus {
public static void main(String args[]) {
int x = 42;
double y = 42.25;
System.out.println("x mod 10 = " + x % 10);
System.out.println("y mod 10 = " + y % 10);
}
}
When you run this program, you will get the following output:
x mod 10 = 2
y mod 10 = 2.25
Arithmetic Compound Assignment Operators
Syntax: var op= expression;

Java provides special operators that can be used to combine an arithmetic operation with
an assignment. As you probably know, statements like the following are quite common in
programming:
a = a + 4;
In Java, you can rewrite this statement as shown here:
a += 4;
This version uses the += compound assignment operator. Both statements perform the same
action: they increase the value of a by 4.
Here is another example,
a = a % 2;
which can be expressed as
a %= 2;
In this case, the %= obtains the remainder of a /2 and puts that result back into a.
There are compound assignment operators for all of the arithmetic, binary operators.
Thus, any statement of the form
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. For example, this statement: x = x + 1; can be rewritten like this by use of
the increment operator: x++; Similarly, this statement: x = x - 1;
These operators are unique in that they can appear both in postfix form, where they follow the operand as just shown, and
prefix form, where they precede the operand. In the foregoing examples, there is no difference between the prefix and postfix
forms. However, when the increment and/or decrement operators are part of a larger expression, then a subtle, yet powerful,
difference between these two forms appears. In the prefix form, the operand is incremented or decremented before the value
is obtained for use in the expression. In postfix form, the previous value is obtained for use in the expression, and
then the operand is modified. For example:
x = 42;
y = ++x;
In this case, y is set to 43 as you would expect, because the increment occurs before x is
assigned to y. Thus, the line y = ++x; is the equivalent of these two statements:
x = x + 1;
y = x;
However, when written like this,
x = 42;
y = x++;
the value of x is obtained before the increment operator is executed, so the value of y is 42.
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. They are summarized in the following table:
The Bitwise Operators Working:

Left Shifts
When shifting left, the most-significant bit is lost, and a

0 bit is inserted on the other end.

0010 << 1 → 0100


0010 << 2 → 1000
A single left shift multiplies a binary number by 2:

0010 is 2
0100 is 4

Right Shifts
When shifting right with a logical right shift, the least-significant bit is lost
For positive numbers, a single logical right shift divides a number by 2, throwing out any remainders.
0100 is 4
0010 is 2
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.
// Demonstrate the bitwise logical operators. System.out.println(" a = " + binary[a]);
class BitLogic { System.out.println(" b = " + binary[b]);
public static void main(String args[]) { System.out.println(" a|b = " + binary[c]);
String binary[] = { System.out.println(" a&b = " + binary[d]);
"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", System.out.println(" a^b = " + binary[e]);
"1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111" System.out.println("~a&b|a&~b = " + binary[f]);
}; System.out.println(" ~a = " + binary[g]);
int a = 3; // 0 + 2 + 1 or 0011 in binary }
int b = 6; // 4 + 2 + 0 or 0110 in binary }
int c = a | b; Here is the output from this program:
int d = a & b; a = 0011
int e = a ^ b; b = 0110
int f = (~a & b)|(a & ~b); a|b = 0111
int g = ~a & 0x0f; a&b = 0010
a^b = 0101
~a&b|a&~b = 0101
~a = 1100
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. For each shift left, the high-order bit is shifted out
(and lost), and a zero is brought in on the right. This means that when a left shift is applied to an int operand,bits are lost
once they are shifted past bit position 31. If the operand is a long, then bits are lost after bit position 63

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.
>> operator automatically fills the high-order bit with its previous contents each time a shift occurs
// Left shifting as a quick way to multiply by 2. // Masking sign extension.
class MultByTwo { class HexByte {
public static void main(String args[]) { static public void main(String args[]) {
int i; char hex[] = {
int num = 0xFFFFFFE; '0', '1', '2', '3', '4', '5', '6', '7',
for(i=0; i<4; i++) { '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
num = num << 1; };
System.out.println(num); byte b = (byte) 0xf1;
} System.out.println("b = 0x" + hex[(b >> 4) &
} 0x0f] + hex[b & 0x0f]);
} }
The program generates the following output: }
536870908
1073741816 Here is the output of this program:
2147483632 b = 0xf1
-32
The Unsigned Right Shift
As you have just seen, the >> operator automatically fills the high-order bit with its previous contents each time a shift
occurs. This preserves the sign of the value. However, sometimes this is undesirable. For example, if you are shifting
something that does not represent a numeric value, you may not want sign extension to take place. This situation is common
when you are working with pixel-based values and graphics. In these cases, you will generally want to shift a zero into the
high-order bit no matter what its initial value was. This is known as an unsigned shift. To accomplish this, you will use
Java’s unsigned, shiftright operator, >>>, which always shifts zeros into the high-order bit. The following code fragment
demonstrates the >>>. Here, a is set to –1, which sets all 32 bits to 1 in binary. This value is then shifted right 24 bits, filling
the top 24 bits with zeros, ignoring normal sign extension. This sets a to 255.
Example: int a = -1; a = a >>> 24;
Bitwise Operator Compound Assignments
All of the binary bitwise operators have a compound form similar to that of the algebraic operators, which combines the
assignment with the bitwise operation. For example, the following two statements, which shift the value in a right by four
bits, are equivalent:
a = a >> 4; a >>= 4;
Likewise, 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. The relational operators are shown here:
Any type in Java, including integers, floating-point numbers, characters, and Booleans can be compared using the equality
test, ==, and the inequality test, !=. Notice that in Java equality is denoted with two equal signs, not one. (Remember: a
single equal sign is the assignment operator.) 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.
As stated, the result produced by a relational operator is a boolean value. 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
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.
The logical Boolean operators, &, |, and ^, operate on boolean values in the same way that they operate on the bits of an
integer. The logical ! operator inverts the Boolean state: !true == false and !false == true. The following table shows the
effect of each logical operation:
Short-Circuit Logical Operators
Java provides two interesting Boolean operators not found in some other computer languages. These are secondary versions
of the Boolean AND and OR operators, and are commonly known as short-circuit logical operators. As you can see from the
preceding table, the OR operator results in true when A is true, no matter what B is. Similarly, the AND operator results in
false when A is false, no matter what B is. If you use the || and && forms, rather than the | and & forms of these operators,
Java will not bother to evaluate the righthand operand when the outcome of the expression can be determined by the left
operand alone. This is very useful when the right-hand operand depends on the value of the left one in order to function
properly.
For example, the following code fragment shows how you can take advantage of short-circuit logical evaluation to be sure
that a division operation will be valid before evaluating it: if (denom != 0 && num / denom > 10) Since the short-circuit
form of AND (&&) is used, there is no risk of causing a run-time exception when denom is zero. If this line of code were
written using the single & version of AND, both sides would be evaluated, causing a run-time exception when denom is
zero.
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; Here, using a single & ensures that the increment operation
will be applied to e whether c is equal to 1 or not.
The Assignment Operator
The assignment operator is the single equal sign, =. The assignment operator works in Java much as it does in any other
computer language. It has this general form: var = expression; Here, the type of var must be compatible with the type of
expression. The assignment operator does have one interesting attribute that you may not be familiar with: it allows you to
create a chain of assignments.
For example, consider this fragment: int x, y, z; x = y = z = 100; // set x, y, and z to 100

The ? Operator
Java includes a special ternary (three-way) operator that can replace certain types of if-then-else statements. This operator is
the ?. It can seem somewhat confusing at first, but the ? can be used very effectively once mastered. 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. The result of the ? operation is that of
the expression evaluated. Both expression2 and expression3 are required to return the same (or compatible) type, which can’t
be void. Here is an example of the way that the ? is employed:
num=29;
denom == 0 ? ratio = 0 : ratio = num / denom;
Operator Precedence
Bemow Table shows the order of precedence for Java operators, from highest to lowest. Operators in the same row are equal
in precedence. In binary operations, the order of evaluation is left to right (except for assignment, which evaluates right to
left). Although they are technically separators, the [ ], ( ), and . can also act like operators. In that capacity, they would have
the highest precedence. Also, notice the arrow operator (->). It was added by JDK 8 and is used in lambda expressions.
Using Parentheses

Parentheses raise the precedence of the operations that are inside them.

This is often necessary to obtain the result you desire.

For example, consider the following expression: a >> b + 3

This expression first adds 3 to b and then shifts a right by that result.

That is, this expression can be rewritten using redundant parentheses like this: a >> (b + 3)

However, if you want to first shift a right by b positions and then add 3 to that result,

you will need to parenthesize the expression like this: (a >> b) + 3

In addition to altering the normal precedence of an operator, parentheses can sometimes be used to help clarify the meaning
of an expression.
import java.util.Scanner;

/**
* This program demonstrates various Scanner methods.
*/

public class ReadEmployee


{
public static void main(String[] args)
{
String name; // To hold the employee's name
int age; // To hold the employee's age
char gender; // To hold the employee's gender
double salary; // To hold the employee's salary

// Create a Scanner object to read input.


Scanner console = new Scanner(System.in);

// Get the employee's name


System.out.print( "Enter name: " );
name = console.nextLine();

// Get the employee's age


System.out.print( "Enter age: " );
age = console.nextInt();

// Get the employee's gender


System.out.print( "Enter gender: " );
gender = console.next().charAt(0);

// Get the employee's salary


System.out.print( "Enter salary: " );
salary = console.nextDouble();

// Display the information


System.out.println( "Name: " + name + " Age: " + age + " Gender: "
+ gender + " Salary: " + salary);

}
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:
1. selection
2. iteration
3. jump

1. Java’s Selection Statements


Java supports two selection statements: if and switch. These statements allow you to control the flow of your program’s
execution based upon conditions known only during run time.
The if statement is Java’s conditional branch statement. It can be used to route program execution through two different
paths. Here is the general form of the if statement:

if (condition) statement1; else statement2;

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. The if works like this: If the condition is
true, then statement1 is executed. Otherwise, statement2 (if it exists) is executed. In no case will both statements be
executed. For example, consider the following: int a, b; //... if(a < b) a = 0; else b = 0;
Nested ifs
A nested if is an if statement that is the target of another if or else. Nested ifs are very common in programming. When you
nest ifs, the main thing to remember is that an else statement always refers to the nearest if statement that is within the same
block as the else and that is not already associated with an else. Here is an example:
if(i == 10)
{
if(j < 20) a = b;
if(k > 100) c = d; // this if is
else a = c; // associated with this else
}
else a = d; // this else refers to if(i == 10)
The if-else-if Ladder
A common programming construct that is based upon a sequence of nested ifs is the if-elseif ladder. It looks like this:
if(condition) statement;
else if(condition) statement;
else if(condition) statement;
...
else statement;
The if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement
associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else
statement will be executed.
switch
The switch statement is Java’s multiway branch statement. It provides an easy way to dispatch execution to different parts of
your code based on the value of an expression. As such, it often provides a better alternative than a large series of if-else-if
statements. Here is the general form of a switch statement:
switch (expression) {
case value1: Expression can be of data type
// statement sequence byte,short,int,boolean and String.
break;
case value2: No duplicate values are allowed for case Values.
// statement sequence
break;
.
.
.
case valueN :
// statement sequence
break;
default:
// default statement sequence
}
Nested switch Statements

We can use a switch as part of the statement sequence of an outer switch. This is called a nested switch. Since a switch
statement defines its own block, no conflicts arise between the case constants in the inner switch and those in the outer
switch. For example, the following fragment is perfectly valid:
switch(count)
{
case 1:
switch(target)
{ // nested switch
case 0: System.out.println("target is zero");
break;
case 1: // no conflicts with outer switch
System.out.println("target is one");
break;
}
break;
case 2: // ...
Here, the case 1: statement in the inner switch does not conflict with the case 1: statement in the outer switch. The count
variable is compared only with the list of cases at the outer level. If count is 1, then target is compared with the inner list
cases.
Iteration Statements

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

while The while loop is Java’s most fundamental loop statement. It repeats a statement or block while its controlling
expression is true. Here is its general form:

while(condition)

{ // body of loop }

The condition can be any Boolean expression. The body of the loop will be executed as long as the conditional expression is
true. When condition becomes false, control passes to the next line of code immediately following the loop. The curly braces
are unnecessary if only a single statement is being repeated.
Example for while loop:
// Demonstrate the while loop.
class While {
public static void main(String args[]) {
int n = 10;
while(n > 0) {
System.out.println("tick " + n);
n--;
}
}
}
When you run this program, it will “tick” ten times:
tick 10
tick 9
tick 8
tick 7
tick 6
tick 5
tick 4
tick 3
tick 2
tick 1
An Empty While Loop:

The body of the while (or any other of Java’s loops) can be empty. This is because a null
statement (one that consists only of a semicolon) is syntactically valid in Java. For example,
consider the following program:
// The target of a loop can be empty.
class NoBody {
public static void main(String args[]) {
int i, j;
i = 100;
j = 200;
// find midpoint between i and j
while(++i < --j); // no body in this loop
System.out.println("Midpoint is " + i);
}
}
This program finds the midpoint between i and j. It generates the following output:
Midpoint is 150
do-while

As you just saw, if the conditional expression controlling a while loop is initially false, then the body of the loop will not be
executed at all. However, sometimes it is desirable to execute the body of a loop at least once, even if the conditional
expression is false to begin with. Fortunately, Java supplies a loop that does just that: the do-while. The do-while loop
always executes its body at least once, because its conditional expression is at the bottom of the loop. Its general form is

do

{ // body of loop

} while (condition);

Each iteration of the 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.
Do-while example:
// Demonstrate the do-while loop.
class DoWhile {
public static void main(String args[]) {
int n = 10;
do {
System.out.println("tick " + n);
n--;
} while(n > 0);
}
}
The loop in the preceding program, while technically correct, can be written more
efficiently as follows:
do {
System.out.println("tick " + n);
} while(--n >
For:

Beginning with JDK 5, there are two forms of the for loop. The first is the traditional form that has been in use since the
original version of Java. The second is the newer “for-each” form. Both types of for loops are discussed here, beginning with
the traditional form. Here is the general form of the traditional for statement:

for(initialization; condition; iteration)

{ // body

If only one statement is being repeated, there is no need for the curly braces.

The for loop operates as follows. When the loop first starts, the initialization portion of the loop is executed. It is important
to understand that the initialization expression is executed only 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 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
For example
Using the Comma
// Demonstrate the for loop. // Using the comma.
class ForTick { class Comma {
public static void main(String args[]) { public static void main(String args[]) {
int n;
int a, b;
for(a=1, b=4; a<b; a++, b--) {
for(n=10; n>0; n--)
System.out.println("a = " + a);
System.out.println("tick " + n);
System.out.println("b = " + b);
} }
} }
Declaring Loop Control Variables Inside the for Loop }
Often the variable that controls a for loop is needed only program generates the following output:
for the purposes of the loop and is not used elsewhere a=1
// Declare a loop control variable inside the for. b=4
class ForTick { a=2
public static void main(String args[]) { b=3
// here, n is declared inside of the for loop
for(int n=10; n>0; n--)
System.out.println("tick " + n);
}
}
The For-Each Version of the for Loop
Beginning with JDK 5, a second form of for was defined that implements a “for-each” style 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:
// Use a for-each style for loop.
for(type itr-var : collection) class ForEach {
statement-block public static void main(String args[]) {
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0; // use for-each style for to display and sum the values
for(int x : nums)
System.out.print("Value is: " + x); sum += x;
System.out.println("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
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. There are various types of
collections that can be used with the for, but the only type used in this chapter is the array.
Nested Loops
Like all other programming languages, Java allows loops to be nested. That is, one loop
may be inside another. For example, here is a program that nests for loops:
// Loops may be nested.
class Nested {
public static void main(String args[]) { The output produced by this program is shown here:
int i, j; ..........
for(i=0; i<10; i++) { .........
for(j=i; j<10; j++) ........
System.out.print("."); .......
System.out.println(); ......
} .....
} ....
} ...
..
.
Jump Statements

Java supports three jump statements: break, continue, and return. These statements transfer control to another part
of your program. Each is examined here.

Using break In Java, the break statement has three uses. First, as you have seen, it terminates a statement sequence in a
switch statement. Second, it can be used to exit a loop. Third, it can be used as a “civilized” form of goto

// Using break to exit a System.out.println("Loo // Using break as a civilized form of goto.


loop. p complete."); class Break {
public static void main(String args[]) {
class BreakLoop { } boolean t = true;
public static void }
first: {
second: {
main(String args[]) { This program generates third: {
System.out.println("Before the break.");
for(int i=0; i<100; i++) { the following output: if(t) break second; // break out of second block
if(i == 10) break; // i: 0 System.out.println("This won't execute");
}
i: 1
terminate loop if i is 10 i: 2
System.out.println("This won't execute");
}
System.out.println("i: " i: 3 System.out.println("This is after second block.");
i: 4
+ i); i: 5
}
}
} i: 6
i: 7
}
Running this program generates the following output:
i: 8 Before the break.
i: 9 This is after second block.
Loop complete.
Using continue

Sometimes it is useful to force an early iteration of a loop. That is, you might want to continue running the loop but stop
processing the remainder of the code in its body for this particular iteration

// Demonstrate continue.
class Continue { This code uses the % operator to check if i is even. If
public static void main(String args[]) { it is, the loop continues without
for(int i=0; i<10; i++) { printing a newline. Here is the output from this
System.out.print(i + " "); program:
if (i%2 == 0) continue; 01
System.out.println(""); 23
} 45
} 67
} 89
return
The last control statement is return. The return statement is used to explicitly return from a method. That is, it causes
program control to transfer back to the caller of the method. As such, it is categorized as a jump statement.

// Demonstrate return.
class Return {
public static void main(String args[]) {
boolean t = true;
System.out.println("Before the return.");
if(t) return; // return to caller
System.out.println("This won't execute.");
}
}

The output from this program is shown here:


Before the return.

You might also like