Unit-1 Basic Syntactical Concepts in Java · Unit-1 Basic Syntactical Concepts in Java Introduction...

45
Unit-1 Basic Syntactical Concepts in Java Introduction to object-oriented paradigm The major objective of object-oriented approach is to eliminate some of the flaws encountered in the procedural approach. 00P treats data as a critical element in the program development and does not allow it to flow freely around the system . It ties data more closely to the functions that operate on it and protects it from unintentional modification by other functions. OOP allows us to decompose a problem into a number of entities called Objects and then build data and functions (known as methods in Java) around these entities. The combination of data and methods make up an object (see Fig.). 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. Basic Concepts of Object Oriented Programming There are some basic concepts of object oriented programming as follows: 1. Object 2. Class 3. Data abstraction 4. Data encapsulation 5. Inheritance 6. Polymorphism 7. Dynamic binding Object = Data + Methods

Transcript of Unit-1 Basic Syntactical Concepts in Java · Unit-1 Basic Syntactical Concepts in Java Introduction...

Page 1: Unit-1 Basic Syntactical Concepts in Java · Unit-1 Basic Syntactical Concepts in Java Introduction to object-oriented paradigm The major objective of object-oriented approach is

Unit-1

Basic Syntactical Concepts in Java

Introduction to object-oriented paradigm

The major objective of object-oriented approach is to eliminate some of the flaws

encountered in the procedural approach. 00P treats data as a critical element in the

program development and does not allow it to flow freely around the system. It ties data

more closely to the functions that operate on it and protects it from unintentional modification

by other functions. OOP allows us to decompose a problem into a number of entities

called Objects and then build data and functions (known as methods in Java) around these

entities. The combination of data and methods make up an object (see Fig.).

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.

Basic Concepts of Object Oriented Programming

There are some basic concepts of object oriented programming as follows:

1. Object

2. Class

3. Data abstraction

4. Data encapsulation

5. Inheritance

6. Polymorphism

7. Dynamic binding

Object = Data + Methods

Page 2: Unit-1 Basic Syntactical Concepts in Java · Unit-1 Basic Syntactical Concepts in Java Introduction to object-oriented paradigm The major objective of object-oriented approach is

1. Object

Objects are important runtime entities in object oriented method. They may characterize

a location, a bank account, and a table of data or any entry that the program must handle.

For example:

Object: STUDENT

DATA

Name

Address

Marks

METHODS

Total()

Average()

Fig.1.1 Representation of an object ―STUDENT

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

Page 3: Unit-1 Basic Syntactical Concepts in Java · Unit-1 Basic Syntactical Concepts in Java Introduction to object-oriented paradigm The major objective of object-oriented approach is

another. The important thing about the class is to identify the properties and procedures and

applicability to its instances.

Fig.1.3 Representation of class

In above example, we will create an objects MH-01 EP 1234 belonging to the class car. The

objects develop their distinctiveness from the difference in their attribute value and

relationships to other objects.

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.

For example : Vehicle

Vehicle

Car

MH - 01 EP 1234

COLOUR=Red C OST=4,00,000

Page 4: Unit-1 Basic Syntactical Concepts in Java · Unit-1 Basic Syntactical Concepts in Java Introduction to object-oriented paradigm The major objective of object-oriented approach is

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.

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.

For Example:

Vehicle

Car

Hyundai

Santro Accent

Page 5: Unit-1 Basic Syntactical Concepts in Java · Unit-1 Basic Syntactical Concepts in Java Introduction to object-oriented paradigm The major objective of object-oriented approach is

Fig.1.5 Polymorphism

7. Dynamic Binding

Binding refers to the linking of a procedure call to the code to be executed in response to the

call. Dynamic binding means that the code related with a given procedure call is not known

until the time of the call at run time. Dynamic binding is associated polymorphism and

inheritance.

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.

Shape

Draw()

Rectangle Object

Draw (Rectangle)

Square Object

