unit-1 introduction to java - wordpress.com · 1. the wrapping up of data and methods in to a...
TRANSCRIPT
UNIT-1
INTRODUCTION TO JAVA:
In 1990 , the team known as green project team in sun micro system was decide to
develop a special software .
Java is a general purpose , case sensitive , high level , structured and object oriented
programming language developed by sun micro system of USA in 1991.
It was originally called oak by james gosling is one of the inventers of language.
In 1995 oak was renamed by java , due to some legal problems.
In 1996 java become as a leader for Internet Programming.
FEATURES OF JAVA:
Sun micro system officially describe java with the following features
1. COMPLIED AND INTERPRETED
Java combines both these approach , thus by making a two stage process.
Source code compiler byte code interpreter machine code
Compiler translates a source code in to byte code at the time of compilation.
Interpreter translates a byte code in to machine code that can directly executed
by the machine. (ie) Running the java programming.
2. PLATFORM INDEPENDENT
Changes and upgrades in operating system , processor and system resources
will not force any changes in java program.
Java program can download from a remote location on to our local system via
internet and execute it locally.
3. OBJECT ORIENTED
Java is a true object oriented .
All program code and data resides within objects and classes , it is easy and
simple to extend.
Java comes with an rich set of classes , arranged in packages.
4. ROBUST AND SECURE
Java provides many safeguards to ensures reliable codes .
It has run time checking for data types , garbage collected language.
Java provides the concept of exception handling avoids any risk of crashing
the system.
5. DISTRIBUTED
Java has the ability to share both data and program and facilitate the
programmers at multiple location to collabrate and work together in a single
project.
6. SIMPLE , SMALL AND FAMILIER
Java does not use pointers , pre processor header files , go to statement ,
operator overloading , multiple inheritance.
Java statement syntax is very closer to c and c++.
Java inherits many features of c and c++. So , it is familiar language.
7. HIGH PERFORMANCE
Inter mediate by code , architecture and multithreading enhance the over
execution speed of java.
8. MULTI THREADING
Handling multiple task simantaneously .
We need not wait for the application to finish the task before , beginning
another.
9. DYNAMIC AND EXTENSIBLE
Java supports a dynamic link libraries .(ie) DLL files.
Java supports method written in other language. (ie) c and c++ are known as
native methods.
Classes:
1. A class is thus a collection of objects of similar type.
2. For ex: mango, apple, orange are the members of the class fruit.
3. The syntax used to create an object. If fruit has been defined as the class, then the
statement
Fruit mango
Will create an object mango belonging to the class fruit.
Person
Name
Basic pay
Salary()
tax
Data Abstraction And Encapsulation:
1. The wrapping up of data and methods in to a single unit is known as encapsulation.
2. The data in the class only access by the methods of the class.
Information in Information out
3. Class uses the concept of abstraction and are defined as a list of abstract attributes
such as size, weight, cost and methods that operate on these attributes.
Inheritance:
1. Inheritance is the process by which objects of one class acquire the properties of
object of another class.
2. Inheritance supports the concept of hierarchical classification.
3. For ex: The class robin is a part of the class flying bird, which is again a part of the
class bird.
4. The following figure illustrate this concept
Data and methods
object
data
methods
BIRD
Attributes Feathers Lay eggs
FLYING BIRD
Attribute
5. Each derived class shares common characteristic with the class from which it is
derived.
6. In OOPs , the concept of inheritance provide the idea of reusability.
7. This is possible by deriving a new class (derived class) from the existing one (base
class).
8. The new class will have the combined features of both the classes.
Polymorphism:
1. Polymorphism means the ability to take more than one form.
2. For ex: An operation may exhibit different behavior at different instance of time.
3. The behavior depends upon the type of data used in the operation
4. The following figure illustrate the concept
SHAPE
Draw()
Circle(obj) Box(obj) Triangle(obj)
Draw(circle) Draw(box) Draw(triangle)
ROBIN
Attribute
PENQUIN
Attribute
SPARROW
Attribute
DUCK
Attribute
NON FLYING BIRD
Attribute
Dynamic Binding:
1. Binding refers to the linking of procedure call to the code to be executed in response
to the call
2. Dynamic Binding means that the code associated with the given procedure call is not
know until the time of call at run time.
3. It is associated with polymorphism and inheritance.
Message Communication:
1. An object _oriented program consist of a set of object that communicate with each
other.
2. The process of programming in an object oriented language involves the following
basic step
Creating a class that defines object and their behavior
Creating objects from the class definitions
Establishing communication among the object.
A message for an object is a request for execution and therefore will invoke a
method (procedure) in the receiving object that generates the desired results.
Sending objects () message
(Method1)Receiving objects
A message passing involves specifying the name of the object, the name of the
method(message)
and the information to sent .
For ex; consider the statement
Employee salary (name)
Here, Employee - object
Salary - message and
Name - parameter that contains information.
Over View Of Java
Execution flow of Java Programs
1. We can develop two types of java program
Stand-alone application
Web applets
Simple Java Program :
The simple java program prints a line of text as output
Class Sample
{
Public static void main(String args[])
{
System.out.println(“java is an object oriented “);
}
}
Let us discuss the program line by line
1.Class declaration
The 1st line –class sample, declares a class, everything must be placed inside a class.
Here, class is a keyword that defines new class sample in an identifier that specifies the
name of the class to be defined.
Java source code
Java complies
Java enabled web
browser
Java interprets
Outputs Outputs
2. Opening and closing
Every class definition in java begins with an opening brace’{‘ and ends with closing
brace’}’.
3. The main line (function)
Public static void main (String args[])
It is the starting point for the interpreter to begin the execution of the program.
Java application program can have any number of class but only new of include in
the method to initiate the execution.
This line contains a number of keywords public, static and void.
4. Public
The keyword public is an access specifier that declares the main method as unprotected
and therefore making it accessible to all other classes.
5. Static
The keyword static declares this method as one that belongs to the entire class and not a
part of any object of the class.
6. Void
The type of modifier void states that the main method does not returns any value.
All parameter to the method are declared inside a form of parenthesis.
Here, String args[] declares a parameter named args, which contains an array of object of
the class type string.
7. The output line
The only executable statement in the program is System.out.println(“java is an object
oriented”);
Here, the println method is a member of the out object which is a static data member of
system class.
This line prints the string’ java is an object oriented’
Every java statement ends with a semicolon.
Java Program Structure:
suggested
optional
essential
1.DOCUMENTATION SECTION
This section contains a set of comment lines giving the name of the program ,the
author,date of birth and comments which are related to the programs.
/**…….*/ this form of comment is used for generating documentation comment.
2. PACKAGE STATEMENT
This statement declares a package name and informs the complier that the classes defined
here belongs to this package.
Eg: package student;
This statement is optional.
3. IMPORT STATEMENT
After a package statement may be as number of import statements
Eg:import java.lang.math;
This statement instructs the interpreter to load the math class contained in the package
lang.
4. INTERFACE STATEMENT
An interface is like a class but includes a group of method declaration.it is optional.
5. CLASS DEFINITION
A java program may contain multiple class definition.
The number of classes used depends on the complexity of the problem.
These classes are used to map the object of real_world problems.
Documentation section Package statement Import statement Interface statement Class definition Main method class { Main method definition }
6. MAIN METHOD CLASS
A simple java program may contain only this part.
The main method creats objects of various classes and establish
communication between them.
Program execution starts from main method , on reaching the end of main , the
program terminates.
A program illustrate a java application with classes
Class Room
{
float length;
float breadth;
void getdata(float length, float breadth)
{
length=a;
breadth=b;
}
}
Class Room1
{
public static void main(String args[])
{
float area ;
Room r1=new room() // creat an object r1
r1.getdata(14,10) // assigns value to length and
breadth
area =r1.length*r1.breadth;
System.out.println(“area”+area);
}
}
JAVA TOCKENS
Smallest individual unit in a program is known as tokens .the compiler
recognizes them for building up expressions and statements
Java language includes five types of tockens.they are
1. Reserved keywords 2.Identifire 3.Literals 4.operators 5.seperators
JAVA CHARACTER SET
The smallest units of java language are the character used to write java
tockens,which includes letters ,digitsand specified symbols used in normal English.
We have used only ASCII character
KEYWORDS
Keywords are an essential part of a language definition
Keywords have specific meaning in java ,we cannot use them as a name for
variables , class and methods and soon.
All the keywords are to be written in lower case letters.
Java language has 50 keywords.
abstract ,asserts, Boolean, break, byte, case , catch ,char, class, const , continue, default , do ,
double, else ,enum, extends , final, finally, float, for, goto ,if,implements, import, instanceof,
int, interface, long,
native, new ,package, private, protected, public, return, short, static, strictfp, super, switch,
synchronized, this, throw, throws, transient, try, void, volatile, while.
IDENTIFIERS
Identifiers are programmer designed tokens. They are used for naming
classes, methods, variables, object, labels, package and interface in a program.
Java identifier follow the following rules:
1. They can have alphabets, digit, underscore and dollar sign character
2. They must not begin with a digit.
3. Uppercase and lowercase letters are distinct.
4. They can be of any length.
5. Identifier should be meaningful and short.
JAVA DEVELPERS HAVE FOLLOWED SOME NAMEING CONVENTIONS
1. Names of methods and variables start with a lowercase letters. For eg:average,
sum.
2. When more than one word are used in a name, the second and subsequent
words are marked with a uppercase letters. For ex: dayTemperature,
firstDayOfMonth.
3. All private and local variables use only lowercase letters combined with
underscore.for eg:length, batch_strength.
4. All classes and interface start with uppercase. For ex:HelloJava,Student.
5. Variables that represents constant use all uppercase and underscore between
words.for eg: TOTAL,PRINCIPAL_AMOUNT.
They are like symbolic constant in c.
While naming the identifier we should follow the basic rules and conventions.
LITERALS
Literals are a sequence of character (digit, letters and other
characters)represents constant value to the stored in variables.
Java language specifies 5 major types of literals , they are:
1. Integer literals
2. Floating_point literals
3. Character literals
4. String literals
5. Boolean literals
Each of them has a type associated with it. The type describes how the values
behaves and how the values stored.
OPERATOR
*An operator is a symbol that takes one or more arguments and operators on them to
produce a result.
SEPARATORS
*An operator is a symbol used to indicate where group of code are divided and
arranged .they basically define the shape and function of our code
1.paranthesis()-used to enclose parameter in method,expression etc.
2. braces{}- to define a block of code for classes,methods.
3. brackets[]-used to declare array types
4.semicolon;-used to separate statement
5.comma,-used to seperate a consecutive identifier in a variable decleration.
6. period.-used to separate package names from sub_packages, classes and methods.
JAVA STATEMENTS
1.The statements in java are like sentence in natural languages
2. A statement is an executable combination of tokens ending with semicolon(;).
3. Statements are usually executed in sequence in the order in which they appear.
4.It is possible to control the flow of execution using special statement.
5. java implements the following type of statement:
* Empty statement-These do nothing and are used during program development.
*Labelled statement-Any statement may begin with a lable, such labels must not be a
keyword, variables or previously used labels in this module.Labels in java are used as a
jump statement.
*Expression statement- Most statement are expression statement .java has 7 types of
Expression statement Assignment,pre-increment/ decrement ,
post-increment/decrement ,method call and allocation expression.
*Selection statement-these select one of several control flows.There are 3 types of selection
statements in java :if, if-else and switch.
*Iteration statement-These specify how and when looping will take place.there ar 3 types
of iteration statement: while , do and for.
*Jump statement-Jump statement pass control to the beginning or end of the current block
or to a labeled statement, there are 4 types of jump statement: break ,continue,
return and throw
*Synchronization statement-These are used for handling issues for multi-threading.
*Guarding statement –Guarding statements are used for safe handling of code that may
cause exception. These statement use the keywords try, catch and finally.
CONSTANTS:
Constants in java refer to fixed values that do not change during the execution
of the program.java supports several types of constants as illustrated below
JAVA CONSTANT
NUMERIC CONSTANT CHARACTER CONSTANT
INTEGER CONSTANT REAL CHARACTER STRING CONSTANT
CONSTANT CONSTANT
INTEGER CONSTANT:
An integer constant refers to sequence of digits
There are 3 types of integer :
1.decimal integer
2. Octal integer
3. Hexadecimal integer.
1. Decimal integer :
Decimal integer consist of a set of digits ,0-9.
Valid examples of decimal integer are 1239 ,-132, 0,6544321.
Invalid examples are 15 750 , 20,00 , $345.
Spaces , comma and non-digit characters are not permitted between digits.
2.Octal integer:
An octal integer constant consists of any combination of digits from 0-7, with
leading 0.
Some examples are 037 , 0 , 0453 , 0565.
3.Hexadecimal:
A sequence of digits preceded by 0x,0X is considered as hexadecimal integers.
They may also include alphabets A-F or a-f.
Valid examples are 0x2, 0X34 , 0x0f , 0X67afd.
REAL CONSTANTS
1.The quantities such as distance , height , temperature , prices and so on are represented
by numbers containing fractional part like 17.905. Such numbers are called real or floating
point constants.
2. Examples are 0.0083 , 435.38.
3. A real number may also be expressed in exponential notation.
4. For example : The value 215.65 may be written as 2.1565e² in exponential notation. e²
means multiply by 10². The general form is :
mantissa e exponent
SINGLE CHARACTER CONSTANTS
A single character constant contains a single character enclosed within a pair
of single quote marks
Examples of character constant are : ‘5’,’x’ , ‘a’ .
STRING CONSTANT:
A string constant is a sequence of character enclosed between double quotes.
The character may be alphabets ,digits , special characters and blank space.
Examples are : “hello java”, “1459”.
BACK SLASH CHARACTER CONSTANT:
Java supports some special backslash character constant that are used in
output methods.
A list of such backslash character constant are given below
‘\b’ =backslash , ‘\f ‘=form feed ,’ \n ‘=new line , ‘ \r ‘=carriage return ,
‘\t‘=horizontal .
NOTE: These characters combinations are known as Escape sequence.
VARIABLES:
A variable is an identifier that denotes a storage location used to store a data
value.
A variable may take different values at different instance of time during the
execution of the program.
A variable name can be chosen by the programmer in a meaning full way.
Some examples are :average , height , total_height , classstrength.
While naming the variables we should follow the conditions
1. They must not begin with a digit.
2. Uppercase and Lowercase are distinct.
3. It should not be a keyword.
4. White space is not allowed.
5. Variable names can be of any length.
DATA TYPES:
Every variables in java has a data type.
Data types specify the size and type of values that can be stored.
Java language is rich in its data type.
Various categories of data type of value that can be stored.
Java language is rich in its data types
Various categories of data type are shown below
Data types
Primitive(intrinsic)
Numeric Non-numeric
Classes Array
integer Floating point
Character Boolean
INTEGER TYPE:
Integer type can hold whole number such as 123, -26, 5673.
Non-primitive(derived)
Interface
The size of the values that can be stored depends on the integer data type we choose
Java supports 4 types of integer .They are 1. Byte , 2. Short , 3. Int , 4. Long.
The following table shows the memory size and range of all the 4 integer data types.
TYPES SIZES MINIMUM VALUE MAXIMUM VALUE
byte 1 byte -128 127
short 2byte -32,768 32,767
int 4byte -2,147,483,648 2,147,483,647
long 8byte -9,223,372,036,854,755,808 9,223,372,036,854,755,807
We can make integer long by appending the letter L or l at the end of the
numbers.ex:1234l or 1234L.
FLOATING POINT:
Floating point type can hold numbers containing fractional parts such as 27.56 and -
1.357.
There are two kinds of floating point storage in java .They are float and double.
The following table gives the size and range of these two types.
TYPE SIZE MINIMUM VALUE MAXIMUM VALUE
float 4bytes 3.4e-038 3.4e+038
double 8bytes 1.7e-308 1.7e+308
NOTE: In a single-precision mode (float) ,we must append f or F to the numbers.
Ex: 1.23f , 7.5692F
CHARACTER TYPE:
Java provides a character data type called char. It can hold only a single character .
The character type has a size of 2 byte.
BOOLEAN TYPE:
It is used when we want to text a particular condition during the execution of the
program.
There are only two values that a Boolean type can take: true or false.
It can use only 1 bit of storage.
TYPE CASTING:
We need to store a value of one type in to a variable of another type. In such
situations, we must cast the value to be stored by proceeding it with the type name
in paranthesis.
The syntax: type variable1=(type) variable2;
The process of converting one data type to another is called casting.
Examples: int m=50;
byte n=(byte) m;
long count=(long) m;
casts that result are in no loss of information
FROM TO
byte short , char , int , long , float , double.
short int , long , float , double.
Char int , long , float , double.
int long , float , double.
OPERATORS:
Operator is a symbol that tells the computer to perform certain mathematical and
logical manipulation.
Operators are used in program to manipulate data and variables. They are usually
from a part of expression.
Java operator can be classified in to number of related categories as below:
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment operator
6. Conditional operator
7. Bitwise operator
8. Special operators.
ARITHMETIC OPERATOR:
Java provides all the basic arithmetic operators .They are listed below.
OPERATOR MEANING
+ Addition or Unary plus
- Subtraction or Unary minus.
* Multiplication
/ Division
% Modulo division (Reminder).
Example:
Let us take a=14 and b=4 we have the following results.
a + b= 18, a-b=10 , a*b= 56, a/b= 3(decimal point truncated) , a % b=2(reminder of integer
division) .
RELATIONAL OPERATOR:
We often compare two quantities and depending on their relations take
certain decisions.
For example: we may compare the age of two persons .these comparisons can
be alone with the help of relationship operators.
Java supports 6 relational operators. These operators and their meaning are
shown below:
OPERATOR MEANING
< IS less than
<= Is less than or equal to
> Is greater than
>= Is greater than or equal to
== Is equal to
!= Not equal to.
A simple relational expression contains only one relational operator and is of
the following form.
ae -1 relational operator ae – 2.
ae-1 and ae-2 are arithmetic expression , which may be simple constants ,
variables or combination of them.
CLASS RELATIONAL:
{
Public static void main(String args[])
{
int a=15, b=20, c=15;
System.out.println(“a<b is” +(a<b));
System.out.println(“a>b is” +(a>b));
System.out.println(“a==c is” +(a==c));
System.out.println(“a<=c is” +(a<=c));
System.out.println(“a>=b is” +(a>=b));
System.out.println(“b!=c is” +(b!=c));
}
}
LOGICAL OPERATORS:
Java has three logical operators , which are given below
OPERATOR MEANING
&& Logical AND
|| Logical OR
! Logical NOT
Example : a>b&&x==10
1.An expression this kind which combines two or more relational expression is termed as
logical expression.
2. The logical expression given above is true only if both a>b and x==10 are true .if either of
them false the expression is false.
ASSIGNMENT OPERATOR:
Assignment operator are used to assign the value of an expression to a
variable.
The assignment operator is ‘=’ .Java has a set of shorthand assignment
operator .
The general form is
V op = exp;
Where , v=variable ,exp= expression , op=java binary operator. The operator op= is
called short hand assignment operator.
Some commonly used short hand assignment operator are illustrated as
follows
STATEMENT WITH SIMPLE
ASSIGNMENT OPERATOR
STATEMENT WITH SHORT HAND
OPERATOR
a=a+1 a+=1
a=a-1 a-=1
a=a*(n+1) a*=n+1
a=a/(n+1) a/=n+1
a=a% b a%=b
INCREMENT AND DECREMENT OPERATOR
The operator ++ adds 1 to the operand while – subtracts 1 . Both are unary
operators and are used in the following form .
++m
m++
--m
m--
Pre increment
Post increment
Pre decrement
Post decrement
(++m is equivalent to m=m+1 or m+=1)
Class Inc
{
Public static void main (String args[])
{
int m=10, n=20;
System.out.println(“m is” +m);
System.out.println(“n is” +n);
System.out.println(“++m is” + ++m);
System.out.println(“m++ is” +m++);
System.out.println(“n-- is” +n--);
System.out.println(“--n is” +--n);
}
}
DOT OPERATOR :
The dot operator (.) is used to class the instance variables and methods of
class objects.
Ex: person. age //variable
person. salary() //method
It is also used to access classes and sub-packages from a package.
EXPRESSIONS
An expression is a combination of variables , constants and operators
arranged as per the syntax of the language.
Java can handle any complex mathematical expression.
Some of the examples of java expressions are shown below
ALGEBRIC EXPRESSION
ab-c
(m+n)(x+y)
ab÷c
3x²+2x+1
x÷y+c
JAVA EXPRESSION
A*b-c
(m+n)*(x+y)
A*b/c
3*x*x+2*x+1
x/y+c
CONTROL STATEMENT:
BRANCHING STATEMENT:
Java program is a set of statements , which are normally executed sequentially
in the order in which they appear.
When a program breaks the sequential flow and jumps to another part of the
code , it is called branching.
When the branching is based on a particular condition is known as conditional
branching.
If branching takes place without any decision , it is known as un conditional
branching.
Java possess such decision making capabilities and supports the following
statements,1. If statement ,2. Switch statement , 3. Conditional statement .
The if statement may be implemented in different forms depending on the
complexity of conditions to be tested .1. simple if statement , 2. If….. else statement ,
3. Nested if …..else statement , 4. Else if ladder.
SIMPLE IF STATEMENT:
The general form :
if (test expression)
{
Statement_block
}
Statement _x;
The statement block may be a single statement or a group of statement .
If the test expression is true , the statement _block and the statement x are
executed , otherwise the statement _block will be skipped and the execution will
jump to the statement_x.s
FLOW CHART:
Test expression?
Next statement
CONSIDER THE FOLLOWING SEGEMENTS OF A PROGRAM
Statement _block
Statement_x
……………………………………………
………………………………….
If(category==sports)
{
Marks += bonus_mark;
}
System . out . Print ln(marks);
…………………………………..
…………………………………
THE if……..else statement:
a)It is an extension of the simple if statement .the statement form
If(test expansion)
{
True-block statement
}
Else
{
False-block statement
}
Statement-x;
*If the text expansion is true ,then the true-block statement are executed, otherwise ,the
false-block statement are executed
FLOW CHART:
(T) Test expression? (F)
Program
Class if else
{
P S V main(string orgs[])
{
int num[]={65,56,50,81,44};
Int even =0, odd =0;
for (int i=0; i<num. length ; i ++)
{
If ((num[i] %2) ==0)
{
Even +=1;
}
Else
{
Odd+=1;
}
True-block
statement
False –block
statement
Statement-x
}
S.o.print (“even number ” +even+ “odd number” + odd );
Nested of if …. Else statement
when a series of decisions are involved , we may have to use more than one
if …..else statement is nested from as follows :
if ( tested condition1)
{
if (test condition 2 )
{
statement 1 ;
}
else
{
Statement2:
}
}
else
{
Statement 3;
}
Statement x;
FLOW CHART:
Test expression1?
test expression 2?
Statement 3 Statement 2
Next statement
Program
Class IfElseNesting
{
Public static void main(String args[])
{
int a=32 , b=71 , c=47;
System.out.println(“LARGEST VALUE IS:”);
if (a>b)
{
if (a>c)
{
System.out.println(a);
}
else
{
if(c>b)
Statement 1
Statement x
{
System.out.println(c);
}
else
{
System.out.println(b);
}
}
}
}
THE else-if LADDER:
a) There is another way of putting if statement together when multi path decision are
involved.
b) It takes the following general form:
if (condition 1)
statement 1;
else if(condition 2)
statement 2;
else if(condition 3)
statement 3;
……………………………….
……………………………………
else if(condition n)
statement n;
else
default statement;
statement x;
c) The conditions are evaluated from the top to down. As soon as the condition is true ,
the statement associated with it is executed and the control is transferred to the
statement –x.
d) If all the conditions become false , the the final else containing the default –
statement will be executed .
e) Consider the following segment of the program
if(marks >79)
grade = “Distinction”;
else if(marks>59)
grade =”First class”;
else if(marks>49)
grade = “Second class”;
else if(mark>39)
grade = “Third class
else
grade=”Fail”;
System.out.println(“Grade:”+grade);
The flow chart shows the logic of execution of elseif ladder statements.
(t) Condition 1 (f)
(t) condition 2 (f)
(t)condition 3 (f)
Statement 3
(t) Condition 4 (f)
Statement
2
Default statement
Statement x
Next statement
CONDITIONAL OPERATOR:
*The character pair ?: is a ternary operator .This operator is used to construct conditional
expression of the form
exp1 ? exp2 : exp3
Where exp1 , exp2 and exp3 are expressions.
*Here exp1 is evaluated first , if it is true , then the expression exp2 is evaluated otherwise
exp3 is evaluated .
Example:
Statement 1
Statement 2
a=10; b=5;
x = (a<b) ? a : b;
*In this example , x will be assigned the value of b. This can be achieved using the if-else
statement as follows
if (a>b)
x=a;
else
x=b;
BIT WISE OPERATORS
*These operators are act upon the individual bits of their operator . They are summarized
in the following table
OPERATOR RESULT
~ Bit wise NOT
& Bit wise AND
| Bit wise OR
^ Bit wise XOR (Exclusive OR)
>> shift right
>>> shift right zero fill
<< shift left
&= Bit wise AND assignment
!= Bit wise OR assignment
^= Bit wise XOR assignment
>>= shift right assignment
>>>= shift right zero fill assignment
<<= shift left assignment
THE BIT WISE LOGICAL OPERATOR:
*The bit wise logical operator are & , | , ^ and ~.
* The following table shows the outcome of each operation.
A B A|B A&B A^B ~A
0 0 0 0 0 1
1 0 1 0 1 0
0 1 1 0 1 1
1 1 1 1 0 0
SPECIAL OPERATORS:
*Java supports some special operators . They are instanceOf operator and member
selection operator(.).
1.INSTANCEOF OPERATOR: The instanceof is an object reference operator and returns true
if the object on the left hand side is an instance of the class given on the right hand side .
This operator allows us to determine whether the object belongs to a particular class or
not. EXAMPLE: person instanceOf student;
*Is true if the object person belongs to the class student.
THE SWITCH STATEMENT:
*The switch statement tests the value of a given variable or expression against a list of case
value and when a match is found , a block of statement associated with that case is
executed.
* The general form of the switch statement is as shown below:
Switch (expression)
{
case value 1:
block 1;
break;
case value 2:
block 2;
break;
………………………….
……………………………
default:
default-block;
break:
}
Statement x;
*The expression is an integer expression on character .
*Value1 , value2 . . . . . . . are constants or constants expression and are known as case labels.
Each of them values should be unique.
* block1 , block2 . . . . . . . are statement list and may contain zero or more statements.
* There is no need to put braces around these blocks but it is important to note that case
labels and with colon(:).
*When the switch is executed , the value of the expression is successively compared with
the value1 , value2 .
*If a case is found whose value matches with the value of the expression , then the block of
the statement that follows the case are executed .
*The break statement at the end of each block signals the end of a particular case and
causes an exit from the switch statement , transferring the control to the statement x
following the switch.
*The default is an optional case . It will be executed if the value of the expression does not
match with any of the case value.
* If not present , no action takes place when all matches fail and control goes to the
statement x.
*The selection process of switch statement is illustrated as follows:
switch expression
expression=value1
block 1
expression =value2
(no match) default
*consider the following segments of a program
. . . .. . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . .
Index=marks/10;
Switch(index)
{
Case 10:
Case 9:
Case 8:
grade = “Distinction”;
break;
case 7:
case 6:
grade =”First class”;
block2
Statement-x
default block
break;
case 5:
grade = “Second class”;
break;
case 4:
grade = “Third class”;
break;
default:
grade=”Fail”;
break;
}
System.out.println(“Grade:”+grade);
. .. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . .
. . . . .. . . . . . . . . . . . . . . . .
*The segment of the program illustrates 2 important features:
1. It uses empty cases. The first 3 cases will execute the same statement .
2. default condition is used.
LOOPING
1.Every computer language must have features that instruct a computer to perform
such respective tasks.
2. The process of repeatedly executing a block of statements is known as looping.
3. A program loop consists of two segments , one known as the body of the loop and
the other known as the control statements.
4. The control statement tests certain conditions and then directs the repeated
execution of the statement contained in the body of the loop.
5.A control structure may be classified either as the entry-controlled loop or as exit
controlled loop.
a) Entry control b) Exit control
entry
test condition? (f)
test condition? (f)
(t)
Body of the
loop
* Java provides three constructs for performing loop operation . They are
1. while construct , 2. do construct , 3. for construct
1. THE WHILE STATEMENT:
The basic format of the while statement is
While (test condition)
{
Body of the loop:
}
*The while is an entry-controlled loop statement .
* The test condition is evaluated and if the condition is true , then the body of the loop is
executed.
Body of the
loop
(t)
*After execution of the body , the test condition is once again evaluated and if it is true , the
body is executed once again.
*This process of repeated execution of the body continous until the test condition becomes
false.
*consider the following program
Class whileTest
{
Public statics void main(String arg[])
{
StringBuffer str=new StringBuffer();
Char c;
While ((c=(char)System.in.read())!=’\n’)
{
Str.append(c);
}
System.out.println(str);
}
}
2.THE DO STATEMENT:
* On some cases it might be necessary to execute the body of the loop before the text is
performed . Such situations can be handled with the loop of the do statement
*The general format is
Do
{
Body of the loop
}while (test conditrion);
*Here, the body of the loop is evaluated first .At the end of the loop, of the test condition
in the while statement is evaluated.
*If the condition is true , the program continues to evaluate the body of the loop once
again.
* This process continues as long as the conditions is true .Otherwise the control
transferred to the statement x.
*consider the following program
Class DwTest
{
Public static void main(String args[])
{
Int r , c , y ;
System .out.println(“MULIPLICATION TABLE \n”);
r=1;
do
{
c=1;
do
{
y=r*c;
System.out.println( “ “+y);
c+=1;
} While(c<=3);
System.out.println(“\n”);
r+=1;
}while(r<=3);
}
}
3. THE for STATEMENTS:
*The for loop provides a more concise loop control structure.
The general form of the for loop is
for(initialization ;test condition ; increment / decrement)
{
Body of the loop
}
*The execution of the for statement is as follows:
1. Initialization of the control variable is done first , using assignment statements such as
i=1 and count = 0.
2. The value of the control variable is tested using the test condition .If the condition is
true , the body of the loop is executed , otherwise the loop is terminated.
3.When the body of the loop is executed , the control is transferred back to the for
statement after evaluating the last statement in the loop. Now , the control variable is
incremented /decremented using an assignment statement such as i=i+1; i=i-1;
* consider the segment of a program
. . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . .
Sum=0;
For(n=1 ; n<=10 ;n++)
{
Sum +=n*n;
}
*The body of the loop is executed 10 times .
4. THE NESTED for LOOPS:
*Nesting of loops , i.e ,one for statement within another for statement .
*for loops can be nested as follows:
For(i=1 ;i<=n ; i++)
{
. . . . . . . . .
. . . . . . . . . . .
For(j=1 ; j<=n ; j++)
{
. . . . . . . . . . . . . . . inner outer
. . . . .. . . . . . . . . . . loop loop
}
. . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . .. . .
}
*A program segment to display a multiplication table using for loops is shown below
:
for (row=1; row<=r ; r++)
{
for( col=1 ; col<=c ; col++)
{
y=row * col;
System.out.println(“ “+y);
}
System.out.println(“\n”);
}
THE JUMP STATEMENTS:
1. BREAK:
a .An early exit from a loop can be accomplished by using the break statement .We have
already seen the use of the break in the switch statement.
b. This statement can also be used within while , do or for loops.
c. When the break statement is encounted inside a loop , the loop is immediately exited and
the program continous with the statement immediately following the loop.
d. The general form of break statement is
for( . . . . . . . . )
{
. . . . . . .. . . .. . .. .. . ..
.. . . . .. . . . .. . . .. .
If(condition)
break;
. . . . . . . . . . . . . exit from
. . .. . .. . . . .. . . . loop
}
. . . . . . . . . . . . . . .
PROGRAM USING BREAK TO EXIT A LOOP
Class breakE \ex
{
Public static void main(String args[])
{
For (int i=0 ; i<=10 ; i++)
{
If (i==5)
Break; //terminate the if i-5
ASstem.out.println(“i:”+i);
}
System.out.printl;n(“LOOP TERMINATES”);
}
}
2. CONTINUE
*Unlike the break which causes the loop to be terminated , the continue , as the name
implies causes the loop to be continued with the next iteration after skipping any statement
in between.
* The format of the continue statement in loop is illustrated below
For(. . . . . . . . . . . . .. . . . . )
{
. . . . . . . . . . . . . . .. .
If(condition)
Continue;
. . . . . . . . . . . . . .
. . . . .. . .. . . . .. . . . . .
}
PROGRAM
Class cont
{
Public static void main(String args[])
{
For (int i=0 ; i<10 ; i++)
{
If(i%2==0)
Continue;
System.out.println(“ “+i);
}
}
}