Unit-1 Basic Syntactical Concepts in Java: Introduction To Object-Oriented Paradigm
Unit-1 Basic Syntactical Concepts in Java: Introduction To Object-Oriented Paradigm
Unit-1 Basic Syntactical Concepts in Java: Introduction To Object-Oriented Paradigm
The data of an object can be accessed only by the methods associated with that object.
However, methods of one object can access the methods of other objects. Some of the
features of object-oriented paradigm are:
Emphasis is on data rather than procedure.
Programs are divided into what are known as Objects.
Data structures are designed such that they characterize the objects.
Methods that operate on the data of an object are tied together in the data structure.
Data is hidden and cannot be accessed by external functions.
Objects may communicate with each other through methods.
New data and methods can be easily added whenever necessary.
Follows bottom-up approach in program design.
Object: STUDENT
DATA
Name
Address
Marks
METHODS
Total()
Average()
Each object holds data and code to operate the data. Object can interact without having to
identify the details of each other‗s data or code. It is sufficient to identify the type of
message received and the type of reply returned by the objects.
Another example of object is CAR
Object: CAR
DATA
Colour
Cost
METHODS
LockIt()
DriveIt()
Fig.1.2 Representation of object CAR
Fig.1.1and Fig.1.2 shows actual representation of object.
2. Classes
A class is a set of objects with similar properties (attributes), common behaviour
(operations), and common link to other objects. The complete set of data and code of an object
can be made a user defined data type with the help of class.
The objects are variable of type class. A class is a collection of objects of similar type.
Classes are user defined data types and work like the build in type of the programming
language. Once the class has been defined, we can make any number of objects belonging to
that class. Each object is related with the data of type class with which they are formed.
As we learned that, the classification of objects into various classes is based on its properties
(States) and behaviour (methods). Classes are used to distinguish are type of object from
another. The important thing about the class is to identify the properties and procedures and
applicability to its instances.
For example:Vehicle
Vehicle
Car
MH 01
- EP 1234
COST=4,00,000 COLOUR=Red
3. Data Abstraction
Data abstraction refers to the act of representing important description without including
the background details or explanations.
Classes use the concept of abstraction and are defined as a list of abstract attributes such as
size, cost and functions operate on these attributes. They summarize all the important
properties of the objects that are to be created. Classes use the concepts of data abstraction and
it is called as Abstract Data Type (ADT).
4. Data Encapsulation
Data Encapsulation means wrapping of data and functions into a single unit (i.e. class). It is
most useful feature of class. The data is not easy to get to the outside world and only those
functions which are enclosed in the class can access it.
These functions provide the boundary between Object‗s data and program. This insulation of
data from direct access by the program is called as Data hiding.
5. Inheritance
Inheritance is the process by which objects of one class can get the properties of objects of
another class. Inheritance means one class of objects inherits the data and behaviours from
another class. Inheritance maintains the hierarchical classification in which a class inherits
from its parents.
Inheritance provides the important feature of OOP that is reusability. That means we can
include additional characteristics to an existing class without modification. This is possible
deriving a new class from existing one.
In other words, it is property of object-oriented systems that allow objects to be built from
other objects. Inheritance allows openly taking help of the commonality of objects when
constructing new classes. Inheritance is a relationship between classes where one class is the
parent class of another (derived) class. The derived class holds the properties and behaviour of
base class in addition to the properties and behaviour of derived class.
For Example:
Vehicle
Car
Hyundai
Santro Accent
Fig.1.4 Inheritance
In Fig.1.4, the Santro is a part of the class Hyundai which is again part of the class car and car
is the part of the class vehicle. That means vehicle class is the parent class.
6. Polymorphism
(Poly means ―many and morph means ―form). Polymorphism means the ability to take more
than one form. Polymorphism plays a main role in allocate objects having different internal
structures to share the same external interface. This means that a general class of operations
may be accessed in the same manner even though specific activities associated with each
operation may differ. Polymorphism is broadly used in implementing inheritance.
It means objects that can take on or assume many different forms. Polymorphism means that
the same operations may behave differently on different classes. Polymorphism allows us to
write generic, reusable code more easily, because we can specify general instructions and
delegate the implementation detail to the objects involved.
For Example:
In a pay roll system, manager, office staff and production worker objects all will respond to the
compute payroll message, but the real operations performed are object particular.
Shape
Draw()
JAVA FEATURES
As we know that the Java is an object oriented programming language developed by Sun
Microsystems of USA in 1991. Java is first programming language which is not attached with
any particular hardware or operating system. Program developed in Java can be executed
anywhere and on any system.
Features of Java are as follows:
1. Compiled and Interpreted
2. Platform Independent and portable
3. Object- oriented
4. Robust and secure
5. Distributed
6. Familiar, simple and small
7. Multithreaded and Interactive
8. High performance
9. Dynamic and Extensible
1. Compiled and Interpreted
Basically a computer language is either compiled or interpreted. Java comes together
both these approach thus making Java a two-stage system.
Java compiler translates Java code to Bytecode instructions and Java Interpreter generate
machine code that can be directly executed by machine that is running the Java program.
2. Platform Independent and portable
Java supports the feature portability. Java programs can be easily moved from one
computer system to another and anywhere. Changes and upgrades in operating systems,
processors and system resources will not force any alteration in Java programs. This is
reason why Java has become a trendy language for programming on Internet which
interconnects different kind of systems worldwide. Java certifies portability in two ways.
First way is, Java compiler generates the bytecode and that can be executed on any
machine. Second way is, size of primitive data types are machine independent.
3. Object- oriented
Java is truly object-oriented language. In Java, almost everything is an Object. All program
code and data exist in objects and classes. Java comes with an extensive set of classes;
organize in packages that can be used in program by Inheritance. The object model in Java is
trouble-free and easy to enlarge.
4. Robust and secure
Java is a most strong language which provides many securities to make certain reliable
code. It is design as garbage –collected language, which helps the programmers virtually from
all memory management problems. Java also includes the concept of exception handling,
which detain serious errors and reduces all kind of threat of crashing the system.
Security is an important feature of Java and this is the strong reason that programmer
use this language for programming on Internet.
The absence of pointers in Java ensures that programs cannot get right of entry to memory
location without proper approval.
5. Distributed
Java is called as Distributed language for construct applications on networks which can
contribute both data and programs. Java applications can open and access remote objects on
Internet easily. That means multiple programmers at multiple remote locations to work
together on single task.
6. Simple and small
Java is very small and simple language. Java does not use pointer and header files, goto
statements, etc. It eliminates operator overloading and multiple inheritance.
7. Multithreaded and Interactive
Multithreaded means managing multiple tasks simultaneously. Java maintains multithreaded
programs. That means we need not wait for the application to complete one task before starting
next task. This feature is helpful for graphic applications.
8. High performance
Java performance is very extraordinary for an interpreted language, majorly due to the
use of intermediate bytecode. Java architecture is also designed to reduce overheads during
runtime. The incorporation of multithreading improves the execution speed of program.
9. Dynamic and Extensible
Java is also dynamic language. Java is capable of dynamically linking in new class,
libraries, methods and objects. Java can also establish the type of class through the query
building it possible to either dynamically link or abort the program, depending on the reply.
Java program is support functions written in other language such as C and C++, known as
native methods.
TABLE COMPARING C, C++ AND JAVA
Java Object Framework act as the intermediary between the user programs and the virtual machine
which in turn act as the intermediary between the operating system and the Java Object Framework.
Operating System
User
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). That is,in its standard form, the JVM
is an interpreter for bytecode.
This may come as a bit of a surprise. As you know, C++ is compiled to executable code.
In fact, most modern languages are designed to be compiled, not interpreted—mostly because
of performance concerns. However, the fact that a Java program is executed by the JVM helps
solve the major problems associated with downloading programs over the Internet.
Here is why. Translating a Java program into bytecode helps makes it much easier to run a
program in a wide variety of environments. The reason is straightforward: only the JVM needs
to be implemented for each platform. Once the run-time package exists for a given system, any
Java program can run on it. Remember, although the details of the JVM will differ from
platform to platform, all interpret the same Java bytecode. If a Java program were compiled to
native code, then different versions of the same program would have to exist for each type of
CPU connected to the Internet. This is, of course, not a feasible solution. Thus, the
interpretation of bytecode is the easiest way to create truly portable programs.
The fact that a Java program is interpreted also helps to make it secure. Because the
execution of every Java program is under the control of the JVM, the JVM can contain the
program and prevent it from generating side effects outside of the system. As you will see,
safety is also enhanced by certain restrictions that exist in the Java language. When a program
is interpreted, it generally runs substantially slower than it would run if compiled to executable
code. However, with Java, the differential between the two is not so great. The use of bytecode
enables the Java run-time system to execute programs much faster than you might expect.
Sun supplies its Just In Time (JIT) compiler for bytecode, which is included in the Java 2
release. When the JIT compiler is part of the JVM, it compiles bytecode into executable code
in real time, on a piece-by-piece, demand basis. It is important to understand that it is not
possible to compile an entire Java program into executable code all at once, because Java
performs various run-time checks that can be done only at run time. Instead, the JIT compiles
code as it is needed, during execution. However, the just-in-time approach still yields a
significant performance boost. Even when dynamic compilation is applied to bytecode, the
portability and safety features still apply, because the run-time system (which performs the
compilation) still is in charge of the execution environment. Whether your Java program is
actually interpreted in the traditional way or compiled on-the-fly, its functionality is the same.
Java Environment:
Java environment includes a number of development tools, classes and methods. The
development tools are p
art of the system known as Java Development Kit (JDK) and the classes and methods are part
of the Java Standard Library (JSL), also known as the Application Programming Interface
(API).
Java Development kit (JDK) – The JDK comes with a set of tools that are used for
developing and running Java program. It includes:
1. Appletviewer( It is used for viewing the applet)
2. Javac(It is a Java Compiler)
3. Java(It is a java interpreter)
4. Javap(Java diassembler,which convert byte code into program description)
5. Javah(It is for java C header files)
6. Javadoc(It is for creating HTML document)
7. Jdb(It is Java debugger)
For compiling and running the program we have to use following commands:
a) javac (Java compiler)
In java, we can use any text editor for writing program and then save that program with .java
extension. Java compiler convert the source code or program in bytecode and interpreter
convert ―.java file in ―.class file.
Syntax:
C:\javac filename.java
If my filename is ―abc.java then the syntax will be
C:\javac abc.java
b) java(Java Interpreter)
As we learn that, we can use any text editor for writing program and then save that
program with ―.java extension. Java compiler converts the source code or
program in bytecode and interpreter convert ―.java file in ―.class file. Syntax:
C:\java filename
If my filename is abc.java then the syntax will be
C:\java abc
class FirstProgram
{
public static void main(String args[])
{
System.out.println(―This is my first program‖);
}
}
The file must be named ―FirstProgram.java to equivalent the class name containing the
main method.
Java is case sensitive. This program defines a class called ―FirstProgram.
A class is an object oriented term. It is designed to perform a specific task. A Java class is
defined by its class name, an open curly brace, a list of methods and fields, and a close
curly brace.
The name of the class is made of alphabetical characters and digits without spaces, the first
character must be alphabetical.
The line ―public static void main (String [] args ) shows where the program will start
running. The word main means that this is the main method. The JVM starts running any
program by executing this method first.
The main method in ―FirstProgram.java consists of a single statement
System.out.println("This is my first program");
The statement outputs the character between quotes to the console.
Above explanation is about how to write program and now we have to learn where to write
program and how to compile and run the program. For this reason, the next explanation is
showing the steps.
1. Edit the program by the use of Notepad.
2. Save the program to the hard disk.
3. Compile the program with the javac command.(Java compiler)
4. If there are syntax errors, go back to Notepad and edit the program.
5. Run the program with the java command.(Java Interpreter)
6. If it does not run correctly, go back to Notepad and edit the program.
7. When it shows result then stop.
1.2 Defining a Class, Creating Objects and accessing class members
A class is a blueprint from which individual objects are created.
//fields, constructors
//method declarations
}
A class can contain any of the following variable(fields) types.
Local variables − Variables defined inside methods, constructors or blocks are called
local variables. The variable will be declared and initialized within the method and the
variable will be destroyed when the method has completed.
Instance variables − Instance variables are variables within a class but outside any
method. These variables are initialized when the class is instantiated. Instance
variables can be accessed from inside any method, constructor or blocks of that
particular class.
Class variables − Class variables are variables declared within a class, outside any
method, with the static keyword.
A class can have any number of methods to access the value of various kinds of methods.
Example
Syntax
For the above defined Bike class objects can be created in new
class BikeDemo or the main() method can be defined in the same
class.
Class BikeDemo{
Public static void main(String args[]){
//creating Objects
Bike honda=new Bike(120,4);//passing arguments to constructor
honda.setGear(4); // calling methods
honda.applyBreak(20);
honda.speedUp(40);
}
}
int puppyAge;
puppyAge = age;
/* Object creation */
myPuppy.setAge( 2 );
myPuppy.getAge( );
Output
Name chosen is :tommy
Puppy's age is :2
Variable Value :2
Java Tokens
Constants:- Constants in Java refer to fixed values that do not change during the execution of a
program. Java supports several types of constants as illustrated in Fig.
JAVA CONSTANTS
Fig:Java Constants
Integer Constants
An integer constant refers to a sequence of digits. There are three types of integers, namely,
decimal integer, octal integer and hexadecimal integer.
Decimal integers consist of a set of digits, 0 through 9, preceded by an optional minus
sign. Valid examples of decimal integer constants are:
123 -321 0 654321
Embedded spaces, commas, and non-digit characters are not permitted between digits. For
example,
15 750 20.000 $1000
are illegal numbers.
An octal integer constant consists of any combination of digits from the set 0 through 7,
with a leading 0. Some examples of octal integer are:
037 0 0435 0551
A sequence of digits preceded by OX or OX is considered as hexadecimal integer (hex
integer). They may also include alphabets A through F or a through f. A letter A through F
represents the numbers 10 through 15. Following are the examples of valid hex integers.
0X2 OX9F Oxbcd Ox
Real Constants
Integer numbers are inadequate to represent quantities that vary continuously, such as
distances, heights temperatures, prices, and so on. These quantities are represented by numbers
containing fractional parts like 17.548. Such numbers are called real (or floating point)
constants. Further examples of real constants are:
0.0083 -0.75 435.36
These numbers are shown in decimal notation, having a whole number followed by a
decimal point and the fractional part, which is an integer. It is possible that the number may
not have digits before the decimal point or digits after the decimal point. That is,
215. .95 -.71
are all valid real numbers.
A real number may also be expressed in exponential (or scientific) notation. For
example, the vain! 215.65 may be written as 2.1565e2 in exponential notation. e2 means
multiply by 102. The general form is:
mantissa e exponent
The mantissa is either a real number expressed in decimal notation or an integer. The
exponent is an integer with an optional plus or minus sign. The letter e separating the
mantissa and the exponent can be written in either lowercase or uppercase. Since the
exponent causes the decimal point to "float", this notation is said to represent a real number
in floating point form. Examples of legal floating point constants are:
0.65e4 12e-2 1.5e+5 3.18E3 -1.2E-1
Embedded white (blank) space is not allowed, in any numeric constant.
A floating point constant may thus comprise four parts: a whole number, a decimal point,a
fractional part, an exponent.
Variable Declaration
type identifier [ = value][, identifier [= value] ...] ;
The type is one of Java‘s atomic types, or the name of a class or interface. The identifier is the
name of the variable. You can initialize the variable by specifying an equal sign and a value.
That the initialization expression must result in a value of the same (or compatible) type as that
specified for the variable. To declare more than one variable of the specified type, use a
comma-separated list.
Here are several examples of variable declarations of various types. Note that some include an
initialization.
int a, b, c; // declares three ints, a, b, and c.
int d = 3, e, f = 5; // declares three more ints,
byte z = 22; // initializes z.
double pi = 3.14159; // declares an approximation of pi.
char x = 'x'; // the variable x has the value 'x'.
Java Keywords:
abstract continue for new switch
assert default goto package synchronized
boolean do if private this
break double implements protected throw
byte else import public throws
case enum instanceof return transient
catch extends int short try
char final interface static var
class finally long strictfp void
const float native super volatile
while
Following table shows the datatypes with their size and ranges.
Data type Size (byte) Range
byte 1 -128 to 127
boolean 1 True or false
char 2 A-Z,a-z,0-9,etc.
short 2 -32768 to 32767
Int 4 (about) -2 million to 2 million
long 8 (about) -10E18 to 10E18
float 4 -3.4E38 to 3.4E18
double 8 -1.7E308 to 1.7E308
Integer data type: Integer datatype can hold the numbers (the number can be positive
number or negative number).
In Java, there are four types of integer as follows:
1. byte
2. short
3. int
4. long
We can make integer long by adding ―l‖ or ―L‖ at the end of the number.
Floating point data type: It is also called as Real number and when we require
accuracy then we can use it.
There are two types of floating point data type.
1. Float
2. Double
It is represent single and double precision numbers. The float type is used for single precision
and it uses 4 bytes for storage space. It is very useful when we require accuracy with small
degree of precision. But in double type, it is used for double precision and uses 8 bytes of
storage space. It is useful for large degree of precision.
SCOPE OF VARIABLES
Java variables are actually classified into three kinds:
instance variables,
class variables, and
local variables.
Instance and class variables are declared inside a class. Instance variables are created
when the objects are instantiated and therefore they are associated with the objects.
They take different values for each object. On the other hand, class variables are
global to a class and belong to the entire set of objects that class creates. Only one
memory location is created for each class variable.
Variables declared and used inside methods are called local variables. They are called so
because they are not available for use outside the method definition. Local variables
can also be declared inside program blocks that are defined between an opening brace {and
a closing brace}. These variables are visible to the program only from the beginning
of its program block to the end of the program block. When the program control
leaves a block, all the variables in the block will cease to exist. The area of the
program where the variable is accessible (i.e., usable) is called its scope.
We can have program blocks within other program blocks (called nesting) as shown in Fig.
Each block can contain its own set of local variable declarations. We cannot, however,
declare a variable to have the same name as one in an outer block. In Fig the variable x
declared in Blockl is available in all the three blocks. However, the variable n declared in
Block2 is available only in Block2, because it goes out of the scope at the end of
Block2. Similarly, m is accessible only in Block3.
Note that we cannot declare the variable x again in Block2 or Block3 (This is perfectly legal in C
and C++).
SYMBOLIC CONSTANTS
We often use certain unique constants in a program. These constants may appear repeatedly in
a number of places in the program. One example of such a constants is 3.142, representing the
value of the mathematical constant "pi". Another example is the total number of students whose
mark-sheets are analysed by a 'test analysis program'. The number of students, say 50, may
be used for calculating the class total, class average, standard deviation, etc. We face two
problems in the subsequent use of such programs. They are:
1. Problem in modification of the program.
2. Problem in understanding the program.
Modifiability
We may like to change the value of "pi" from 3.142 to 3.14159 to improve the accuracy of
calculations or the number 50 to 100 to process the test results of another class. In both the
cases, we will have to search throughout the program and explicitly change the value of the
constant wherever it has been used. If any value is left unchanged, the program may produce
disastrous outputs.
Understandability
When a numeric value appears in a program, its use is not always clear, especially when the
same value means different things in different places. For example, the number 50 may mean
the number of students at one place and the 'pass marks' at another place of the same program.
We may forget what a certain number meant, when we read the program some days later.
Assignment of a symbolic name to such constants frees us from these problems. For
example, we may use the name STRENGTH to denote the number of students and
PASS_MARK to denote the pass marks required in a subject. Constant values are assigned to
these names at the beginning of the program. Subsequent use of the names STRENGTH and
PASS_MARK in the program has the effect of causing their defined values to be
automatically substituted at the appropriate points. A constant is declared as follows:
final type symbolic-name - value:
Valid examples of constant declaration are:
final int STRENGTH - 100;
final int PASS_MARK = 50;
final float PI = 3.14159;
Note that:
1. Symbolic names take the same form as variable names. But, they are written in
CAPITALS to visually distinguish them from normal variable names. This is only a
convention, not a rule.
2. After declaration of symbolic constants, they should not be assigned any other value
within the program by using an assignment statement. For example, STRENGTH = 200;
is illegal.
3. Symbolic constants are declared for types. This is not done in C and C++ where symbolic
constants are defined using the # define statement.
4. They can NOT be declared inside a method. They should be used only as class data
members in the beginning of the class.
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. Let‘s look at both automatic type conversions
and casting.
class Conversion {
public static void main(String args[]) {
byte b;
int i = 257;
double d = 323.142;
System.out.println("\nConversion of int to byte.");
b = (byte) i;
System.out.print("i and b " + i + " " + b);
System.out.println("\nConversion of double to int.");
i = (int) d;
System.out.print("d and i " + d + " " + i);
System.out.println("\nConversion of double to byte.");
b = (byte) d;
System.out.print("d and b " + d + " " + b);
}
}
This program generates the following output:
THE JAVA LANGUAGE
Conversion of int to byte i and b 257 1
Conversion of double to int. d and i 323.142 323
Conversion of double to byte d and b 323.142 67
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.
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:
Operator Importance/ significance
+ Addition
- Subtraction
/ Division
* Multiplication
% Modulo division or remainder
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 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 following simple example program demonstrates the arithmetic operators. It also
illustrates the difference between floating-point division and integer division.
Since the bitwise operators manipulate the bits within an integer, it is important to understand
what effects such manipulations may have on a value. Specifically, it is useful to know how
Java stores integer values and how it represents negative numbers.
All of the integer types are represented by binary numbers of varying bit widths. For example,
the byte value for 42 in binary is 00101010, where each position represents a power of two,
starting with 20 at the rightmost bit. The next bit position to the left would be 21, or 2,
continuing toward the left with 22, or 4, then 8, 16, 32, and so on. So 42 has 1 bits set at
positions 1, 3, and 5 (counting from 0 at the right); thus 42 is the sum of 21 + 23 + 25, which is
2 + 8 + 32.
All of the integer types (except char) are signed integers. This means that they can represent
negative values as well as positive ones. Java uses an encoding known as two’s complement,
which means that negative numbers are represented by inverting (changing 1‘s to 0‘s and vice
versa) all of the bits in a value, then adding 1 to the result. For example, –42 is represented by
inverting all of the bits in 42, or 00101010, which yields 11010101, then adding 1, which
results in 11010110, or –42. To decode a negative number, first invert all of the bits, then add
1. –42, or 11010110 inverted yields 00101001, or 41, so when you add 1 you get 42.
00101010
becomes
11010101
after the NOT operator is applied.
00101010 42
&00001111 15
----------------
00001010 10
The Bitwise OR
The OR operator, |, combines bits such that if either of the bits in the operands is a 1, then the
resultant bit is a 1, as shown here:
00101010 42
| 00001111 15
--------------
00101111 47
00101010 42
^00001111 15
---------------
00100101 37
The following program demonstrates the bitwise logical operators:
In this example, a and b have bit patterns which present all four possibilities for two binary
digits: 0-0, 0-1, 1-0, and 1-1. You can see how the | and & operate on each bit by the results in
c and d. The values assigned to e and f are the same and illustrate how the ^ works. The string
array named binary holds the human-readable, binary representation of the numbers 0 through
15. In this example, the array is indexed to show the binary representation of each result. The
array is constructed such that the correct string representation of a binary value n is stored in
binary[n]. The value of ~a is ANDed with 0x0f (0000 1111 in binary) in order to reduce its
value to less than 16, so it can be printed by use of the binary array. Here is the output from
this program:
a = 0011
b = 0110
a|b = 0111
a&b = 0010
a^b = 0101
~a&b|a&~b = 0101
~a = 1100
Since a is promoted to int for the purposes of evaluation, left-shifting the value 64 (0100 0000)
twice results in i containing the value 256 (1 0000 0000). However, the value in b contains 0
because after the shift, the low-order byte is now zero. Its only 1 bit has been shifted out.
int a = 35;
a = a >> 2; // a still contains 8
Looking at the same operation in binary shows more clearly how this happens:
00100011 35
>> 2
00001000 8
THE JAVA LANGUAGE
Each time you shift a value to the right, it divides that value by two—and discards any
remainder. You can take advantage of this for high-performance integer division by 2. Of
course, you must be sure that you are not shifting any bits off the right end. When you are
shifting right, the top (leftmost) bits exposed by the right shift are filled in with the previous
contents of the top bit. This is called sign extension and serves to preserve the sign of negative
numbers when you shift them right. For example, –8 >> 1 is –4, which, in binary, is
11111000 –8
>>1
11111100 –4
It is interesting to note that if you shift –1 right, the result always remains –1, since sign
extension keeps bringing in more ones in the high-order bits.
The outcome of these operations is a boolean value. The relational operators are most
frequently used in the expressions that control the if statement and the various loop statements.
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;
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:
Here is a program that is almost the same as the BitLogic example shown earlier, but it
operates on boolean logical values instead of binary bits:
THE JAVA LANGUAGE
// Demonstrate the boolean logical operators.
class BoolLogic {
public static void main(String args[]) {
boolean a = true;
boolean b = false;
boolean c = a | b;
boolean d = a & b;
boolean e = a ^ b;
boolean f = (!a & b) | (a & !b);
boolean g = !a;
System.out.println(" a = " + a);
System.out.println(" b = " + b);
System.out.println(" a|b = " + c);
System.out.println(" a&b = " + d);
System.out.println(" a^b = " + e);
System.out.println("!a&b|a&!b = " + f);
System.out.println(" !a = " + g);
}
}
After running this program, you will see that the same logical rules apply to boolean values as
they did to bits. As you can see from the following output, the string representation of a Java
boolean value is one of the literal values true or false:
a = true
b = false
a|b = true
a&b = false
a^b = true
a&b|a&!b = true
!a = false
Java provides two interesting Boolean operators not found in many other computer languages.
These are secondary versions of the Boolean AND and OR operators, and are 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
right-hand 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 left one being true or
false 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:
The ?: Operator
Java includes a special ternary (three-way) operator that can replace certain types of if-then-
else statements. This operator is the ?:, and it works in Java much like it does in C, C++, and
C#. It can seem somewhat confusing at first, but the ?: can be used very effectively once
mastered. The ?: has this general form:
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 type, which can‘t be void. Here is an example of the way that the ? is
employed:
When Java evaluates this assignment expression, it first looks at the expression to the left of the
question mark. If denom equals zero, then the expression between the question mark and the
colon is evaluated and used as the value of the entire ? expression. If denom does not equal
zero, then the expression after the colon is evaluated and used for the value of the entire ?
expression. The result produced by the ? operator is then assigned to ratio. Here is a program
that demonstrates the ? operator. It uses it to obtain the absolute value of a variable.
// Demonstrate ?:.
class Ternary {
public static void main(String args[]) {
int i, k;
i = 10;
k = i < 0 ? -i : i; // get absolute value of i
System.out.print("Absolute value of ");
System.out.println(i + " is " + k);
i = -10;
k = i < 0 ? -i : i; // get absolute value of i
System.out.print("Absolute value of ");
System.out.println(i + " is " + k);
}
}
The output generated by the program is shown here:
Absolute value of 10 is 10
Absolute value of -10 is 10
An arithmetic expression without any parentheses will be calculated from left to right using
the rules of precedence of operators.
There are two priority levels of arithmetic operators are as follows:
(a) High priority (* / %)
(b) Low priority (+ -)
The evaluation process includes two left to right passes through the expression.
During the first pass, the high priority operators are applied as they are encountered.
During the second pass, the low priority operators are applied as they are
encountered.
For example:
Z=A-
B/3+C*3-1
When
A=10,
B=13, C=3
First pass:
Z=10-(13/3) + (3*3)-1
Z=10-4+3-1
Second pass:
Z=6+3-1
Z=7
Answer is=7
Following table shows associativity of operators.
CONTROL STRUCTURE
Simple if statement:
Syntax:
If (condition)
{
Statement block;
}
Statement-a;
In statement block, there may be single statement or multiple statements. If the condition is
true then statement block will be executed. If the condition is false then statement block will
omit and statement will be executed.
If Else Statement
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;
Here, if a is less than b, then a is set to zero. Otherwise, b is set to zero. In no case are
they both set to zero.
Nested If
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)
As the comments indicate, the final else is not associated with if(j<20), because it is not
in the same block (even though it is the nearest if without an else). Rather, the final else
is associated with if(i==10). The inner else refers to if(k>100), because it is the closest if
within the same block.
class SampleSwitch {
public static void main(String args[]) {
for(int i=0; i<6; i++)
switch(i) {
case 0:
System.out.println("i is zero.");
break;
case 1:
System.out.println("i is one.");
break;
case 2:
System.out.println("i is two.");
break;
case 3:
System.out.println("i is three.");
break;
default:
System.out.println("i is greater than 3.");
}
}
}
The output produced by this program is shown here:
i is zero.
i is one.
i is two.
i is three.
i is greater than 3.
i is greater than 3.
LOOPING
While
The while loop is Java‘s most fundamental looping 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.
Here is a while loop that counts down from 10, printing exactly ten lines of ―tick‖:
do-while
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 while
loop at least once, even if the conditional expression is false to begin with. In other words,
there are times when you would like to test the termination expression at the end of the loop
rather than at the beginning. 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. Here is a reworked version of the ―tick‖ program that demonstrates the do-while
loop. It generates the same output as before.
for
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.
Generally, this is an expression that sets the value of the loop control variable, which acts as a
counter that controls the loop. It is important to understand that the initialization expression is
only executed once. Next, condition is evaluated. This must be a Boolean expression. It usually
tests the loop control variable against a target value. If this expression is true, then the body of
the loop is executed. If it is false, the loop terminates. Next, the iteration portion of the loop is
executed.
class ForTick {
public static void main(String args[]) {
int n;
for(n=10; n>0; n--)
System.out.println("tick " + n);
}
}
By using break, you can force immediate termination of a loop, by passing the conditional
expression and any remaining code in the body of the loop. When a break statement is
encountered inside a loop, the loop is terminated and program control resumes at the next
statement following the loop. Here is a simple example:
Math.pow() It returns the value of first argument raised to the power to second
argument.
Math.ceil() It is used to find the smallest integer value that is greater than or
equal to the argument or mathematical integer.
// return a power of 2
System.out.println("exp of a is: " +Math.exp(x));