Вы находитесь на странице: 1из 48

c  



   
 
   
?
 ?
  ???
C is a structured programming language invented in the year 1980¶s. It is a powerful tool
that enables programmers to write complex programs.
OOPs is an approach to program organization and development. Not all languages are
suitable to implement the OOP concepts easily. Languages that support OOPs features include
small talk, objective C, C++, Ada and object Pascal.
C++ is an extension of C language. It is the most popular language with object-oriented
extension. The latest one added to this list is Java, a pure object-oriented language.
?

  ?
??
OOP¶s allows us to decompose a problem into a   ? ?  ?   ?   and
then build data and functions around these entities. The combination of data and methods make
up an object.
Object = Data + methods
 ?   ?  ? ? ?  ?  ?  ? ?  ? ?   ?
 ?? ?  ? ?  ???  ? ?? ? ? ? ? ?
   ?? ? ???  ?? !?

"#$ ?%?
$&'?
?()*+' ?$'$ ,-!?

  ?
·? -mphasis is on data rather than procedure.
·? Programs are divided into objects.
·? Data structures are designed such that they characterize the objects.
·? |ethods 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.
·? ×ollows bottom-up approach in program design.
?
"#$ ?%?($ *?**?
?()*+' ?','$-- ,.??
©?   ?Objects are the basic runtime entities. They may represent a person, a place, a
bank account or any item that the program may handle.
©? *   ? A class is a collection of objects of similar type. -xample: |ango, Apple &
Orange are members of the class fruit. Classes are user-defined data types and behave
like the built-in types of a programming language.
©?    The wrapping up of data and methods into a single unit (called class).
©? $  It refers to the act of representing essential features without including the
background details or explanation.
©?    It is the process by which objects of one class acquires the properties of
another class.
©?   means the ability to take more than one form. The behavior depends
upon the types of data used in the operation.
©?  ? It means that the code associated with a given procedure call is not
know until the time of the call at runtime. Binding refers to the linking of a procedure
call to the code to be executed in response to the call.
?
(  ?? ?
OOP offers several benefits to both the program designer and the user. The new technology
promises greater programmer productivity, better quality of software and lesser maintenance cost.
X? Through inheritance, eliminate redundant code and extend the use of existing classes.
X? Build programs from the standard modules that communicate with one another.
X? The principle of data hiding helps the programmer to build secure programs that cannot
be invaded by code in other parts of the program.
X? It is possible to have multiple objects to co-exist without any interference.
X? It is possible to map objects in the problem domain to those objects in the program.
X? It is easy to partition the work in a project based on objects.
X? The data centered design approach enables us to capture more details of a model in an
implementable form.
X? Object oriented systems can be easily upgraded from small to large systems.
X? |essage passing techniques for communication between objects make the interface
descriptions with external systems much simpler.
X? aoftware complexity can be easily managed.
†' ?%?$# *$ ?
?!??
$ ?? ?
·? ‘eal-time systems
·? aimulation and modeling
·? Object oriented databases.
·? rypertext, hypermedia and expertext
·? AI and expert systems
·? Neural networks and parallel programming
·? Decision support and office automation system
·? CAD/CI| systems
†' ?%?

'*?(†?*?$?)$/$.??
)  ? ?* ?
·? Java does not include the C unique statement keywords goto, sizeof and typedef.
·? Java does not contain data type struct, union and enum.
·? Java does not define the type modifiers keywords auto, extern, register, signed and
unsigned.
·? Java does not support an explicit pointer type.
·? Java does not have a preprocessor and therefore we cannot use #define, #include and
#ifdef.
·? Java does not support any mechanism for defining variable arguments to functions.
·? Java requires that the functions with no arguments must be declared with empty
parenthesis and not with the void keyword as done in C.
·? Java adds new operator such as instance and >>>.
·? Java adds labeled break and continue statements
·? Java adds many features required for object oriented programming.

"#$ ?%?

'*?(†?)$/$?$?*00!??
)  ? ?*00 ?
Java is a true object oriented language while C++ is basically C with object oriented extension.
·? V  ??? 
? 

?
   ?
·? Java does not have template classes.
·? Java does not support multiple Inheritances of classes. This is accomplished using a new
feature called 6.
·? Java does not support global variables. -very variable and method is declared within a
class and forms parts of that class.
·? Java does not use pointers.
·? Java has replaced the destructor functions with finalize () function with a finalize()
function.
·? There are no header files in JAVA.
·? Java does not have a preprocessor and therefore we cannot use #include and # ifdef
statement

`  ??

? `

)$/$?$? '?
?
%†?)$/$? ?',#1?$* $?† %?%? '.??
*' (?%?/$' &?1-?'2& '?
'? '?','$-- ,.??
)$/$?3? ' ?
¦? Java expands the universe of objects that can move about freely in cyberspace. In a
network, two very broad categories of objects are transmitted between the server and your
personal computer: passive information and dynamic, active programs.
¦? Java is strongly associated with the Internet because the first application program written in
Java was rot Java, a web browser to run applets on Internet.
¦? Internet users can use Java to create applet programs and run then locally using ³Java-
enabled browser6 such as rot Java.
¦? „sing Java-enabled browser to download an applet located on a computer anywhere in the
Internet and run it on local computer.
¦? Java is popularly known as Internet language.
¦? Java can be used to create two types of programs: applications and applets. An application
is a program that runs on your computer, under the operating system of that computer.
¦? An  is actually a   Java program, dynamically downloaded across the network, just
like an image, sound file, or video clip


  







?
? 4 ??  ? ?   5?
?
†%$? ?†††.?†%$? ?%?*' (& ?
?)$/$??%?†††.??
)  ? ?††† ?
â? ††† is an open ±ended information retrieval system designed to be used in the internet¶s
distributed environment.
â? The web pages contain rT|L tags that enable us to find, retrieve, manipulate and display
documents world wide. The java could be easily incorporated into the web systems.
â? The incorporation of java into web pages has made it capable of supporting animation,
graphics, games and a wide range of special effects.
›  
     
      

!""#
â? Java communicates with a web page through a special tag called <APPL-T>. The below
figure shows the communication steps:
? The user sends a request for an rT|L document to the remote computers web server.
The web server is a program that accepts a request processes the request, and sends
the required document.
? The rT|L document is returned to the users browsers. The document contains the
APPL-T tag, which identifiers the applet.
? The applet byte code is transferred to the user¶s computer. This byte code had been
created by the Java compiler using the Java source code file for that applet.
? The Java enabled browser on the users computer interprets the byte code and provides
output.
? The user may have further interaction with the applet but with no further
downloading from the provider¶s web server. This is because the byte code contains
all the information necessary to interpret the applet.

$ 

‰  
 

‰ 



?

?
 
