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

CH 2

Uploaded by

Tech With Sonu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

CH 2

Uploaded by

Tech With Sonu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 74

CHAPTER 2

JAVA PROGRAM BUILDING


ELEMENTS
JAVA TOKENS
• A Java program is basically a collection of classes.
• A class is defined by a set of declaration statements
and methods containing executable statements.
• Smallest individual units in a program are known as
tokens.
• The compiler recognizes them for building up
expressions and statements.
• In simple terms, a Java program is a collection of
tokens, comments and white spaces.
• Java language includes five types of tokens.
1. Reserved Keywords
2. Identifiers
3. Literals
4. Operators
5. Separators
JAVA CHARACTER SET
• The smallest units of Java language are the
characters used to write Java tokens.
• These characters are defined by the Unicode
character set, and emerging standard that tries
to create characters for a large number of scripts
worldwide.
• The Unicode is a 16-bit character coding system
and currently supports more than 34,000 defined
characters derived from 24 languages from
America, Europe, Middle East, Africa and Asia
(including India).
KEYWORDS
• Java language has reserved 60 words as keywords.
• Since keywords have specific meaning in Java, we cannot use them as
names for variables, classes, methods and so on.
• All keywords are to be written in lower-case letters.

abstract boolean break byte byvalue*

case east* catch char class

const* continue default do double

else extends false** final finally


float for future* generic* goto*

if implements import inner* instanceof


int interface long native new

null** operator* outer* package private

protected public rest* return short

static super switch synchronized this

threadsafe* throw throws transient true**

try var* void volatile while


IDENTIFIERS
• Identifiers are programmer-designed tokens.
• They are used for naming classes, methods, variables,
objects, labels, packages and interface in a program. Java
identifiers follow the following rules:
1. They can have alphabets, digits, underscore and dollar
sign characters.
2. They must not begin with a digit.
3. Uppercase and lowercase letters are distinct.
4. They can be of any length.
• Identifier must be meaningful, short enough to be quickly
and easily typed and long enough to be descriptive and
easily read.
• Java developers have followed some naming conventions.
• Names of all public methods and instance variables start
with a leading lowercase letter.
Examples:
average
sum
IDENTIFIERS
 When more than one words are used in a name, the second
and subsequent words are marked with a leading uppercase
letters. Examples:
dayTemperature
firstDayOfMonth
totalMarks
 All private and local variables use only lowercase letters
combined with underscrores.
Example:
length
batch_strength
 All classes and interfaces start with a leading uppercase letter
(and each subsequent word with a leading uppercase letter).
Examples: Student, HelloJava
 Variables that represent constant values use all uppercase
letters and underscores between words.
Examples: TOTAL, F_MAX, PRINCIPLE_AMOUNT
LITERALS AND OPERATORS
• Literals in Java are a sequence of characters
(digits, letters, and other characters) that
represent constant values to be stored in
variables. Java language specifies five major types
of literals. They are:
Integer literals
Floating_point literals
Character literals
String literals
Boolean literals
• An operator is a symbol that takes one
or more arguments and operates on
them to produce a result.
SEPARATORS
VARIABLES
• A variable is an identifier that denotes a storage location used to store a data value.
• Unlike constants that remain unchanged during the execution of a program, a
variable may take different values at different times during the execution of the
program.
• A variable name can be chosen by the programmer in a meaningful way so as to
reflect what it represents in the program. Some examples of variable names are:
 Average
 total_height
 classStrength
• variable names may consist of alphabets, digits, the underscore(_) and dollar
characters, subject to the following conditions:
– They must not begin with a digit.
– Uppercase and lowercase are distinct. This means that the variable Total is not
the same as total or TOTAL.
– It should not be a keyword.
– White space is not allowed.
– Variable names can be of any length.
SCOPE OF VARIABLES

• The area of the program where the variable is