Draw (Square) Circle Object

Draw (Circle)

Page 6: Unit-1 Basic Syntactical Concepts in Java · Unit-1 Basic Syntactical Concepts in Java Introduction to object-oriented paradigm The major objective of object-oriented approach is

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.

Page 7: Unit-1 Basic Syntactical Concepts in Java · Unit-1 Basic Syntactical Concepts in Java Introduction to object-oriented paradigm The major objective of object-oriented approach is

TABLE COMPARING C, C++ AND JAVA

Feature C C++ Java

Paradigms Procedural Procedural, OOP, Generic

Programming

OOP, Generic

Programming (from

Java 5)

Form of

Compiled Source

Code

Executable Native

Code Executable Native Code Java bytecode

Memory

management Manual Manual

Managed, using a

garbage collector

Pointers Yes, very

commonly used.

Yes, very commonly used,

but some form of references

available too.

No pointers; references

are used instead.

Preprocessor Yes Yes No

String Type Character arrays Character arrays, objects Objects

Complex Data

Types Structures, unions Structures, unions, classes Classes

Inheritance N/A Multiple class inheritance

Single class inheritance,

multiple interface

implementation

Operator

Overloading N/A Yes No

Automatic

coercions

Yes, with warnings

if loss could occur

Yes, with warnings if loss

could occur

Not at all if loss could

occur; must cast

explicitly

Go to Statement Yes Yes No

Java Virtual machine: As we know that all programming language compilers convert the source code to machine

code. Same job done by Java Compiler to run a Java program, but the difference is that Java

compiler convert the source code into Intermediate code is called as bytecode. This machine is

called the Java Virtual machine and it exits only inside the computer memory.

Following figure shows the process of compilation.

Source Code Byte Code

Java

Program

Virtual

Machine

Java

Compiler

Page 8: Unit-1 Basic Syntactical Concepts in Java · Unit-1 Basic Syntactical Concepts in Java Introduction to object-oriented paradigm The major objective of object-oriented approach is

The Virtual machine code is not machine specific. The machine specific code is generated. By Java

interpreter by acting as an intermediary between the virtual machine and real machines shown

below

Virtual machine Real Machine

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.

Fig: Layers of Interaction for Java programs

The Bytecode / JVM / JRE

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

Byte Code Machine code Java

Interpreter

Framework

Operating System

Java Virtual Machine

Java Object Framework

Compiler and Interpreter

User Application Programs

User

Page 9: Unit-1 Basic Syntactical Concepts in Java · Unit-1 Basic Syntactical Concepts in Java Introduction to object-oriented paradigm The major objective of object-oriented approach is

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.

JIT (Just In Time Compiler)

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.

Page 10: Unit-1 Basic Syntactical Concepts in Java · Unit-1 Basic Syntactical Concepts in Java Introduction to object-oriented paradigm The major objective of object-oriented approach is

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

Page 11: Unit-1 Basic Syntactical Concepts in Java · Unit-1 Basic Syntactical Concepts in Java Introduction to object-oriented paradigm The major objective of object-oriented approach is

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

Simple Java Program:

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.

Page 12: Unit-1 Basic Syntactical Concepts in Java · Unit-1 Basic Syntactical Concepts in Java Introduction to object-oriented paradigm The major objective of object-oriented approach is

1.2 Defining a Class, Creating Objects and accessing class members A class is a blueprint from which individual objects are created.

[modifier] class myClass { //class header

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

public class Bike {

//fields:

public int speed;

public int gear;

//Constructor:

public Bike(int startSpeed, int startGear) {

gear = startGear;

speed = startSpeed;

}

//Methods:

public void setGear (int newValue) {

this.gear = newValue;

}

public void applyBrake(int decrement) {

this.speed -= decrement;

}

public void speedUp(int increment) {

this.speed += increment;

}

}

Page 13: Unit-1 Basic Syntactical Concepts in Java · Unit-1 Basic Syntactical Concepts in Java Introduction to object-oriented paradigm The major objective of object-oriented approach is

Creating an Object

As mentioned previously, a class provides the blueprints for objects. So basically, an object is

created from a class. In Java, the new keyword is used to create new objects.

There are three steps when creating an object from a class −

Declaration − A variable declaration with a variable name with an object type.

Instantiation − The 'new' keyword is used to create the object.

Initialization − The 'new' keyword is followed by a call to a constructor. This call

initializes the new object.

Syntax

className objectName = new className(inputParameters);

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);

}

}