?







 *&?$(&?†(?('†'?3? ?1!?
† ?  ?
The Internet consists of more information represented in many formats and stored on
many computers. The web browsers are used to navigate through the information found on the
net. They allow retrieving the information spread across the Internet and displaying it using the
rypertext |arkup Language (rT|L).
An example of web browsers includes:
â? rot Java.
â? Netscape Navigator.
â? Internet -xplorer.
?
%?)$/$ ?
? rot java is the web browser from aun |icrosystems that enables the display of
interactive content on the web using the Java language. It was entirely in Java.
? †hen the Java language was first developed and ported to the Internet, no browsers were
available that could run java applets.
? rot java is currently available for the aPA‘C/ aolaris platform as well as †indows 95
and †indows NT.
   ?   ?
? Netscape navigator from Netscape Communication Corporation is a general purpose
browser that can run Java applets. †ith versions available for window 95, NT, aolaris and
Applet |acintosh, NN is one of the most widely used browsers today.


 
½ ? Visual display about downloading process and indication of the number of bytes
downloaded. It also supports Javaacript, a scripting language used in rT|L
document.
  ?6  ?
A popular web browser developed by |icrosoft for †indows 95 and NT workstation.
Both the Navigator and -xplorer use tool bars, icons, menus and dialog boxes for easy
navigation. Internet -xplorer uses Just-In-Time (JIT) compiler which greatly increases the speed
of execution.

%& ''
?
†' ?%'???)$/$?/ '&$#?-$*% .?
†%$? ?-$?(1?(1?*.?
? Byte code is a highly optimized set of instructions designed to be executed by the java
run-time system, which is called the ava irtual achine (JV|). It is an interpreter for byte
code.
In other word, the Java compiler produces an intermediate code known as byte code for a
machine that does not exist. This machine is called the Java Virtual |achine and it exists only
inside the computer memory.
The process of compiling a java program into byte code is referred to as virtual machine
code.
 ??  ?
?
  
    

 ? ? ? ?
? ? ? ??????????( ?* ?
The virtual machine code is not machine specific. The machine specific code (known as
machine code) is generated by the java interpreter by acting as an intermediary between the
virtual machine and the real machine.
 ?? ? ? ??  ? ?

‰ `    

/ ?  ???????????????????????????????????????????????????????????????????????' ?  ?


The use of byte code enables the java run-time system to execute programs much faster.
Just-In-Time (JIT) compiler is part of the JV|, it compiles byte code into executable code in
real time, on a piece-by-piece. 

('
'( 
?
"#$ ?%?
$&'?
?)$/$? ?(' 
!?
The aun |icrosystems describes Java with the following attributes.
? Compiled and interpreted
? Platform ± independent and portable
? Object oriented
? ‘obust and secure
? Distributed
? ×amiliar, simple and small
? |ultithreaded and Interactive
? righ performance
? Dynamic and -xtensible

·*  ? ?     ?
>? The computer language is either compiled or interpreted. Java is a two-stage system.
1.? Java compiler translates source code into byte code instruction. Byte codes are
not machine instructions.
2.? Java interpreter generates machine code that can be directly executed by the
machine that is running the java program.

·  +   ? ?  ?
º? Java programs can be easily moved from one computer system to another, anywhere
and anytime.
º? The user downloads a Java applet from a remote computer onto our local system via
Internet and executes it locally.
º? The changes and „pgrades in operating systems, processors and system resources will
not force any changes in Java programs.
º? Java achieves the portability in two ways:
? Java compiler generates byte code instructions that can be implemented on any
machine.
? The sizes of the primitive data types are machine independent.

· +   ?
â? Java is a pure object-oriented language. -verything is an object. The program code and
data reside within objects and classes.

·'? ?  ?
·? Java is a robust language. It provides many safeguards to ensure reliable code. This
language incorporates with exception handling which captures series errors and
eliminates any risk of crashing the system.
·? aecurity becomes an important issue for a language. Java systems not only verify
memory access but also ensure that no viruses are communicated with an applet.
·? The absence of pointers in java ensures that programs cannot gain access to memory
locations without proper authorization.

·  ?
·? Java is designed for creating applications on networks. It has the ability to share both data
and programs. Java applications can open and access remote objects on Internet as easily
as they can do in a local system.
·? This enables multiple programmers at multiple remote locations to collaborate and work
together on a single project.

·  7? ? ?
  ?
·? Java is a small and simple language. It does not use pointers, preprocessor header files,
goto statement and many others.
·? It also eliminates operator overloading and multiple inheritance.
·? ×amiliarity is another striking feature of java. Java was modified on C and C++
languages. It uses many constructs of C and C++. Java code looks like a C++ code. It¶s
a simplified version of C++.

·-  ? ?   ?
·? |ultithreaded means handling multiple tasks simultaneously. It supports multithreaded
programs. No need to wait for the application to finish one task before beginning another.
This feature greatly improves the interactive performance of graphical applications.
·? The Java runtime comes with tools that support multiprocess synchronization and
construct smoothly running interactive systems.

·%?   ?
JAVA speed is comparable to the native C/C++. Java architecture is also designed to
reduce overheads during runtime.
· ? ?6  ?????
 JAVA is capable of dynamically linking in new class libraries, methods and objects. It
can also determine the type of class through a query, making it possible to either dynamically
link or abort the program, depending on the response.
Java programs support functions written in other languages such as C and C++. These
functions are known as native methods. Native methods are linked dynamically at runtime.

 ' 'c' '  ' 
?
†' ?%'???)$/$?/#-?/ '-!??
©? Java environment includes a large number of development tools and hundreds of classes
and methods.
©? The development tools are part of the system known as Java Development Kit (JDK) and
the classes and methods are part of the Java atandard Library (JaL) also known as
Application Programming Interface(API).

†' ?%'???)$/$?/#-?8 ?4)85!?


The Java Development Kit comes with a collection of tools that are used for developing
and running java programs. They include:
ƒ? $ ?/  ?(for viewing java applets)-To run java applet.
ƒ? )   (java compiler)-Translates source code to byte code files.
ƒ? )  ?(java interpreter) - which runs applets and applications.
ƒ? )   for C header files)-produces header files for use with native methods.
ƒ? )  ?(java dissembler) - converts byte code files into a program description.
ƒ? )?(java debugger)-To find errors in our programs.
ƒ? )   for creating rT|L documents).

 ??? ??  ?  ? ?
ƒ? Create a source code file using text editors.
ƒ? The source code is then compiled using the java compiler javac and executed
using the java interpreter java.
ƒ? The java debugger jdb is used to find errors, if any, in the source code.
ƒ? A compiled java program can be converted into a source code with the help of
java disassemble javap.
?
†' ???$# *$ ?','$-- ,? '
$*?4$ 5!?
$ ? ?    ?4$ 5 ?
The Java standard Library (or) API includes hundreds of classes and methods grouped
into several functional packages.
?
-? ? ? 9  ?  ??
>? #   ?? 9  ??A collection of methods and classes required for basic
features of java.
>? & ?  9  A collection of classes to provide utility functions such as date and
time functions.
>? :? 9  ?A collection of classes required for input/output manipulation.
>?  9?  9  A collection of classes for communicating with other computers
via Interface.
>? $†?  9   Abstract †indow Tool Kit contains classes that implements graphical
user interface.
>? $ ? 9  This includes a set of classes that allows us to create java applets.

 )  ' ' 
?
†' ?$(&?)$/$?*%$'$*'?!??
M? The smallest units of java language are the characters used to write java tokens. These
characters are defined by the „nicode character set, an emerging standard.
M? „nicode is a character set that aims to define all characters.
M? The „nicode is a 16-bit character coding system and currently supports more than
34,000 defined characters derived from 24 languages from America, -urope, |iddle
-ast, Africa and Asia.
M? It includes letters, digits and punctuation marks. These characters are defined by the
„nicode character set.

c'   
?

?'$'!??
Java supports a rich set of operators. An operator is a symbol that is used to perform
certain mathematical or logical manipulations. Operators are used in programs to manipulate
data and variables.

"#$ ?%?1?
?'$'? ?)$/$?† %?"$-#!?
Java operators can be classified into number of related categories.
¦? Arithmetic Operator
¦? ‘elational Operator
¦? Logical Operator
¦? Assignment Operator
¦? Increment and Decrement Operator
¦? Conditional Operator
¦? Bit-wise Operator
¦? apecial Operators

$ ?   ?


The operators +,-,*, / and % all work the same way as they do in other languages. †e
can¶t use these operators on Boolean type.
  ? - ?
+ Addition
- aubtraction
* |ultiplication
/ Division
% modulo division
These can operate on any built-in numeric data type of java. The unary minus operator,
multiplies its single operand by -1. A number preceded by a minus sign changed its sign.
Arithmetic operators are used as follows:
6  ?
 a+b, a-b, a*b, a/b, a % bwhere a & b are operands

  ?$  ?
†hen both the operands in a single arithmetic expression such as a+b are integers, the
expression is called an integer expression, and the operation is called integer arithmetic.
6  ?
a = 14 b = 4
a - b = 10 a * b = 56 a % b = 2 a + b = 18 a / b = 3

' ?$  ?
An arithmetic operation involving only real operands is called real arithmetic. A real
operand may assume values either in decimal or exponential notation. ×loating point values are
rounded to the number of significant digits permissible; the final value approximates the correct
result.
6  ?
a= 20.5× b= 6.4× means
a + b = 26.9
a - b = 14.1
a * b = 131.2
a / b = 3.2031
a % b = 1.3

-6 +  ?   ?


†hen one of the operands is real and the other is integer, the expression is called mixed-
mode arithmetic expression. If either operand is of the real type, then the other operand is
converted to real and the real arithmetic is performed.
6  ?
  15 / 10.0 produce the result 1.5
15 / 10 produce the result 1

'   ?   
The comparisons can be done with the help of relational operators.
  ? - ?
ù Is less than
ù  Is less than or equal to
* Is greater than
*  Is greater than or equal to
  Is equal to
+  Is not equal to

A simple relational expression contains only one relational operator.


???????? 6 ae-1 relational operator ae-2
†here, ae-1 and ae-2 are arithmetic expressions, which may be a simple constant, variable or
combinations of them.
6  ?
? 6 ? ? /  ???????
7 < 10 true
2.5 > 1.5 false
    20 > 8+5 false
# ?   
Java language has three logical operators. They are:

  ? - ?
** Logical AND
ii Logical O‘
+ Logical NOT
These operators are used to combine two or more relations to form compound conditions.
It is termed as logical expression or compound relational expressions. It also yields a value of
true or false.
6  ?
a >b && x = = 10
Combines two or more relational expression is termed as a logical expression or a
compound relational expression.
?  ?
?/  ?? 6 ?
+;? +<?
+;?33?+<? +;?==?+<?
True True True True 
True ×alse ×alse True 
×alse True ×alse True

×alse ×alse ×alse ×alse



6  ?? ? ?????  ???
? ?????
????
???

$ ?   ?
Assignment operators are used to assign the values of an expression to a variable.
Assignment operator is = (equal to).

a m   


†here, is a variable;,is an expression,  is a binary operator. The operator  "known


as theshorthand assignment operator.
6  ?
x = x + 1 is equal to x += 1
y = y + 5 is equal to y += 5
a = a * (n+1) is equal to a *= n + 1
a = a ± 1 is equal to a -= 1
$    ?
¦? †hat appears on the left-hand side need not be repeated.
¦? The statement is more concise and easier to read.
¦? The shorthand operator results in a more efficient code.

 ? ?  ?   ?
 The operator ++ and ± is the increment and decrement operators. These two are very
useful operators. The ++ operator adds 1 to the operand and -- subtracts 1 from the operand. Both
are unary operator and may be used in the forms.
¦? ++m (or) m++
¦? --m (or) m--
¦? ++m is equivalent to m=m+1 or m+=1
¦? --m is equivalent to m=m-1 or m-=1
These two operators are used in for and while loops.
6 ??
m=8
m=8
y = ++ m
y = m++
-y = 9 y = 8 then at next turn y = 9
A prefix operator first adds 1 to the operand and then the result is assigned to the variable
on left. A postfix operator first assigns the value to the variable on left and then increments the
operand.
* ?   ??
 The character ".- is a ternary operator. This operator is used to construct conditional

6;.? 6< ? 6@?


?
expression of the form:

†here exp1, exp2 and exp3 are expressions. The exp1 is evaluated first. If it is true, then
the expression exp2 is evaluated and becomes the value of the conditional expression. If exp1 is
false, exp3 is evaluated and its value becomes the value of the conditional expression.
6  ? ??>  ???
    /01! ½0" *!
,  *!.-!2·, 2
  
 
, !2
( ?   ?
 It is used for testing the bits or shifting them to the right to left. It may not be applied to
float or double.

  ? - ?
* Bitwise AND
i Bitwise O‘
3 Bitwise exclusive O‘
4 One¶s complement or bitwise unary NOT
ùù ahift left
** shift right
*** ahift right with zero fill
*  Bitwise AND assignment 
i  Bitwise O‘ assignment ?
?
3  Bitwise exclusive O‘ assignment
?
**  ahift right assignment ?
ùù  ahift left assignment ?
***  ahift right zero fill assignment ?
?
6  ?
1010 · 0101 (bitwise NOT)
1010 & 1111 · 1010 (bitwise AND- produces a 1 bit if both operands are also 1, otherwise 0)
1010 | 1110 · 1111 (bitwise O‘- produces a 1 bit if either of the bits in the operands is a 1,
otherwise 0)
1010 ^ 1111 · 0101 (bitwise XO‘ ± produces a 1 bit if exactly one operand is 1, otherwise 0)
?
  ?   ?
Java contains two special operators. They are:
¦? Instance of operator.
¦? |ember selection operator (.)
  ??   ?
It 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. It allows us to determine whether the object
belongs to a particular class or not.
6  person   ? student
It returns µtrue¶ if the object person belong to class student, otherwise it is µfalse¶.
?4!5?   ?
The dot operator is used to access the instance variables and methods of class objects.
6  person.age; // reference to variable age
person.salary ( ); // reference to method salary ()
?
  ?    ?
Parentheses are used to alter the precedence of an operation. It is often necessary to
obtain the result.

)"5# 
  67
 88 99 4
 : ; <
 8 9
 ** *** ùù
 * *  ù
  +  
 3
 i
 **
 ii
 .-
    
=
?
   '' 

A programming language uses control statements to cause the flow of execution to


advance and branch based on changes to the state of a program.
†hen a program breaks the sequential flow and jumps to another part of the code, it is
called  .
†hen the branching is based on a particular condition, it is known as  ?
 . It branching takes place without any decision it is known as  ?
 
Java¶s program control statements can be put into the following categories: selection,
iteration and jump.
©?   ?    allow our programs to choose different paths of execution based
upon the outcome of an expression or the state of a variable.
©?   ?   enable program execution to repeat one or more statements.
©? ) ?   allow our program to execute in a nonlinear fashion.
?
)  A?  ?   ?
Java supports two selection statements: if and switch. These statements allow us to
control the flow of our program¶s execution based upon conditions known only during run time.
?
†' ?%'???
?$-!?
;5? ?   ?
· The ?statement is a powerful decision making statement and is used to control the flow
of execution of statements. It is a two way decision statement and is used in conjunction with an
expression.


>,-?4 ? 6 5?
?
It allows the computer to evaluate the expression first and then depending on whether the
values of the expression is µtrue¶ or µfalse¶, it transfer the control to a particular statement.
6 
"? if (a> 0)
The number is positive
""? if (tamil >=40)
‘esult is pass

The if statement in different forms


è? a  ? ? ?
è?  ? ?
è? p?  ? ?
è? - ? ? 
?

"#$ ?$(&? -#?
?$-!?
The general form of a simple if statement is

   

   


 
 

The µ ?  !" may be a single or group of statements. If the test expression is true
then statement block will be executed otherwise statement block will be skipped and execution
will jump to µstatement x¶.


6  ?
if ( weight <10)
{
weight = weight +10;
}
weight = 0;
?
<5??C?  ?   ?
The ?statement is Java¶s conditional branch statement. It can be used to route program
execution through two different paths.

          

    

If the condition is true, then statement1 is executed. Otherwise statement2 is executed.


-ach statement may be a single statement or a compound statement enclosed in curly braces.
The condition is any expression that returns a Boolean value. The else clause is optional.
6  ?
?44?D?E?<5?F?F?G5?
!
 !!?4H?? ?  ??  ?H5I?
??
 ?
!
 !!?4H? ?  ???H5I?
?
 ?
 ?  ??  !?
?
 *&?$(&? ,?
?
!!!#?$-!?
@5?!!!  ?   ?
†hen a series of decision are involved, use more than one if« else statement in nested
form.
,   ? ?
  "@""½
  !
  " @""A
  !
  9½2
  ?
  
  !
   9A2
  ?
 ?
  
  !
  9B2
  ?
  9,2
If the condition 1 is false, the statement-3 will be executed; otherwise it continues to
perform the second test. If the condition 2 is true, the statement 1 will be executed, otherwise the
statement-2 will be evaluated and then the control is transferred to the statement-x.
6  To find largest of 3 numbers
? ?
{
 ?  ? ? ?a
 ?
#?$?
? %?
? ???? ? &'?('? )(*?
? ???? ?? ???
? ???%?
? ???????? ?? ? ?
? ????????%? ? ?
? ? a
 ?+?,-? ??
? ?+?.?? ?
*?
? ?????????/?
? ????????? ?
? ?????????%?
? ? ?a
 ?+?,-? ??
? ?+?.?? ?
*?
? ?????????/?
? ???/?
? ???? ?
? ????%? ?
? ????????? ?? ??
? ?????????%? ? ?
? ? a
 ?+?,-? ??
? ?+?.?? ?
*?
? ?????????/?
? ????????? ?
? ?????????%?
? ? a
 ?+,-? ??
? ?+?.???
*?
? ?????????/?

  ? ?  ???J<


?
? ???/?
???????/?
??/?
?
 *&?$(&?#?
?#$'!?
K!?  ??  ?
It is used when multipath decisions are involved use else if ladder statement. A multipath
decision is a chain of "¶s in which the statement associated with each  is an ".
?
,   ? ?
?
    

   

     

   



     

   

The conditions are evaluated from top to towards. The true condition is found, the

statement associated with it is executed and the control is transferred to the statement-x. †hen
all the n conditions become false, then the final else containing the default statement will be
    
executed.
-  0?    

1 ? 
?
%? ? ?
?  ?  ? ? a
 ?
#$?
? %??
? ? ?
#$??%''&')/*?
? ? ?#$??%2'(')&'2/*?
? ? 
 ???*? 
  -*? ..?
? ? %?
? ? ? # $??(3?
? ? ? ? a
 
# $*?
? ? ?  ? ?# $?3?
? ? ? ? a
 
# $*?
? ? ?  ? # $?)3?
? ? ? ? a
 
# $?.?+??   4*?
? ? ?  ?
? ? ? ? a
 
# $?.?+ 4*?
? ? /?
? /?
/?
?
 *&?$(&?† *%?$-!??
?   ?
? Java has a built-in multi-way decision statement known as a ="# The switch statement
tests the value of a given variable against a list of case values and when a match is found, a block
of statements associated with the case is executed.
?
,   ? ?
??4 6 5? ?
!
case value-1:
block-1;
break;
case value-2:
block-2;
break;
««
default:
default-block
break;
?
  ?6I?

The expression is an integer expression or characters. Value1, value 2 «.. are constants
or constants expression and are known as case labels. Block1, block2 are statement lists and may
contain zero or more statement.
†hen the switch is executed, the value of the expression is successively compared
against the values value1, value2« If a case is found whose value matches with the value of the
expression, then the block of statements that follow the case are executed.
The break statement at the end of each block signals the end of a particular case and exit
from the switch statement, transferring the control to the statement x following the switch.
The default is an optional case. The selection process of switch statement is as follows:






 '>

a 




',C ½
‰

‰ 
',C A

 #@

?
6  ?
class city
{
public static void main(atring args[])
{
char choice;
aystem.out.println(³choice6);
aystem.out.println(³|· |adras6);
aystem.out.println(³B· Bombay6);
aystem.out.println(³C· Calcutta6);
aystem.out.flush();
try{
switch(choice = (char)aystem.in.read()
{
case µ|¶
case µm¶: aystem.out.println(³|adras6);
case µB¶
case µb¶: aystem.out.println(³Bombay6);
case µC¶
case µc¶: aystem.out.println(³Calcutta6);
default: aystem.out.println(³Invalid6)¶
}
}
catch(-xception e)
{
aystem.out.println(³error in statement6);
}
}
}
  ??   ?
A switch is part of the statement sequence of an outer switch. This is called a nested
switch.

switch (count)
{
case 1:
switch(target)
{
case 0:
aystem.out.println (³target is zero6);
break;
case 1:
aystem.out.println (³target is one6);
break;
}
break;
case 2: «.
? ? ? ?
There are three important features of the switch statement:
½ ? The ="#differs from the "?in that switch can only test for equality, whereas " can
evaluate any type of Boolean expression.
A ? No two  constants in the same ="# can have identical values. A ="#
statement enclosed by an outer ="# can have  constants.
B ? A ="# statement is usually more efficient than a set of nested "
?
)  A?  ?   ?
Java iteration statements create loops. The process of repeatedly executing a block of
statements is known as looping. The statements in the block may be executed any number of
times from zero to infinite number. If a loop continues forever, it is called as infinite loop.
A program loop consists of two segments
©? Body of the loop
©? Control statement
The control statement tests certain conditions and then directs the repeated execution of the
statements contained in the body of the loop. It classified into 2 types.
? +* ??
? 6+* ??





(
‰ "
  

 ?
(
     

 ‰ " ?

 



  '>  
   ',"

+* ?·?The control conditions are tested before the start of the loop execution.
If the conditions are not satisfied then the body of the loop will not be executed.
6+* ??·?The test is performed at the end of the body of the loop and therefore the
body is executed unconditionally for the first time.
The looping process involving four steps:
X? aetting and initialization of a counter.
X? -xecution of the statements in the loop.
X? Test for a specified condition for execution of the loop.
X? Incrementing the counter.
The java language provides three constructs. They are:
·? † ?  ?
·? ?  ?
·?
?  ?
?
"#$ ?†% #?$-?$?, /?$?"$-#!??
† ?   ?
It repeats a statement or block while its controlling expression is true.
???? 6 ???????????
initialization
?†  test condition
!
body of the loop2
?
?

The while is an entry-controlled loop statement. The test condition is evaluated and if the
condition is true the body of the loop is executed. 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 continues until the condition finally becomes false, and the control is
transferred out of the loop.
The body of the loop may have one or more statements. The braces are needed only if
the body contains two or more statements.
?
6  ?
?5-  ?%?
?
 ?  ? ? a
 ? #$?
%?
 ?  ? ? a
 ? #$?
%?
?%? ???*?
? ? ?'?6*?
7- ?
? 7- .. ??6..*88???
%?
? ?a
 +9 ? ?4. *?
a
+:4.*?
?/? ? ;;*?
?/? /?
/?/?
?
‘esult is 150
 
?
'? ? ? ? ?

The body of the while loop can be empty. This is because a null statement is syntactically valid
in Java.
?
"#$ ??$-?† %?& $(#?"$-#!??
 It executes the body of the loop before the text is performed.
 6 ??

initialization
?????
????

??????????? ?
? ?

?????G ?

?
?

?
The program evaluates the body of the loop statement first. At the end of the loop, 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 condition is
true.
†hen the condition becomes false, the loop will be terminated and the control goes to the
statement that appears immediately after the =#" statement.
The test condition is evaluated at the bottom of the loop. And therefore the body of the
loop is executed at least once.
6  ??
 ???*?
? ??%?
? ? a
 +:?+?.*?
? ? ?;;*?
? ???????/?7- *?

†' ?$???L
'A?$-!?
 The for loop is a entry-controlled loop that provides a more concise loop control
structure.
>,-

    <  *??   *? 

! 

????????????????
 ??? #

The execution of the µfor¶ statement is as follows:
ƒ? Initialization of the control variables is done first using assignment statements. " = 0,
count = 0. The variables " and count are known as loop control variables.
ƒ? The value of the control variable is tested using test condition. If the condition is true
the body of the loop is executed, otherwise the loop is terminated and the execution
continues with the statement that immediately follows the loop.
ƒ? †hen the body of the loop is executed the control is transferred back to the µfor¶
statement after evaluating the last statement in the loop.
6  ?
class ×orex
{
public static void main(atring a[])
{
int n;
for(n=10; n>0; n--)
aystem.out.println(n);
}
}
  ?#??   ? ? ?? ?
It is possible to declare the variable inside the initialization portion of the  
  for (int n=10; n>0; n--)
aystem.out.println(n);
†hen we declare a variable inside a for loop, there is one important point to remember:
the scope of that variable is limited to the  loop. Outside the  loop, the variable will cease
to exist. If we need to use the loop control variable elsewhere in our program, we will not be
able to declare it inside the loop.
-  0?
class forst
{
public static void main(atring a[])
{
int num;
boolean isprime = true;
num=14;
for(int i =2; i< num/2; i++)
{
if(num % i) == 0)
{
isprime = false;
break;
}
}
if(isprime)
aystem.out.println(³prime6);
else
aystem.out.println(³Not prime6);
}
}
$ ?  ??? ?
1) |ore that one variable can be initialized at a time in the for statement.
-xample : for (i=0, j=0; i<10; i++) // Initialization section has
separated by comma.
2) The increment section has more than one part.
-xample: for (n=1, m=50; n<=m; n=n+1, m=m-1)

---

---

}
3) The test condition may have any compound relation and the testing need not be limited only to
the loop control variable.


-xample:
sum=0;
for (i=1, i<20 && sum <100; i++)
{

---
  }
4) It is also permissible to use expression in the assignment statements of initialization and
increment section.


-xample: for(x= (m+n) /2; x>0; x=x/2)


5) ×or loop is than one or more sections can be omitted
-xample: for (; m! =50 ;)
6) Both the initialization and increment section are omitted in the  statement. The
initialization has been done before the  statement and the control variables is incremented
inside the loop. The body of the loop contains only one semicolon is known as empty statement.
  ?#?
One  statement within another  statement is called nesting for loop. That is, one
loop may be inside another.
>,-
 " ½2"ù½0288"
!
DD 
DD 
 E ½2E+ /288E
!
DDD 
DDD 
?
DDD 
DDD 
?
DD 

The outer loop controls the rows while the inner one controls the column.
6  ??    ? ?  ?
? class Nesting
{
public static void main(string a[])
{   
int i,j;
for(i = 0; i<5; i++)
ööööö?
{
öööö?
for(j=1; j<5; j++)
ööö?
aystem.out.print(³*6);

aystem.out.println();
}

aystem.out.print(³\n6);
}
}

†' ???)&-? ?#!?


Java supports three jump statements: break, continue, and return. These statements
transfer control to another part of the program.
?
&? 9 ?
The break statement has three uses.
½ ? It terminates a statement sequence in a ="# statement.
A ? It can be used to exit a loop.
B ? It can be used as a ³civilized6 form of goto.
?
;5?&? 9??6? ? ?
†e can force immediate termination of a loop, bypassing the conditional expression and
any remaining code in the body of the loop. †hen a !F statement is encountered inside a
loop, the loop is terminated and program control resumes at the next statement following the
loop.
-x:
class Breakloop
 
{
public static void main(atring a[]) Y??? Y???? Y??? Y??? Y?? ??
{
for(int i =0; i<100; i++)
{
if(i == 5)
Break;
aystem.out.print(³\t I = ³+i);
}
aystem.out.println(³\n Loop complete6);
}
}

<!?&? 9? ? ? ?? ?


This form of !F works with a label.
   
a #?

†here,    is the name of a label that identifies a block of code. The control is transferred out
of the named block of code. A   ?is any valid Java identifier followed by a colon.
? 6  ?
class Breakst
{
public static void main(atring a[])
{
first: for(int i=0; i<3; i++)
{
aystem.out.print(³Pass ³ + i + ³: ³);
for(int j=0; j<100; j++)
{
if(j == 10)
break first;
}
aystem.out.println(³This will not print6);
}
aystem.out.println(³Loop complete.6);
}
}
?
&? ?
It helps to skip a part of the body of the loop under certain conditions. The part of the
program loop that processes the application details is skipped and the execution continues with
the next loop operations.
Java supports another similar statement called the continue statement. The break
statement called the continue statement.
The break which causes the loop to be terminated, the " as the name implies
causes the loop to be continued with the next iteration after skipping any statement in between.

>,-"2 
? 6  ?
class Cont {
public static void main (atring a[]) ? ?
{
for(int i =0; i<10; i++) { ? ?
aystem.out.print(i+ ³6);
? '?
If(i%2 == 0)
Continue;
aystem.out.println(³6);
}
}
}
 ?
It is used to explicitly return from a method. It causes program control to transfer back to
the caller of the method. It is categorized as a jump statement.
At any time in a method the return statement can be used to cause execution to branch
back to the caller of the method. The  statement immediately terminates the method in
which it is executed.
? 6  ?
class ‘eturnex
{ public static void main(atring a[])  ‰  ?
?
!?
{ boolean t = true;
aystem.out.println(³Before the return.6);
if(t) return;
aystem.out.println(³This won¶t execute.6);
}
}
As soon as  is executed, control passes back to the caller.

c'c  

Java program may contain many classes of which only one class defines a main method
classes contain data members and methods that operate on the data members of the class.
|ethods may contain data type declarations and executable statements.

"" a 

cF5"
 
"
"  

""" 
"#@  
!
"#@@"""
 
?2
4,   ? ?? ?)$/$? 5?
?
  ?  ??
 It contains set of comment lines giving the name of the program, the author and other
details. Comments must explain why and what of classes and how of algorithms.
/** « */ is known as @" . It is used for generating
documentation automatically.
?
 9  ?   ??
This statement declares a package name and informs the compiler that the classes defined
here belong to this package.
6  ?cF5>F52·This statement is optional.
?
?   ??
 Importstatement is similar to the #include statement in C.
 ">F5 >2
It instructs the interpreter to load the > class contained in the package student.
„sing import statements, we can access to classes that are part of other named packages.
?
?
   ?   ?
An interface is like a class but includes a group of method declarations. It is an optional
section and is used only to implement the multiple inheritance features in the program.


a% 6  ?
?
? * ?    ?
Class Classname · declares a class,
?
which is an object-oriented construct. Java is
’
?`

? a true object-oriented language and therefore
everything must be placed inside a class.
? Class is a keyword.
?
??????  ’? 
’??
 ? ?
 ??  ?  ?
-very class definition in java begins
???????? with an opening brace ³{³and ends with
matching closing brace ³}6 appearing in the last line.
?
- ? ??
c ?  ? ? ?a
 ?
#?$?defines a method named  . m  method is
the starting point for the interpreter to begin the execution of the program. A java application
can have any number of classes but only one of them must include a main method to initiate the
execution.

The main line contains a number of keywords


·? !"· An access specifier, methods can be accessed in other classes.
·? "· This method belongs to entire class and not part of any object of the class.
|ain must always be declared as static.
·? "@· It states that the main method does not return any value.

atring args[ ] declares a parameter named args, which contains an array of objects of the class
type string.
?
 ?? ?
The only executable statement in the program is:
a
  (³rai16);
? †here, println method is a member of the out object, which is a static data member of
system class. This line prints the string += >4
Println · appends a newline character to the end of the string. -very java statement must
end with a semicolon.
"!- A named memory location that may be assigned a value by our program. The value of
a variable may be changed during the execution of the program.


a% ',"

? "  · it declares an integer variable
called    Java requires that variables
’
?`

? be declared before they are used.

? "- ? + I?
?

??????  ’? 
’??
 ? ?
 ?? Java defines several data types,
including integer, character, and floating
???????? point.

???????????? ?  !?   ½002 · It assigns the value 100 to


the variable  
?  ?"?#$$!?

>  "  " 82· In this the plus sign causes the value of  to be
appended to the string that precedes it.
 :B2· The * operator is used to indicate multiplication.
   ?  ?? ? ?
The print () method is just like println (), except that it does not output a newline
character after each call.



 )  &('
'
?

*' (?%?% '1?


?)$/$!?
)  ?% ?
JAVA is a general-purpose, Object-Oriented Programming Language developed by a?
@
 of „aA in 1991. It¶s originally called oak by V ?A  , one of the inventors
of the language.
Java is a platform-neutral language i.e. it is not tied to any particular hardware or Oa
programs developed in Java can be executed anywhere on any system.
   
& C
1990 aun-micro systems decided to develop special software team
head is James Gosling.
1991 After Object-oriented language C++, a new language called
Oak is announced.
1992 Green project team by aun, demonstrated the application of
new language to control a list of home appliances.
1993 †eb applets (tiny programs) by green project teams.
1994 †eb browser called ³rot Java6.
1995 Oak was renamed as ³Java6.
1996 Java found its home.
Versions:
¦? Java 1.0 - 212 classes in 8 packages, released |ay 1996
¦? Java 1.1 - 503 classes in 23 packages, released ×eb 1997
¦? Java 1.2/2.0 - 1,520 classes in 59 packages, released Dec 1998
¦? Java 5.0 - 3562 classes in 166 packages.

- ³×eatures of Java6 topic is already given in page no.: 5

 ' 'c' G  G

The most popular Java compiler is aun's a7


?B  ?C ?VBC?It contains the
core libraries and compiler required to develop Java. It is typically used in one of the following
ways.
¦? ×rom the DOa command window with the è   command.
¦? †ith a program editor (eg, TextPad) which has an interface to the compiler.
¦? †ith an ID- (Integrated Development -nvironment)
?
,-?VBC? ? ?-
?  0?
â? Java 2 atandard -dition (J2a-)· this is the basic platform for Java.
â? Java 2 -nterprise -dition (J2--)· this edition is mainly for developing and running
distributed multitier architecture Java applications, based largely on modular software
components running on an application server.
â? Java 2 |icro -dition (J2|-)· this is primarily for developing programs to run on
consumer applicances, such as PDAs and cell phones.

,-?VBC?- ? ?

?  ? ?   ??

  ? '?    0?
«? java ± the loader for Java applications. This tool is an interpreter and can interpret the
class files generated by the javac compiler.
«? javac ± the compiler, which converts source code into Java bytecode
«? jar ± the archiver, which packages related class libraries into a single JA‘ file. This tool
also helps manage JA‘ files.
«? javadoc ± the documentation generator, which automatically generates documentation
from source code comments
«? jdb ± the debugger
«? jps ± the process status tool, which displays process information for current Java
processes
«? javap ± the class file disassembler
«? appletviewer ± this tool can be used to run and debug Java applets without a web
browser.
«? javah ± the C header and stub generator, used to write native methods
«? extcheck ± a utility which can detect JA‘-file conflicts.
«? jstack ± (experimental) utility which prints Java stack traces of Java threads
«? jstat ± (experimental) Java Virtual |achine statistics monitoring tool
«? jinfo ± (experimental) This utility gets configuration information from a running Java
process or crash dump.
«? jmap ± (experimental) This utility outputs the memory map for Java and can print shared
object memory maps or heap memory details of a given process or core dump.

  G'
?

?8!??
†' ?%'???)$/$?8!??
The tokens of a language are the basic building blocks which can be put together to
construct programs.
! <=   
| !7
 | 

|  

| 
|  ?
?

A token can be a reserved word (such as "or =#"), an identifier (such as ! or ), a
constant (such as A/ or H @@H), a delimiter (such as ! or2) or an operator (such as 8 or
).

6? ??9 ? 


½ ? Identifiers: names the programmer chooses
A ? Keywords: names already in the programming language
B ? aeparators (also known as punctuators): punctuation characters and paired-delimiters
ß ? Operators: symbols that operate on arguments and produce results
/ ? Literals (specified by their >)
·? Numeric: " and @!
·? Logical: !
·? Textual: # and "5
·? ‘eference: 
I ? Comments
·? Line · //
·? Block · /* « */

?
)  ?   ?  ??
M? The smallest units of java language are the characters used to write java tokens. These
characters are defined by the „nicode character set.
M? The
"@ is a 16-bit character coding system. There are 216 = 65,536 „nicode
characters. aince this character set is very large and its structure very complex. It is
derived from 24 languages from America, -urope, |iddle -ast, Africa and Asia.
M? It includes letters, digits and punctuation marks. These characters are defined by the
„nicode character set.


?

?81†'!?
8  ?
Java has reserved 50 words as keywords. It cannot be used as names for variables,
classes, methods and so on. Keywords are written in lower-case letters. aince java is case
sensitive. These identifiers have built-in meanings that cannot change. Thus, programmers
cannot use these identifiers for anything other than their built-in meanings.
?
abstract continue goto package switch ??????????????????? ?


assert default if private this 



boolean do implements protected throw 

break double import public throws ?
byte else instanceof return transient ?
?
case extends int short try ?
?
catch final interface static void ?
char finally long strictfp volatile ?
?
class float native super while ?
?
const for new synchronized ?
?

? 
'!?
ð?    ??
It is a programmer-designed token. It is used for naming classes, methods, variable,
object, labels, packages and interfaces in a program.
?
' ??)  ?   ?
·? It can have alphabets, digits, underscore and dollar sign characters. (a-z (or) A-Z,
_, $)
·? It must not begin with a digit. (Illegal: ëtotal)
·? „ppercase and lowercase letters are distinct. (Total, total · not same)
·? They can be of any length.
·? It must be meaningful, short enough to be quickly and easily typed.
 ?  ?
>? Names of all public methods and instance variables start with a leading lowercase letter.
†hen more than one word, the second and subsequent words are marked with a leading
uppercase letters.
>? All private and local variables use only lowercase letters combined with underscores
>? All classes and interface start with a leading uppercase letter.
>? Variables that represent constant values use all uppercase letters and underscores between
words.
???????6  ???Total, Average, Total_cost, length, dayTemp, relloJava
?
†%$?$'?%?*/ ?
##†? ?)$/$?
'?$- ,? 
'.?
, /?-?"$-#!??

?# '$#!???
ð#   ??
A literal is a sequence of characters that represent constant values to be stored in
variables.
 ??  0?
L? Integer literals
L? ×loating-point literals
L? Character literals
L? atring literals
L? Boolean literals

ð   ??
 An operator is a symbol that takes one or more arguments and operates on them to
produce a result. Java includes 37 operators that are listed in the table below:
= > < ! ~ ? :
== <= >= != && || ++ --
+ - * / & | ^ % << >> >>>
+= -= *= /= &= |= ^= %= <<= >>= >>=
The keywords " and = are also considered operators in Java.
?
†%$?$'?$'$'.?*' (?%?/$' &?$'$'?&? ?)$/$.?
ð?    ??
 aeparators are symbols used to indicate where groups of code are divided and arranged.
? ? ? 

<=; | , | . | ( | ) | { | } | [ | ]

5
Parentheses  „sed to enclose parameters in method definition and for defining
the precedence in expressions.
Braces !? To contain the values of automatically initialized arrays and to
define a block of code for classes, methods and local scopes.
Brackets 67 To declare array types and for dereferencing array values.
aemicolon 2 To separate statements
Comma 1 To separate consecutive identifiers in a variable declaration, also
used to chain statements together inside a µfor¶ statement.
Period To separate package names from sub-packages and classes, also
used to separate a variable or method from a reference variable.
?
ð?  ? >   ?
An  ;D  inside the single-quotes for a -

; 
or one or more inside
double-quotes for a 
 ; 
each escape sequence is translated into a character that prints in
some "special" way. aome commonly used escape sequences are
'
"5
J
K ="
K #"L!
KC C"!
K! !F
K "5
K @
K !
KK K (needed to denote \ in a text literal)
KM M (does not act as the right M of a char literal)
KH H (does not act as the right H of a atring literal)


   '' 

"#$ ?$(&?)$/$?$-?$? ?1?
?$-.??
†%$? ? $-.? %†? ? %? )$/$? $-? 

'?
'-? %?

?*?$?*00.??
A statement is an executable combination of tokens ending with a semicolon (;) mark.
atatements are usually executed in sequence order.
 ??   ?
·? '>·„sed during program development as a place holder.
·? !@  ·  Labels are not keywords. It is used as the arguments of jump
statements.
·? ',"·?There are 7 types of expression statements.
? Assignment
!? Pre-increment
? Pre-decrement
@? Post-increment
? Post-decrement
? |ethod call,
5? Allocation expression
*?   ?
It contains the following three types:
©? aelection statement
©? Iteration statement
©? Jump statement

©?  ?   ??
 There are three types of selection statements in java. They are
1. if statement
2. if-else statement
3. switch statement

©   ?   ??
These specify how and when looping will take place. There are three types of iteration
statements.
They are:
½ †hile
A do
B for.


©?) ?   ??
It passes control to the beginning or end of the current block or to a labeled statement.
×our types:
½ ? break,
A ? continue
B ? return
ß ? throw.

c ?   ?
It is used for handling issues with multithreading.
c?, ?   ? ?
 It is used for safe handling of code that may cause exceptions. These statements use the
keywords try, catch, and finally.




 &

?$''$1 ??
An array is a group of like-typed variables that are referred to by a common name.
Arrays of any type can be created and may have one or more dimensions. A specific element in
an array is accessed by its index. Arrays offer a convenient means of grouping related
information.
A particular value is indicated by writing a number called  6?   or  in
brackets after the array name.
??????????6  6½072
 It represents the sum of 10 numbers. Thecomplete set of values is referred to as an array;
the individual values are called  .
?
†%1?$''$1?$'?$ '??&?*-$'??$?(&*%?
?'#$?
/$' $(#.?
$ ? ? ?? ?   ? ?
The ability to use a single name to represent a collection of items and to refer to an item
by specifying the item number enables us to develop concise and efficient programs.
There are 3 types:
¦? One-dimensional array
¦? Two dimensional array
¦? |ulti-dimensional array
?
"#$ ?? - $#?$''$1!?
A list of items can be given one variable name using only one subscript and such a
variable is called a single-subscripted or one-dimensional array.
An array must be declared and created in the computer memory before they are used.
Creating an array involves 3 steps.
·? Declare the array.
·? Create memory locations.
·? Put values into the memory locations.
?
   ??   ?
There are two forms to declare
;!?  ?   MNI?
<!?  MN?   I?
?
* ??   ?
Java allows to create arrays using new operator. = is a special operator that allocates
memory.
? ,   ? ? ?? + ?F? ? M NI?
????????????????????????????????????????6??? ?? ?F? ?M;GNI?

? ,   ? ? ? ? + MNI?


? ??????6? ????a[10];
i.e. a[0], a[1],«..a[9]. The subscript can begin with number 0.That is a[0] is allowed.
The subscript of an array can be integer constants, integer variable like µi¶ or expressions that
yield integers.
?
"#$ ?$ #?$(&?†? - $#?$''$1!?
Two dimensional array values are referred by using subscripts for both the column and
row of the corresponding element. Two dimensional arrays may be initialized by following their
declaration with a list of initial values enclosed in braces.
6  ?
int A[ ][ ];
-  ?$ 
|ultidimensional array is referred as ³arrays of arrays6. To declare a multidimensional
array variable, specify each additional index using another set of square brackets.
6  ?
 int a[ ][ ] = new int[3] [ ];
 int a[0] = new int[2];
int a[1] = new int[4];
int a[2] = new int[3];

(‘ows · 3, Colomns · undefined)


 6 ?
 class Table
{
final static int rows =10;
final static int cols = 10;
public static void main(atring a[])
{
int p[] [] = new int[rows][cols];
int i,j;
for(i=10; i<rows; i++)
{

for(j=10; j<cols; j++)

p[i][j] = i * j;

aystem.out.println(p[i][j]);

aystem.out.println(³ ³);
}
}
}

'  


?/*'!??
†%$? ?%?

'*?(†?/*'?$?$''$1.
†%$?$'?%?-%?%$?$'?$/$ #$(#? ?/*'.? ?
·? Vector represents a collection of similar items. In Java, the m M class is defined in
EC " package that implements a growable array of objects.
·? Like an array, its items can be accessed using an integer index. Once the m  has been
created, the size of a m  can be grown or reduced as needed to adding and removing
items to that vector.
·? Vectors are extremely easy to use, and implement. Creating a vector is easy. †e just need
to simply define a variable of type Vector, and call the vector constructor.

Vectors are
¦? -  - store only one kind of element;
¦?   - permit clients to access values using integers that indicate position;
¦? -  - provide fast access to values.

„nlike arrays, vectors are     - we can continue to add elements to a vector, even if the
vector has grown beyond its original size
 
 -  intVect = new Vector ( ); // declaring without size
 list = new Vector (3); // declaring with size
?
Vectors possess a number of advantages over arrays.
¨? It is convenient to use vectors to store objects.
¨? A vector can be used to store a list of objects that many vary in size.
¨? †e can add and delete objects from the list as and when required.
In vector we cannot directly store simple data types in a vector; we can only store
objects. This can be done using the wrapper classes.
?
/ ?-  ?
?
- ? ?  9?  ?
è? list.add-lement(item) è? Adds the item specified to the list at the list
è? list.elementAt(10) at the end.
è? list.size( ) è? Gives the name of the 10th object.
è? list.remove-lement è? Gives the number of objects present.
è? list.remove-lementAt(n) è? ‘emoves the specified item from the list.
è? list.removeAll-lement( ) è? ‘emoves the item stored in the nth position
è? list.copyInto(array) of the list.
è? list.insert-lementAt(item, n)? è? ‘emoves all the elements in the list.
è? Copies all items from list to array.
è? Inserts the item at nth position.?

?
6  ?
import java.util.Iterator;
import java.util.Vector;
public class Vector1
{
public static void main(atring[] args)
{
Vector v = new Vector();
? ? ::?&? ? ?  ?  ?  ?? ?
v.add("1");
v.add("2");
v.add("3");
v.add("4");
::?&? ?? ?? ? ? ?
aystem.out.println("Vector aize :"+v.size());
aystem.out.println("Getting elements of Vector by get method ");
aystem.out.println("*****************************************");
::?&? ? ?? ? ?  ?? ? ?
for(int i=0;i<v.size();i++)
{
aystem.out.println("Vector -lement "+i+" :"+v.get(i));
}

aystem.out.println("Getting elements of Vector by methods ");


aystem.out.println("*****************************************");
aystem.out.println("\tThe elements of vector : " + v);
aystem.out.println("\tThe elements at position 2 is : " + v.elementAt(2));
aystem.out.println("\tThe first element of vector is: " + v.first-lement());

aystem.out.println("\t
2 "!#?$ 
? The last element of vector
is : " + v.last-lement());
$ 
?%& ? ? ?
v.remove-lementAt(2
(

)? * 
? ?$ 
??)
?*
? );
}
ööööööööööööööööööööööööööööööööööööööööö? }
$ 
?+ * 
?? ?

$ 
?+ * 
?? ?

$ 
?+ * 
?? ?

$ 
?+ * 
?? ?

)? * 
? ?$ 
??*
?

ööööööööööööööööööööööööööööööööööööööööö?

????????, ? * 
? ? 
???????? ?-.?.?.? /?

????????, ? * 
?
?
??? ??

????????, ? 
? * 
? ? 
? ??

????????, ? 
? * 
? ? 
?? ? ?

2 "!#?

?
  %
((' 


?' ,!?
%†??*#$'?$?' ,.?
 atrings represent a sequence of characters. The easiest way to represent a sequence of
characters in java is by using character array.
char name[]=new char[4];
name[0] = µJ¶;
name[1] = ¶a¶;
name[2] = ¶v¶;
name[3] = µa¶;
In Java, strings are class objects and implemented using two classes, namely string and
string buffer. A Java string is an instantiated object of the string class. It is not a character array
and is not N„LL terminated.
 6 ?
? ???????? I? ?         G    

????????4'5?
?  ?F? ?4HO5I????
?
6 ??
atring name;      G    !

4'5
name = new atring(³nila6);
To get the length of the string using the length method of the string class, using
parentheses string can be concatenated using the + operator.

?
?
?
?
?
?
?
?
6 ?
atring name1 = new string(³ aathya 6);
atring name2 = new string(³ |oorthy 6);
atring name = name1 + name2;
a
#@ F
th
ystem.ou
s1.setcharAt(n,¶x¶) |odifies the n character to x. t.println(
s1.append(s2) Appends the string s2 to s1 at the end. name);
Inserts the string s2 at the position n of the string s1. ?
s1.insert(n,s2)
aet the length of the string s1 to n. If n<s1.length ( ) s1 is
s1.setLength(n)
truncated. If n>s1.length ( ) zeros are added to s1.
?   ?
atring a[] = new atring[3]; // It holds three string constants.

?  ?
$-?-?
?%?' ,?-%?%$?$'?&? ?)$/$.??
The string class defines a number of methods that allow us to accomplish a variety of string
manipulation tasks.
#@ F@
s2 = s1.toLowerCase Converts the string s1 to all lowercase.
s2 = s1.to„pperCase Converts the strings s1 to all „ppercase.
s2 = s1.replace(µx¶,¶y¶); ‘eplace all appearances of x with y.
s2 = s1.trim( ); ‘emove white spaces at the beginning and end of the string s1.
s1.equals(s2) ‘eturns µtrue¶ if s1 is equal to s2.
s1.equalsIgnorecase(s2) ‘eturns µtrue¶ if s1 = s2, ignoring the case of characters.
s1.legnth( ) Gives the length of s1.
s1.CharAt(n) Gives nth character of s1.
s1.compareTo(s2) ‘eturns negative if s1<s2, positive if s1>s2, and zero if s1 is equal s2.
s1.concat(s2) Concatenates s1 and s2.
s1.substring(n) Gives substring starting from nth character.
s1.substring(n, m) Gives substring starting from nth character up to mth
atring.ValueOf(p) Creates a string object of the parameter p.
p.toatring( ) Creates a atring representation of the object p.
s1.indexOf(µx¶) Gives the position of the first occurrence of µx¶ in the string s1.
s1.indexOf(µx¶,n) Gives the position of µx¶ that occurs after nth position in the string s1.
atring.ValueOf(Variable) Converts the parameter value to string representation.

†' ???' ,?(&

'?*#$!?
? ?  ?
A string buffer implements a mutable sequence of characters. A string buffer is like a
a, but can be modified. It contains some particular sequence of characters, but the length
and content of the sequence can be changed through certain method calls.
atring buffers are safe for use by multiple threads.

   ?  ?? ??  ?


 "5 "5!
1. „sed to manipulate character „sed to represent characters that can be modified.
strings that cannot be changed.
2. It is slow for performing simple It is faster for performing simple concatenations.
concatenations.
#@ F
Concatenations are typically To perform the same concatenation, we would need
‘eturns current length.
length()performed as follows: the code as follows:
3. atring
capacity() str = new atring ("atanford capacity. str = new atringBuffer ("atanford ");
atringBuffer
‘eturns total allocated
"); To set the size of thestr.append("Lost!!");
buffer.
ensurecapacity()
str += "Lost!!";
setLength(n) aet the length of the buffer.
charAt(pos) The value of a single character can be obtained.
setCharAt(pos,ch) aet the value of a character within a buffer.
getChars() To copy a substring of a buffer into an array.
append(str/num) Concatenates the string representation to other type of data.
insert(pos, str) It inserts one string into another.
reverse() It returns the reversed object.
delete(start, end) Deletes a sequence of characters from the invoking object.
deleteCharAt(pos) Deletes the character at the index specified by pos.
replace(start,end,str) It replaces one set of characters with another.
substring(start) ‘eturns a portion of a stringbuffer.

?
?
( ? ?
substring(start,end)

  1  %'  &c'




?*$!?"#$ ?%?1?
?*$?† %?"$-#!??
Constants in java refer to fixed values that do not change during the execution of a
program.

??????????????)  ?* ?

 ?* ?? ??????????????????????????????????????????*   ?* ?

???   ?* ??????????' ?* ????????????????????????*   ?* ?????


* ???????
?
  ?*  ?
An integer constant refers to a sequence of digits. 3 types: 
ð   ?  ·?It consists of set of digits 0 to 9, preceded by an optional minus sign.
(-x: 12450)
ð ?   ?·?It consists ofany combination of digits from the set 0 to 7 with leading
0. (-x 037)
ð% 6   ?  ?· It consists of sequence of digits proceeded by 0x or 0X. It may
also include alphabets A through × or ¶a¶ to µf¶. It represents the number 10 to 15. (-x 
0X2, 0X9×)
?
' ?*  ??
Numbers containing fractional part are called real constants.
6 215.03, 0.75, -0.52, 0.0083
? It have a whole number followed by a decimal point and the fractional part. It is possible
that the number may not have digits before the decimal point or digits after the decimal point.
6 ?215.00, 0.95, -0.71?
A real number may also be expressed in exponential or scientific notation.
? 6 215.65 · 2.1565e2
†here e2 means multiply by 102


>,--  ? ? 6 ?

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.
A floating point constant has 4 parts:
· a whole number
· a decimal point
· a fractional part
· an exponent.

 ?*   ?*  ??


 A single character constant contains a single character enclosed within a pair of single
double quote marks. 6 ¶6¶, µy¶, µ;¶ , µ µ

?*  ?
A string contains is a sequence of characters enclosed between double quotes. The
characters may be alphabets, digits, special characters and blank spaces.
6 ³hello java6 ³19796 ³welcome6, ³r6
?

?/$' $(#!?†%$?$'?%?'&#?
##†?(1?*#$'?$?
/$' $(#!??
 A Variable is an identifier that denotes a storage location used to store a data value. The
name can be chosen by the programmer in a meaning way.
Variable names consist of alphabets, digits, underscore (-) and dollar characters, subject
to following conditions:
'  ?
¿? They must not begin with a digit.
¿? „pper case and Lower case letters are distinct.
¿? It should not be a keyword.
¿? †hite space is not allowed.
¿? Variables names can be of any length.

"#$ ?%?/$' &?$$?1? ?)$/$?† %?"$-#!??


Data types specify the size and types of values that can be stored. The variety of data
types available allows the programmer to select the type appropriate to the needs of the
application.
â Primitive types (intrinsic or built in types) â Derived types (reference type)
  ?  ?
>? A whole number without decimal point. It can hold whole numbers.
>? The size of the values depends on the integer data type.
>? The size of the values that can be stored depending on the integer type.
>? Java does not support the concept of unsigned types. ao it may be signed ie positive or
negative.
>? Java supports four types of integers. They are:
 ?  ? -  ?  ? - 6  ?  ?
byte 1 byte -128 127
short 2 byte -32,768 32,767
int 4 byte -2,147,483,648 2,147,483,647
long 8 byte -9,223,372,036,854,775,808 9,223,372,036,854,775,807


?
?
?
?
?
? 2  
?
?
?
?  " #   "
?
?
?
? %
? # # # `
?
?
?
? $  ×    `   & $  
?

 +?  ?
A whole number with decimal point. There are two kinds of floating point storage in
Java.
Ö? The  type values are single-precision numbers while the double types
represent double-precision numbers.
Ö? ! precision types are used when we need grater precision in storage of
floating point numbers.

Append µf µor µ×¶ to single precision mode numbers. 6 ?1.23f, 7.5694e5f


|athematical functions such as sin, cos and sqrt return double type values.
?
*   ? ??
Java provides a character data type called char. It assumes a size of 2 bytes but it can
hold only a single character.
?
( ? ??
 It is used to test a particular condition during the execution of the program. There are
only two values: true or false.
 ?  ? -  ?  ? - 6  ?  ? This data type is denoted by the
×loat 4 bytes 3.4 e-038 3.4 e+038 keyword Boolean and use only
double 8 bytes 1.7 e-308 1.7 e+308 one bit of storage. Boolean
values are often used in
selection and iteration statement.


  c' '
?

Вам также может понравиться