accessible is called its scope.
• Java variable are actually classified in 3 kinds:
Local variable
Instance variables
Class 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.
• Local variables are visible only within the declared
method, constructor or block.
• There is no default value for local variables so local
variables should be declared and an initial value should
be assigned before the first use.
EXAMPLE OF LOCAL VARIABLES
public class LocalTest
{
public void studAge()
{
int age = 0; //LOCAL VARIABLE
age = age + 18;
System.out.println(“Student’s age is : " + age);
}
public static void main(String args[])
{
LocalTest test = new LocalTest();
test.StudAge();
}
}
INSTANCE VARIABLES
• Instance variables are declared in a class, but outside a method,
constructor or any block.
• When a space is allocated for an object in the heap, a slot for each
instance variable value is created.
• Instance variables are created when an object is created with the use of
the keyword 'new' and destroyed when the object is destroyed.
• Instance variables hold values that must be referenced by more than
one method, constructor or block, or essential parts of an object's state
that must be present throughout the class.
• Instance variables can be declared in class level before or after use.
• Access modifiers can be given for instance variables.
• The instance variables are visible for all methods, constructors and block
in the class.
• Normally, it is recommended to make these variables private (access
level). However visibility for subclasses can be given for these variables
with the use of access modifiers.
• Instance variables have default values. For numbers the default value is
0, for Booleans it is false and for object references it is null. Values can
be assigned during the declaration or within the constructor.
CLASS VARIABLES
• Class variables are global to class and belong to
all the objects of the class.
• Only one memory location is created for each
class variable.
• Class variables also known as static variables are
declared with the static keyword in a class, but
outside a method, constructor or a block.
• There would only be one copy of each class
variable per class, regardless of how many
objects are created from it.
BLOCK
 A block is begun with an opening curly brace and ended by a closing curly brace.
 Each time a new block is started, a new scope is created that determines what
objects are visible to other parts of your program and lifetime of those objects.
 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. The scope rules
provide the foundation for encapsulation.
 Scopes can be nested. For example, each time you create a block of code, you
are creating a new, nested scope. When this occurs, the outer scope encloses the
inner scope.
 This means that 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.
 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.
 Therefore, variables declared within a method will not hold their values between
calls to that method. 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.
DECLARATION OF VARIABLES
• Declaration does three things:
 It tells the compiler what the variable name is.
 It specifies what type of data the variable will hold.
 The place of declaration (in the program) decides the scope of the
variable.
 The general form of declaration of a variable is:
type variable1, variable2, .........., variableN;
 Variables are separated by commas.
 A declaration statement must end with a semicolon.
 Some valid declarations are:
int count;
float x, y;
double pi;
byte b;
char c1, c2, c3;
INITIALIZATION
• The process of giving initial values to
variables is known as the initialization.
• For exmaple:
int finalValue=100;
char yes=‘X’;
double total=75.36;
DATA TYPES
• 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
in method calls, are checked for type compatibility.
• There are no automatic coercions or conversions of
conflicting types as in some languages.
• 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.
• In C/C++ you can assign a floating-point value to an
integer. In Java, you cannot.
• Also, in C there is not necessarily strong type-checking
between a parameter and an argument.
DATA TYPES
DATA TYPES
Type Size Minimum value Maximum value

byte 1 byte -128 127

short 2 bytes -32, 768 32,767

int 4 bytes -2, 147, 483, 648 2, 147, 483, 647

long 8 bytes -9, 223, 372, 036, 854, 775, 9, 223, 372, 036, 854, 775, 807
808

float 4 bytes 3.4e-038 3.4e+038

Double 8 bytes 1.7e-308 1.7e+308


INTEGERS
• The width of an integer type should not be
thought of as the amount of storage it consumes,
but rather as the behavior it defines for variables
and expressions of that type.
• The Java run-time environment is free to use
whatever size it wants, as long as the types
behave as you declared them.
• In fact, at least one implementation stores bytes
and shorts as 32-bit (rather than 8- and 16-bit)
values to improve performance, because that is
the word size of most computers currently in use.
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.
• Any time you have an integer expression involving bytes, shorts,
ints, and literal numbers, the entire expression is promoted to
int before the calculation is done.
• The “int” type is the most versatile and efficient type, and it
should be used most of the time when you want to create a
number for counting or indexing arrays or doing integer math.
• It may seem that using short or byte will save space, but there
is no guarantee that Java won’t promote those types to “int”
internally anyway.
• Remember, type determines behavior, not size. (The only
exception is arrays, where byte is guaranteed to use only one
byte per array element, short will use two bytes, and “int” will
use four.)
float
• The type float specifies a single-precision value that
uses 32 bits of storage.
• Single precision is faster on some processors and takes
half as much space as double precision, but will
become imprecise when the values are either very
large or very small.
• Variables of type float are useful when you need a
fractional component, but don’t require a large degree
of precision. For example, float can be useful when
representing dollars and cents.
• We must append f or F to the floating numbers.
• Example:
 1.23f
 7.56923E5F
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.
• When you need to maintain accuracy over many
iterative calculations, or are manipulating large-
valued numbers, double is the best choice.
CHARACTER TYPE
• In order to store character constants in memory, Java provides a
character data type called char.
• The char type assumes a size of 2 bytes but, basically, it can hold only a
single character.
• WHY CHAR IN JAVA IS OF 2 BYTES?
• Characters in C are ASCII characters. There are only 256 different
characters in the ASCII character set, and so 8-bits are enough to store
this data.
• Java uses unicode to represent characters.
• Unicode defines a fully international character set that can represent all
of the characters found in human languages.
• It is unification of dozens of characters sets such as LATIN,GREEK,ARABIC
etc.
• For this purpose it requires 16 bits.
• Thus in java char is a 16-bit type(2 bytes).
• Since java is designed to allow applets to be written for worldwide use, it
makes sense that it would use unicode to represent characters.
• This is inefficient for languages such as English, German etc that requires
only 8 bits representation.
BOOLEAN TYPE
• Boolean type is used when we want to test a particular
condition during the execution of the program.
• There are only two values that a boolean type can take:
true or false. Remember, both these words have been
declared as keywords.
• Boolean type is denoted by the keyword boolean, and uses
only one bit of storage.
• 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, they can only be assigned to variables declared as
boolean, or used in expressions with Boolean operators.
INTEGER LITERALS
• Integer numbers can be presented in decimal, octal and
hexadecimal.
• Decimal integer consists of set of digits 0 to 9 preceded by an
optional – sign.
– Ex. 123, – 321, 0, 65421
• Spaces, commas & non-digit characters are not permitted between
digits.
– Ex. 20,000 , $ 100 are invalid
• Octal integer constants consists of any combination of digits from 0
to 7 with leading 0. So, 15 is considered as a decimal number but
015 as octal.
– Ex. 037 0 0435 0551
• Hexadecimal integer consists of digits preceded by 0X or 0x.
• It may include alphabets A – F or a – f .
– Ex. 0X2 0X9F 0Xbcad
REAL LITERALS
• Numbers with fractional parts like 17.548, Such
numbers are called real numbers. (floating point)
– Ex. 0.00083 -0.75 435.12
• Can also be expressed in exponential (scientific)
notation.
– Ex. 215.65 may be written as 2.1565e2
• E2 = 102
• They are useful to represent number, that is either
very large or very small.
• Ex. 750000000 = 75E7
• - 0.000000368 = - 3.68 E-7
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.
• 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, which 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 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\””
• Java strings must begin and end on the same line.
• There is no line-continuation escape sequence as there is in
other languages.
• In C/C++, strings are implemented as arrays of characters.
• However, this is not the case in Java. Strings are actually
object types.
• Because Java implements strings as objects, Java includes
extensive string-handling capabilities that are both
powerful and easy to use.
CONSTANTS
• PI = 3.142
• Constants may appear repeatedly in number of places in
the program.
• Constants can be declared as final variables as follows:
final int STRENGTH = 100
final float PI = 3.14159f;
• Once declared not be assigned another value.
• For ex: STRENGTH = 200 is not possible.
• It is considered good practice to represent final constants
in all uppercase, using underscore to separate words.
• They can not be declared inside a method.
• They should be used only as class data members in the
beginning of the class.
TYPE CONVERSION AND CASTING
• It is fairly common to assign a value of one type to a
variable of another type.
• 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 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.
• Eg: The int type is large enough to hold all byte values, so no
explicit cast statement is required.
• For widening conversions, the numeric types, including integer
and floating-point types, are compatible with each other.
• However, the numeric types are not compatible with char or
boolean.
• Also, char and boolean are not compatible with each other.
• Java also performs an automatic type conversion when storing a
literal integer constant into variables of type byte, short, or long.
CASTING INCOMPATIBLE TYPES
• To create a conversion between two incompatible types, you must
use a cast. A cast is simply an explicit type conversion.
• It is known as narrowing conversion also.
• Syntax:
(target-type) value
• Here, target-type specifies the desired type to convert the
specified value to.
• 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.
– int a;
– byte b;
– b = (byte) a;
• A different type of conversion will occur when a floating-point
value is assigned to 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.
CASTING WITHOUT LOSS OF DATA
TYPE PROMOTION IN EXPRESSIONS
• In expressions certain type conversions may occur:
byte a = 40;
byte b = 50;
byte c = 100;
int d = a * b / c;
• In an expression, the precision required of an intermediate value
will sometimes exceed the range of either operand.
• To handle this kind of problem, Java automatically promotes each
byte or short operand to int when evaluating an expression.
• This means that the subexpression a * b is performed using
integers—not bytes.
• Thus, 2,000, the result of the intermediate expression, 50 * 40, is
legal even though a and b are both specified as type byte.
TYPE PROMOTION IN EXPRESSIONS
• As useful as the automatic promotions are, they can cause confusing compile-time
errors.
byte b = 50;
b = b * 2; // Error! Cannot assign an int to a byte!
• The code is attempting to store 50 * 2, a perfectly valid byte value, back
into a byte variable.
• Because the operands were automatically promoted to int when the
expression was evaluated, the result has also been promoted to int.
• Thus, the result of the expression is now of type int, which cannot be
assigned to a byte without the use of a cast.
• This is true even if, as in this particular case, the value being assigned
would still fit in the target type.
• In cases where you understand the consequences of overflow, you
should use an explicit cast, such as
byte b = 50;
b = (byte)(b * 2);
• which yields the correct value of 100.
TYPE PROMOTION RULES
• First, all byte and short values are promoted
to int, as just described.
• Then, if one operand is a long, the whole
expression is promoted to long.
• If one operand is a float, the entire expression
is promoted to float.
• If any of the operands is double, the result is
double.
EXAMPLE: TYPE PROMOTION RULES
byte b = 42;
char c = 'a';
short s = 1024;
int i = 50000;
float f = 5.67f;
double d = .1234;
result = (f * b) + (i / c) - (d * s);
• What is the datatype of “result”?
STANDARD DEFAULT VALUES
Byte 0
Short 0
Int 0
Long 0L
Float 0.0F
Double 0.0D
Char Null
Boolean false
COMMAND LINE ARGUMENTS
• Sometimes you will want to pass information into
a program when you run it.
• This is accomplished by passing command-line
arguments to main( ).
• A command-line argument is the information that
directly follows the program’s name on the
command line when it is executed.
• To access the command-line arguments inside a
Java program is quite easy—they are stored as
strings in the String array passed to main( ).
• All command-line arguments are passed as
strings. You must convert numeric values to their
internal forms manually.
ARRAY
• An Array is a group of like-typed variables that
referred to by a common name.
• Array 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.
• If you are familiar with C/C++, be careful.
• Arrays in Java work differently than they do in
those languages.
ONE-DIMENSIONAL ARRAY
• A one-dimensional array is a list of like-typed variables.
• To create an array, you first must create an array variable of the desired type.
The general form of a one-dimensional array declaration is
• Syntax : type var-name[ ];
• Here, type declares the base type of the array. The base type determines the
data type of each element that comprises the array. Thus, the base type for
the array determines what type of data the array will hold.
• The following declares an array named month_days with the type “array of
int”:
– int month_days[];
• The value of month_days is set to null, which represents an array with no
value.
• 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 general form of new as it applies to one-dimensional arrays appears as
follows:
array-var = new type[size];
month_days[] = new int[12];
• The elements in the array allocated by “new” will automatically be initialized
to zero.
INITIALIZING AN ARRAY
• It is possible to combine the declaration of the array
variable with the allocation of the array itself, as shown
here:
int month_days[] = new int[12];
• Once you have allocated an array, you can access a
specific element in the array by specifying its index
within square brackets.
• All array indexes start at zero. For example, this
statement assigns the value 28 to the second element of
month_days.
month_days[1] = 28;
• If you try to access elements outside the range of the
array (negative numbers or numbers greater than the
length of the array), you will cause a run-time error.
INITIALIZING AN ARRAY
• Arrays can be initialized when they are declared.
• The process is much the same as that used to
initialize the simple types.
• An array initializer is a list of comma-separated
expressions surrounded by curly braces.
• 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”.
int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
MULTIDIMENSIONAL ARRAYS
• In Java, multidimensional arrays are actually arrays of arrays.
• To declare a multidimensional array variable, specify each
additional index using another set of square brackets.
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.
• 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.
int twoD[][] = new int[4][];
twoD[0] = new int[5];
twoD[1] = new int[5];
twoD[2] = new int[5];
twoD[3] = new int[5];
MULTIDIMENSIONAL ARRAYS
• It is possible to initialize multidimensional arrays.
• To do so, simply enclose each dimension’s initializer
within its own set of curly braces.
• The following program creates a matrix where each
element contains the product of the row and column
indexes.
• Also notice that you can use expressions as well as
literal values inside of array initializers.
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 }
};
OPERATORS
• Arithmetic Operators (+,-,*,/,%)
• Assignment Operator.(=)
• Increment and decrement Operators.(++,--)
• Relational Operators (==,<,>,>=,<=,!=)
• Boolean Logical Operator(&,|,^ etc…).
• Ternary Operator(?)
• Bitwise Operators.(~,&,| etc…)
ARITHMATIC 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 minus operator also has a unary form which
negates its single operand.
• Remember that when the division operator is applied
to an integer type, there will be no fractional
component attached to the result.
• The modulus operator, %, returns the remainder of a
division operation.
• It can be applied to floating-point types as well as
integer types.
ASSIGNMENT OPERATOR(=)
• Java provides special operators that can be used to
combine an arithmetic operation with an
assignment.
a = a + 4;
a += 4;
• There are assignment operators for all of the
arithmetic, binary operators.
• The assignment operators provide two benefits. First,
they save you a bit of typing, because they are
“shorthand” for their equivalent long forms.
• Second, they are implemented more efficiently by
the Java run-time system than are their equivalent
long forms.
THE BITWISE OPERATORS
• Bitwise operators can be applied to the integer types, long, int,
short, char, and byte.
• These operators act upon the individual bits of their operands.
1. ~ Bitwise unary NOT
2. & Bitwise AND
3. | Bitwise OR
4. ^ Bitwise exclusive OR
5. >> Shift right
6. >>> Shift right zero fill
7. << Shift left
8. &= Bitwise AND assignment
9. |= Bitwise OR assignment
10. ^= Bitwise exclusive OR assignment
11. >>= Shift right assignment
12. >>>= Shift right zero fill assignment
13. <<= Shift left assignment
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.
• For each shift left, the high-order bit is shifted out (and lost), and a zero is
added on the right.
• Example:
byte b = 10;
b<<2
then,
10 is 0000 1010
<<2 is 0010 1000
• Each left shift multiplies the original value by two.
• So, programmers frequently use this fact as an efficient alternative to
multiplying by 2.
THE RIGHT SHIFT
• The right shift operator, >>, shifts all of the bits in a value to the right a
specified number of times.
value >> num
• Here, num specifies the number of positions to right-shift the value.
• The following code fragment shifts the value 32 to the right by two positions,
resulting in a being set to 8:
byte a = 32;
a = a >> 2; // a now contains 8
32 ---- > 0010 0000
>>2 ---- > 0000 1000
• Each time a value is shifted to the right, it divides that value by two—and
discards any remainder.
• In shifting right, the top (leftmost) bits are filled in with the previous contents of
the top bit.
• This is called sign extension and used to preserve the sign of negative numbers
when they are shifted right.
• For example, –8 >> 1 is –4, which, in binary, is 11111000
• –8 >>1
• 11111100 –4
THE UNSIGNED RIGHT SHIFT
• The >> operator automatically fills the high-order bit with
its previous contents each time a shift is performed.
• This preserves the sign of the value.
• Sometimes this is undesirable, when the value is not the
numeric value.
• In these cases only zero should be added into the high-
order bit on each shift no matter what its initial value was.
• This is known as an unsigned shift.
• Unsigned shift-right operator, >>>, is used for that purpose,
which always shifts zeros into the high-order bit.
byte a = 15;
a = a >>> 3
0000 1111 –>15 in binary
>>>3
0000 0001
BOOLEAN LOGICAL OPERATORS
• The Boolean logical operators operate only on boolean
operands.
• All of the binary logical operators combine two boolean
values to form a resultant boolean value.
1. & Logical AND
2. | Logical OR
3. ^ Logical XOR (exclusive OR)
4. || Short-circuit OR
5. && Short-circuit AND
6. ! Logical unary NOT
7. &= AND assignment
8. |= OR assignment
9. ^= XOR assignment
10. = = Equal to
11. != Not equal to
12. ?: Ternary if-then-else
BOOLEAN LOGICAL OPERATORS
RELATIONAL OPERATORS
• The relational operators determine the relationship that one operand has to
the other.
= = equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
• The outcome of these operations is a boolean value.
• Integers, floating-point numbers, characters, and Booleans can be compared
using the equality test, ==, and the inequality test, !=.
• Only integer, floating-point, and character operands may be compared to see
which is greater or less than the other.
• The reason is that Java does not define true and false in the same way as
C/C++.
• In Java, true and false are non numeric values which do not relate to zero or
nonzero.
SHORT-CIRCUIT LOGICAL OPERATORS
• Short-circuit logical operators are secondary versions of the Boolean
AND and OR operators, the OR operator results in true when the first
condition is true, no matter what the outcome of second condition is.
• Similarly, the AND operator results in false when the first condition is
true, no matter what the outcome of second condition is.
• If you use the || and && forms, rather than the | and & forms of these
operators, Java will not evaluate the second expression when the
outcome of the expression can be determined by the first expression
alone.
• This is very useful when the execution of second expression depends on
the outcome of first expression.
• For example,
if (denom != 0 && num / denom > 10)
• Here, the division operation will be performed only when the value of
demon is not zero. So, there is no risk of divide by zero error.
THE ? OPERATOR
• It is ternary (three-way) operator that can replace
certain types of if-then-else statements.
• General form:
expression1 ? expression2 : expression3
• Here, expression1 can be any expression that
gives a boolean value.
• If expression1is true, then expression2 is
evaluated; otherwise, expression3 is evaluated.
• Both expression2 and expression3 are required to
return the same type, which can’t be void.
• Example:
int ans = a >= b ? a : b
OPERATOR PRECEDENCE
INTRODUCING CLASSES
class ClassName
{ type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodName1(parameter-list) {
// body of method
}
type methodName2(parameter-list) {
// body of method
}
// ...
type methodNameN(parameter-list) {
// body of method
}
• }
DECLARING OBJECTS
• Box mybox = new Box();
» OR
• Box mybox; // declare reference to object
• mybox = new Box(); // allocate a Box object
DECLARING OBJECTS
• A class creates a logical framework that defines the relationship
between its members.
• When you declare an object of a class, you are creating an instance of
that class.
• Thus, a class is a logical construct. An object has physical reality.
• As just explained, the new operator dynamically allocates memory for
an object.
• It has this general form:
class-var = new ClassName( );
• Here, class-var is a variable of the class type (i.e. Object) being created.
The ClassName is the name of the class that is being instantiated.
• It is important to understand that new allocates memory for an object
during run time.
• The advantage of this approach is that your program can create as many
or as few objects as it needs during the execution of your program.
• However, since memory is finite, it is possible that new will not be able
to allocate memory for an object because insufficient memory exists. If
this happens, a run-time exception will occur.
ASSIGNING OBJECT REFERENCE
VARIABLES
• Box b1 = new Box(); Box b2 = b1;
• Here b1 and b2 will both refer to the same object.
• The assignment of b1 to b2 did not allocate any memory or
copy any part of the original object.
• It simply makes b2 refer to the same object as does b1.
• Thus, any changes made to the object through b2 will affect the
object to which b1 is referring, since they are the same object.
ASSIGNING OBJECT REFERENCE
VARIABLES
• Although b1 and b2 both refer to the same object, they are not
linked in any other way.
• For example, a subsequent assignment to b1 will simply unhook b1
from the original object without affecting the object or affecting b2.
• For example:
• Box b1 = new Box();
• Box b2 = b1;
• // ...
• b1 = null;