Accessing Instance Variables and Methods

Instance variables and methods are accessed via created objects. To access an instance

variable, following is the fully qualified path.

/* First create an object */ Object = new Constructor(); /* Now call a variable as follows */ Object.variableName; /* Now you can call a class method as follows */ Object.MethodName();

Page 14: Unit-1 Basic Syntactical Concepts in Java · Unit-1 Basic Syntactical Concepts in Java Introduction to object-oriented paradigm The major objective of object-oriented approach is

Accessing class members

public class Puppy {

int puppyAge;

public Puppy(String name) {

// This constructor has one parameter, name. System.out.println("Name chosen is :" + name ); }

public void setAge( int age ) {

puppyAge = age;

}

public int getAge( ) {

System.out.println("Puppy's age is :" + puppyAge ); return puppyAge; }

public static void main(String []args) {

/* Object creation */

Puppy myPuppy = new Puppy( "tommy" );

/* Call class method to set puppy's age */

myPuppy.setAge( 2 );

/* Call another class method to get puppy's age */

myPuppy.getAge( );

/* You can access instance variable as follows as well */

System.out.println("Variable Value :" + myPuppy.puppyAge );

} }

If we compile and run the above program, then it will produce the following result −

Output

Name chosen is :tommy

Puppy's age is :2

Variable Value :2

Page 15: Unit-1 Basic Syntactical Concepts in Java · Unit-1 Basic Syntactical Concepts in Java Introduction to object-oriented paradigm The major objective of object-oriented approach is

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

Numeric Constants Character Constants

Integer Real Character String Constants Constants Constants 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

Page 16: Unit-1 Basic Syntactical Concepts in Java · Unit-1 Basic Syntactical Concepts in Java Introduction to object-oriented paradigm The major objective of object-oriented approach is

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.

Single Character Constants

A single character constant (or simply character constant) contains a single character enclosed

within a pair of single quote marks. Examples of character constants are:

` 5 ‘ ‘ X ' ‗ ; ‘ ‗ ‗

Note that the character constant '5' is not the same as the number 5. The last constant is a blank

space.

String Constants

A string constant is a sequence of characters enclosed between double quotes. The

characters may be alphabets, digits, special characters and blank spaces. Examples are:

"Hello Java" "1997" "WELL DONE" "?...!" "5+3"

Backslash Character Constants

Java supports some special backslash character constants that are used in output methods. For

example, the symbol '\n' stands for newline character. A list of such backslash character

constants is given in Table 4.1. Note that each one of them represents one character, although

they consist of two characters. These characters combinations are known as escape sequences.

Constant Meaning

' \ b ' back space

‗\f ‘ form feed

‗\n‘ new line

‗\t‘ horizontal tab

Page 17: Unit-1 Basic Syntactical Concepts in Java · Unit-1 Basic Syntactical Concepts in Java Introduction to object-oriented paradigm The major objective of object-oriented approach is

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. In we had used several

variables. For instance, we used variables length and breadth to store the values of length and

breadth of a room.

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:

As mentioned earlier, variable names may consist of alphabets, digits, the underscore ( _) and

dollar characters, subject to the following conditions:

1. They must not begin with a digit.

2. Uppercase and lowercase are distinct. This means that the variable Total is not the

same as total or TOTAL.

3. It should not be a keyword.

4. White space is not allowed.

5. Variable names can be of any length.

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

Page 18: Unit-1 Basic Syntactical Concepts in Java · Unit-1 Basic Syntactical Concepts in Java Introduction to object-oriented paradigm The major objective of object-oriented approach is

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

Data types in java A data type is a scheme for representing values. An example is int which is the Integer, a data

type. Values are not just numbers, but any manner of data that a computer can process. The

data type defines the kind of data that is represented by a variable. As with the keyword class,

Java data types are case sensitive.

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

Page 19: Unit-1 Basic Syntactical Concepts in Java · Unit-1 Basic Syntactical Concepts in Java Introduction to object-oriented paradigm The major objective of object-oriented approach is

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.

Character data type:

It is used to store single character in memory. It uses 2 bytes storage space.

Boolean data type:

It 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 hold: true and false. Boolean type is denoted

by the keyword boolean and uses only one bit of storage.

Following program shows the use of datatypes.

Program:

import java.io.DataInputStream;

class

cc2 {

public static void main(String args[]) throws Exception

{

DataInputStream s1=new DataInputStream(System.in);

byte rollno;

int marks1,marks2,marks3;

float avg;

System.out.println("Enter roll number:");

rollno=Byte.parseByte(s1.readLine());

Page 20: Unit-1 Basic Syntactical Concepts in Java · Unit-1 Basic Syntactical Concepts in Java Introduction to object-oriented paradigm The major objective of object-oriented approach is

System.out.println("Enter marks m1, m2, m3:");

marks1=Integer.parseInt(s1.readLine());

marks2=Integer.parseInt(s1.readLine());

marks3=Integer.parseInt(s1.readLine());

avg = (marks1+marks2+marks3)/3;

System.out.println("Roll number is="+rollno);

System.out.println("Average is="+avg);

}

}

Mixing Data types: Java allows mixing of constants and variables of different types in an expression, but during

assessment it hold to very strict rules of type conversion. When computer consider operand

and operator and if operands are different types then type is automatically convert in higher

type. Following table shows the automatic type conversion.

char byte short int long float double

Char int int int int long float double

Byte int int int int long float double

Short int int int int long float double

Int int int int int long float double

Long long long long long long float double

Float float float float float float float double

double double double double double double double double

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.

Page 21: Unit-1 Basic Syntactical Concepts in Java · Unit-1 Basic Syntactical Concepts in Java Introduction to object-oriented paradigm The major objective of object-oriented approach is

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

Fig : Nested program blocks

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.

Page 22: Unit-1 Basic Syntactical Concepts in Java · Unit-1 Basic Syntactical Concepts in Java Introduction to object-oriented paradigm The major objective of object-oriented approach is

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.

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

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.

Page 23: Unit-1 Basic Syntactical Concepts in Java · Unit-1 Basic Syntactical Concepts in Java Introduction to object-oriented paradigm The major objective of object-oriented approach is

■ 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. 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. As mentioned

earlier, Java also performs an automatic type conversion when storing a literal integer constant

into variables of type byte, short, or long.

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.

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

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); } }

Page 24: Unit-1 Basic Syntactical Concepts in Java · Unit-1 Basic Syntactical Concepts in Java Introduction to object-oriented paradigm The major objective of object-oriented approach is

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

Standard Default Values In Java, every variable has a default value. If we don't initialize a variable when it is first

created, Java provides default value to that variable type automatically as shown in Table.

Table: Default Values for Various Types

Types of variable Default value

byte Zero : (byte) 0

Short Zero : (short) 0

int Zero : 0

long Zero : OL

float 0.0f

double 0.0d

char null character

boolean false

reference null

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

Page 25: Unit-1 Basic Syntactical Concepts in Java · Unit-1 Basic Syntactical Concepts in Java Introduction to object-oriented paradigm The major objective of object-oriented approach is

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.

// Demonstrate the basic arithmetic operators. class BasicMath { public static void main(String args[]) { // arithmetic using integers System.out.println("Integer Arithmetic"); int a = 1 + 1; int b = a * 3; int c = b / 4; int d = c - a; int e = -d; System.out.println("a = " + a); System.out.println("b = " + b); System.out.println("c = " + c); System.out.println("d = " + d); System.out.println("e = " + e); // arithmetic using doubles System.out.println("\nFloating Point Arithmetic"); double da = 1 + 1; double db = da * 3; double dc = db / 4; double dd = dc - a; double de = -dd; System.out.println("da = " + da); System.out.println("db = " + db); System.out.println("dc = " + dc); System.out.println("dd = " + dd); System.out.println("de = " + de); } } When you run this program, you will see the following output: Integer Arithmetic a = 2 b = 6 c = 1 d = -1 e = 1 Floating Point Arithmetic da = 2.0 db = 6.0 dc = 1.5 dd = -0.5 de = 0.5

Page 26: Unit-1 Basic Syntactical Concepts in Java · Unit-1 Basic Syntactical Concepts in Java Introduction to object-oriented paradigm The major objective of object-oriented approach is

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. (This differs from C/C++, in which the % can

only be applied to integer types.) The following example program demonstrates %:

// 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 Assignment Operators 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 += 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

assignment operators for all of the arithmetic, binary operators. Thus, any statement of the

form

var = var op expression; can be rewritten as

var op= expression;

Here is a sample program that shows several op= operator assignments in action:

// Demonstrate several assignment operators.

class OpEquals { public static void main(String args[]) { int a = 1; int b = 2; int c = 3; a += 5; b *= 4; c += a * b; c %= 6; System.out.println("a = " + a); System.out.println("b = " + b); System.out.println("c = " + c); } }

Page 27: Unit-1 Basic Syntactical Concepts in Java · Unit-1 Basic Syntactical Concepts in Java Introduction to object-oriented paradigm The major objective of object-oriented approach is

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;

is equivalent to

x- -;

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

course, in both cases x is set to 43. Here, the line y = x++; is the equivalent of these two

statements:

y = x;

x = x + 1;

The following program demonstrates the increment operator. // Demonstrate ++.

class IncDec { public static void main(String args[]) { int a = 1; int b = 2; int c, d; c = ++b; d = a++; c++; System.out.println("a = " + a); System.out.println("b = " + b); System.out.println("c = " + c); System.out.println("d = " + d); } } The output of this program follows: a = 2 b = 3 c = 4 d = 1

Page 28: Unit-1 Basic Syntactical Concepts in Java · Unit-1 Basic Syntactical Concepts in Java Introduction to object-oriented paradigm The major objective of object-oriented approach is

The Bitwise Operators Java defines several bitwise operators which 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:

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.

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

Page 29: Unit-1 Basic Syntactical Concepts in Java · Unit-1 Basic Syntactical Concepts in Java Introduction to object-oriented paradigm The major objective of object-oriented approach is

The Bitwise NOT

Also called the bitwise complement, the unary NOT operator, ~, inverts all of the bits of its

operand. For example, the number 42, which has the following bit pattern:

00101010

becomes

11010101

after the NOT operator is applied.

The Bitwise AND

The AND operator, &, produces a 1 bit if both operands are also 1. A zero is produced in all

other cases. Here is an example:

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

The Bitwise XOR The XOR operator, ^, combines bits such that if exactly one operand is 1, then the result is 1.

Otherwise, the result is zero. The following example shows the effect of the ^. This example

also demonstrates a useful attribute of the XOR operation. Notice how the bit pattern of 42 is

inverted wherever the second operand has a 1 bit. Wherever the second operand has a 0 bit, the

first operand is unchanged. You will find this property useful when performing some types of

bit manipulations.

00101010 42

^00001111 15

---------------

00100101 37

Page 30: Unit-1 Basic Syntactical Concepts in Java · Unit-1 Basic Syntactical Concepts in Java Introduction to object-oriented paradigm The major objective of object-oriented approach is

The following program demonstrates the bitwise logical operators:

// Demonstrate the bitwise logical operators.

class BitLogic {

public static void main(String args[]) {

String binary[] = {

"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111",

"1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"

};

int a = 3; // 0 + 2 + 1 or 0011 in binary

int b = 6; // 4 + 2 + 0 or 0110 in binary

int c = a | b;

int d = a & b;

int e = a ^ b;

int f = (~a & b) | (a & ~b);

int g = ~a & 0x0f;

System.out.println(" a = " + binary[a]);

System.out.println(" b = " + binary[b]);

System.out.println(" a|b = " + binary[c]);

System.out.println(" a&b = " + binary[d]);

System.out.println(" a^b = " + binary[e]);

System.out.println("~a&b|a&~b = " + binary[f]);

System.out.println(" ~a = " + binary[g]);

}

}

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

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

Page 31: Unit-1 Basic Syntactical Concepts in Java · Unit-1 Basic Syntactical Concepts in Java Introduction to object-oriented paradigm The major objective of object-oriented approach is

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.

// Left shifting a byte value.

class ByteShift { public static void main(String args[]) { byte a = 64, b; int i; i = a << 2; b = (byte) (a << 2); System.out.println("Original value of a: " + a); System.out.println("i and b: " + i + " " + b); } } The output generated by this program is shown here: Original value of a: 64 i and b: 256 0

Since a is promoted to int for the purposes of evaluation, left-shifting the value 64 (0100 0000)

twice results in i containing the value 256 (1 0000 0000). However, the value in b contains 0

because after the shift, the low-order byte is now zero. Its only 1 bit has been shifted out.

The Right Shift

The right shift operator, >>, shifts all of the bits in a value to the right a specified number of

times. Its general form is shown here:

value >> num Here, num specifies the number of positions to right-shift the value in value. That is, the >>

moves all of the bits in the specified value to the right the number of bit positions specified by

num. The following code fragment shifts the value 32 to the right by two positions, resulting in

a being set to 8:

int a = 32;

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

When a value has bits that are ―shifted off,‖ those bits are lost. For example, the next code

fragment shifts the value 35 to the right two positions, which causes the two low-order bits to

be lost, resulting again in a being set to 8.

int a = 35;

a = a >> 2; // a still contains 8

Looking at the same operation in binary shows more clearly how this happens:

00100011 35

>> 2

00001000 8

THE JAVA LANGUAGE

Page 32: Unit-1 Basic Syntactical Concepts in Java · Unit-1 Basic Syntactical Concepts in Java Introduction to object-oriented paradigm The major objective of object-oriented approach is

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 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, shift-right 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.

int a = -1;

a = a >>> 24;

Here is the same operation in binary form to further illustrate what is happening:

11111111 11111111 11111111 11111111 –1 in binary as an int

>>>24

00000000 00000000 00000000 11111111 255 in binary as an int

The >>> operator is often not as useful as you might like, since it is only meaningful for 32-

and 64-bit values. Remember, smaller values are automatically promoted to int in expressions.

This means that sign-extension occurs and that the shift will take place on a 32-bit rather than

on an 8- or 16-bit value. That is, one might expect an unsigned right shift on a byte value to

zero-fill beginning at bit 7.

Bitwise Operator Assignments

All of the binary bitwise operators have a shorthand 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;

Page 33: Unit-1 Basic Syntactical Concepts in Java · Unit-1 Basic Syntactical Concepts in Java Introduction to object-oriented paradigm The major objective of object-oriented approach is

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:

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;

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:

Page 34: Unit-1 Basic Syntactical Concepts in Java · Unit-1 Basic Syntactical Concepts in Java Introduction to object-oriented paradigm The major objective of object-oriented approach is

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

Short-Circuit Logical Operators

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:

if (denom != 0 && num / denom > 10)

Page 35: Unit-1 Basic Syntactical Concepts in Java · Unit-1 Basic Syntactical Concepts in Java Introduction to object-oriented paradigm The major objective of object-oriented approach is

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 have to 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

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

This fragment sets the variables x, y, and z to 100 using a single statement. This works because

the = is an operator that yields the value of the right-hand expression. Thus, the value of z =

100 is 100, which is then assigned to y, which in turn is assigned to x. Using a ―chain of

assignment‖ is an easy way to set a group of variables to a common value

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:

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 type, which can‘t be void. Here is an example of the way that the ? is

employed:

ratio = (denom == 0) ? 0 : ( num / denom);

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 ?

Page 36: Unit-1 Basic Syntactical Concepts in Java · Unit-1 Basic Syntactical Concepts in Java Introduction to object-oriented paradigm The major objective of object-oriented approach is

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

Operator Precedence in Java:

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

Page 37: Unit-1 Basic Syntactical Concepts in Java · Unit-1 Basic Syntactical Concepts in Java Introduction to object-oriented paradigm The major objective of object-oriented approach is

Following table shows associativity of operators.

Operator Associativity Rank

[ ] Left to right 1

( ) Left to right

3

. Left to right

- Right to left

++ Right to left

-- Right to left

! Right to left

~ Right to left

(type) Right to left

* Left to right

3 / Left to right

% Left to right

+ Left to right 4

- Left to right

<< Left to right

5 >> Left to right

>>> Left to right

< Left to right

6

<= Left to right

> Left to right

>= Left to right

Instanceof Left to right

== Left to right 7

!= Left to right

& Left to right 8

^ Left to right 9

| Left to right 10

&& Left to right 11

|| Left to right 13

?: Right to left 13

= Right to left 14

CONTROL STRUCTURE

Simple if statement:

Syntax:

If (condition)

{

Page 38: Unit-1 Basic Syntactical Concepts in Java · Unit-1 Basic Syntactical Concepts in Java Introduction to object-oriented paradigm The major objective of object-oriented approach is

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.

The if-else-if Ladder class IfElse { public static void main(String args[]) {

Page 39: Unit-1 Basic Syntactical Concepts in Java · Unit-1 Basic Syntactical Concepts in Java Introduction to object-oriented paradigm The major objective of object-oriented approach is

int month = 4; // April String season; if(month == 12 || month == 1 || month == 2) season = "Winter"; else if(month == 3 || month == 4 || month == 5) season = "Spring"; else if(month == 6 || month == 7 || month == 8) season = "Summer"; else if(month == 9 || month == 10 || month == 11) season = "Autumn"; else season = "Bogus Month"; System.out.println("April is in the " + season + "."); } } Here is the output produced by the program: April is in the Spring.

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:

// statement sequence

break;

case value2:

// statement sequence

break;

...

case valueN:

// statement sequence

break;

default:

// default statement sequence

}

The expression must be of type byte, short, int, or char; each of the values specified in the

case statements must be of a type compatible with the expression. Each case value must be a

unique literal (that is, it must be a constant, not a variable). Duplicate case values are not

allowed.

class SampleSwitch { public static void main(String args[]) { for(int i=0; i<6; i++) switch(i) {

Page 40: Unit-1 Basic Syntactical Concepts in Java · Unit-1 Basic Syntactical Concepts in Java Introduction to object-oriented paradigm The major objective of object-oriented approach is

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‖:

// Demonstrate the while loop.

class While { public static void main(String args[]) { int n = 10; while(n > 5) { System.out.println("tick " + n);

Page 41: Unit-1 Basic Syntactical Concepts in Java · Unit-1 Basic Syntactical Concepts in Java Introduction to object-oriented paradigm The major objective of object-oriented approach is

n--; } } } When you run this program, it will “tick” ten times: tick 10 tick 9 tick 8 tick 7 tick 6

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.

// 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); }

}

for

for(initialization; condition; iteration) {

// body

}

Page 42: Unit-1 Basic Syntactical Concepts in Java · Unit-1 Basic Syntactical Concepts in Java Introduction to object-oriented paradigm The major objective of object-oriented approach is

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);

}

}

Using break to Exit a Loop

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:

// Using break to exit a loop.

class BreakLoop {

public static void main(String args[]) {

for(int i=0; i<100; i++) {

if(i == 4) break; // terminate loop if i is 4

System.out.println("i: " + i);

}

System.out.println("Loop complete.");

}

}

This program generates the following output: i: 0 i: 1 i: 2 i: 3 i: 4 Loop complete.

Page 43: Unit-1 Basic Syntactical Concepts in Java · Unit-1 Basic Syntactical Concepts in Java Introduction to object-oriented paradigm The major objective of object-oriented approach is

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. This is, in effect, a goto just past the body of the loop, to the loop‘s end. The

continue statement performs such an action. In while and do-while loops, a continue

statement causes control to be transferred directly to the conditional expression that controls

the loop. In a for loop, control goes first to the iteration portion of the for statement and then to

the conditional expression. For all three loops, any intermediate code is bypassed. Here is an

example program that uses continue to cause two numbers to be printed on each line:

// Demonstrate continue.

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

for(int i=0; i<10; i++) { System.out.print(i + " "); if (i%2 == 0)

continue; System.out.println("");

} } } This code uses the % operator to check if i is even. If it is, the loop continues without

printing a newline. Here is the output from this program:

0 1

2 3

4 5

6 7

8 9

As with the break statement, continue may specify a label to describe which enclosing loop to

continue.

Java Math class

Java Math class provides several methods to work on math calculations like min(), max(),

avg(), sin(), cos(), tan(), round(), ceil(), floor(), abs() etc.

Page 44: Unit-1 Basic Syntactical Concepts in Java · Unit-1 Basic Syntactical Concepts in Java Introduction to object-oriented paradigm The major objective of object-oriented approach is

Program:

public class NewClass { public static void main(String[] args) { // Declaring the variables int V = -1; float V1 = .5f; // Printing the values System.out.println("Initial value of int : "+V); System.out.println("Initial value of int : "+V1); // Use of .abs() method to get the absoluteValue int Absi = Math.abs(V); float Absf = Math.abs(V1); System.out.println("Absolute value of int : "+Absi); System.out.println("Absolute value of int : "+Absf); System.out.println(""); } } Output: Initial value of int : -1 Initial value of int : 0.5 Absolute value of int : 1 Absolute value of int : 0.5

Math.abs() It will return the Absolute value of the given value.

Math.max() It returns the Largest of two values.

Math.min() It is used to return the Smallest of two values.

Math.round() It is used to round of the decimal numbers to the nearest value.

Math.sqrt() It is used to return the square root of a number.

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.

Math.log() It returns the natural logarithm of a double value.

Page 45: Unit-1 Basic Syntactical Concepts in Java · Unit-1 Basic Syntactical Concepts in Java Introduction to object-oriented paradigm The major objective of object-oriented approach is

Another Program:

public class JavaMathExample1

{

public static void main(String[] args)

{

double x = 28;

double y = 4;

// return the maximum of two numbers

System.out.println("Maximum number of x and y is: " +Math.max(x, y));

// return the square root of y

System.out.println("Square root of y is: " + Math.sqrt(y));

//returns 28 power of 4 i.e. 28*28*28*28

System.out.println("Power of x and y is: " + Math.pow(x, y));

// return the logarithm of given value

System.out.println("Logarithm of x is: " + Math.log(x));

System.out.println("Logarithm of y is: " + Math.log(y));

// return the logarithm of given value when base is 10

System.out.println("log10 of x is: " + Math.log10(x));

System.out.println("log10 of y is: " + Math.log10(y));

// return the log of x + 1

System.out.println("log1p of x is: " +Math.log1p(x));

// return a power of 2

System.out.println("exp of a is: " +Math.exp(x));

// return (a power of 2)-1

System.out.println("expm1 of a is: " +Math.expm1(x));

}

}