• Here, b1 has been set to null, but b2 still points to the original
object.
CONSTRUCTORS
• A constructor initializes an object immediately upon
creation.
• It has the same name as the class in which it resides and is
syntactically similar to a method.
• Once defined, the constructor is automatically called
immediately after the object is created, before the new
operator completes.
• Constructors look a little strange because they have no
return type, not even void.
• This is because the implicit return type of a class’
constructor is the class type itself.
• It is the constructor’s job to initialize the internal state of
an object so that the code creating an instance will have a
fully initialized, usable object immediately.
TYPES OF CONSTRUCTORS
• Copy Constructor
• Parameterized Constructor
• Default Constructor
INSTANCE VARIABLE HIDING
• It is illegal in Java to declare two local variables with the same name inside the same
or enclosing scopes. You can have local variables, including formal parameters to
methods, which overlap with the names of the class’ instance variables.
• When a local variable has the same name as an instance variable, the local variable
hides the instance variable.
• This is why width, height, and depth were not used as the names of the parameters
to the Box( ) constructor inside the Box class.
• If they had been, then width would have referred to the formal parameter, hiding
the instance variable width.
• It is usually easier to simply use different names, there is another way around this
situation.
• Because this lets you refer directly to the object, you can use it to resolve any name
space collisions that might occur between instance variables and local variables.
Box(double width, double height, double depth) {
this.width = width;
this.height = height;
this.depth = depth;
}
THE finalize( ) METHOD
• If an object is holding some non-Java resource such as a file handle or window character
font, then you might want to make sure these resources are freed before an object is
destroyed.
• By using finalization, you can define specific actions that will occur when an object is just
about to be reclaimed by the garbage collector.
• The Java run time calls the finalize( ) method whenever it is about to recycle an object of
that class.
• The garbage collector runs periodically, checking for objects that are no longer
referenced by any running state or indirectly through other referenced objects. Right
before an asset is freed, the Java run time calls the finalize( ) method on the object.
protected void finalize( )
{ // finalization code here }
• Te keyword protected is a specifier that prevents access to finalize( ) by code defined
outside its class.
• It is important to understand that finalize( ) is only called just prior to garbage collection,
not when an object goes out-of-scope. So you cannot know when—or even if—finalize( )
will be executed.
• Your program should provide other means of releasing system resources, etc., used by
the object.
• It must not rely on finalize( ) for normal program operation.
ACCESS CONTROL
• Java’s access specifiers are public, private, and protected. Java
also defines a default access level.
• protected applies only when inheritance is involved.
• When a member of a class is modified by the public specifier,
then that member can be accessed by any other code.
• When a member of a class is specified as private, then that
member can only be accessed by other members of its class.
• Now you can understand why main( ) has always been
preceded by the public specifier. It is called by code that is
outside the program—that is, by the Java run-time system.
• When no access specifier is used, then by default the member
of a class is public within its own package, but cannot be
accessed outside of its package.
• NOTE: Check the programs explained in class for overloading
and method arguments and return type.
ACCESS CONTROL
THE Object CLASS
• There is one special class, Object, defined by Java.
• All other classes are subclasses of Object.
• That is, Object is a superclass of all other classes.
• This means that a reference variable of type
Object can refer to an object of any other class.
• Also, since arrays are implemented as classes, a
variable of type Object can also refer to any array.
• Object defines the many methods, which means
that they are available in every object.
• The methods getClass( ), notify( ), notifyAll( ), and
wait( ) are declared as final. You may override the
others.
THE Object CLASS

You might also like