Sei sulla pagina 1di 44

Java Programming

Java Notes
Primitive Data Types in Java
Java's primitive data types are very similar to those of C. They include boolean, byte,
short, int, long, float, double, and char. The boolean type has been added. However the
implementation of the data types has been substantially cleaned up in several ways.
1. Where C and C++ leave a number of issues to be machine and compiler dependent
for instance the si!e of an int" Java specifies everything.
#. Java prevents casting between arbitrary variables. $nly casts between numeric
variables and between sub and superclasses of the same ob%ect are allowed.
&. 'll numeric variables in Java are signed.
si!eof isn't necessary in Java because all si!es are precisely defined. (or instance, an int is
always ) bytes. This may not seem to be ade*uate when dealing with ob%ects that aren't base
data types. However even if you did +now the si!e of a particular ob%ect, you couldn't do
anything with it anyway. ,ou cannot convert an arbitrary ob%ect into bytes and bac+ again.
Mallikarjun Page 1 5/18/2014
Java Programming
Java's Primitive Data Types
boolean
-.bit. /ay ta+e on the values true and false only.
true and false are defined constants of the language and are not the same as True and
False, TRUE and FALSE, !ero and non!ero, - and 0 or any other numeric value.
1ooleans may not be cast into any other type of variable nor may any other variable be
cast into a boolean.
byte
- signed byte two's complement". Covers values from .-#2 to -#3.
short
# bytes, signed two's complement", .&#,342 to &#,343
int
) bytes, signed two's complement". .#,-)3,)2&,4)2 to #,-)3,)2&,4)3. 5i+e all numeric
types ints may be cast into other numeric types byte, short, long, float, double". When
lossy casts are done e.g. int to byte" the conversion is done modulo the length of the
smaller type.
long
2 bytes signed two's complement". 6anges from .7,##&,&3#,0&4,28),338,202 to
+7,##&,&3#,0&4,28),338,203.
float
) bytes, 9::: 38). Covers a range from -.)0-#72)4)&#)2-303e.)8 to
&.)0#2#&)44&28#2240e+&2 positive or negative".
5i+e all numeric types floats may be cast into other numeric types byte, short, long,
int, double". When lossy casts to integer types are done e.g. float to short" the
fractional part is truncated and the conversion is done modulo the length of the smaller
type.
double
2 bytes 9::: 38). Covers a range from ).7)0484)82)-#)48))e.&#)d to
-.37347&-&)24#&-830e+&02d positive or negative".
char
# bytes, unsigned, ;nicode, 0 to 48,8&8
Chars are not the same as bytes, ints, shorts or <trings.
Mallikarjun Page 2 5/18/2014
Java Programming
Java Operators
'n operator is a symbol that operates on one or more arguments to produce a result.
The Hello World program is so simple it doesn't use any operators, but almost all other
programs you write will.
Operator Purpose
+ addition of numbers, concatenation of <trings
+= add and assign numbers, concatenate and assign <trings
. subtraction
.= subtract and assign
> multiplication
>= multiply and assign
? division
?= divide and assign
@ ta+e remainder
@= ta+e remainder and assign
++ increment by one
.. decrement by one
A greater than
A= greater than or e*ual to
B less than
B= less than or e*ual to
C boolean D$T
C= not e*ual to
EE boolean 'DF
GG boolean $6
== boolean e*uals
= assignment
H bitwise D$T
IJ conditional
instanceof type chec+ing
G bitwise $6
G= bitwise $6 and assign
K bitwise L$6
K= bitwise L$6 and assign
E bitwise 'DF
E= bitwise 'DF and assign
AA shift bits right with sign eMtension
AA= shift bits right with sign eMtension and assign
BB shift bits left
BB= shift bits left and assign
AAA unsigned bit shift right
AAA= unsigned bit shift right and assign
White Space
Mallikarjun Page 3 5/18/2014
Java Programming
White space consists mostly of the space character that you produce by hitting the
space bar on your +eyboard and that is commonly used to separate words in sentences.
There are four other white space characters in Java, the hori!ontal tab, the form feed, the
carriage return, and the linefeed. Fepending on your platform, when you hit the return or enter
+ey, you get either a carriage return the /ac", a linefeed ;niM" or both F$<, Windows,
N/<". This produces a hard line brea+ in the source code teMt.
$utside of <tring literals Java treats all white space and runs of white space more than
one white space character in immediate succession" the same. 9t's used to separate to+ens,
and one space is as good as seven spaces, a tab and two carriage returns. :Mactly which
white space characters you use is primarily a result of what's convenient for human beings
reading the code. The compiler doesn't care.
9nside String and character literals the only white space permitted is the space character.
Carriage returns, tabs, line feeds and form feeds must be inserted with special escape
se*uences li+e \r, \t, \f, and \n. ,ou cannot brea+ a <tring across a line li+e thisJ
<tring poem = O/ary had a little lamb
whose fleece was white as snow
and everywhere that /ary went
the lamb was sure to go.OP
9nstead you must use \n and the string concatenation operator, +, li+e thisJ
<tring poem = O/ary had a little lambQnO +
Owhose fleece was white as snowQnO +
Oand everywhere that /ary wentQnO +
Othe lamb was sure to go.OP
Dote that you can brea+ a statement across multiple lines, you %ust can't brea+ a <tring literal.
'lso note that Qn only wor+s on ;niM. ,ou should probably use <ystem.getRropertyOline.separatorO"
instead to return the proper line separator string for the platform your program is running on.
Java does not have all the escape se*uences C has. 1esides those already mentioned it has
only Qb for bac+space, QQ for the bac+slash character itself.
There are also Qu escapes that let you include any ;nicode character.
The proper use of white space in programs
Mallikarjun Page 4 5/18/2014
Java Programming
1lan+ lines to separate bloc+s
;se spaces instead of tabs
Literals
5iterals are pieces of Java source code that mean eMactly what they say. (or instance
OHello WorldCO is a <tring literal and its meaning is the words Hello WorldC
The string OHello WorldCO loo+s li+e it's several thingsP but to the compiler it's %ust one
thing, a <tring. This is similar to how an eMpression li+e -,723,#&) may be seven digits and two
commas but is really %ust one number.
The double *uote mar+s tell you this is a string literal. ' string is an ordered collection
of characters letters, digits, punctuation mar+s, etc.". 'lthough the <tring may have meaning
to a human being reading the code, the computer sees it as no more than a particular set of
letters in a particular order. 9t has no concept of the meaning of the characters. (or instance it
does not +now that OtwoO + OtwoO is Ofour.O 9n fact the computer thin+s that OtwoO + OtwoO is
OtwotwoO
The *uote mar+s show where the string begins and ends. However the *uote mar+s
themselves are not a part of the string. The value of this string is Hello WorldC, not OHello
WorldCO ,ou can change the output of the program by changing Hello World to some other
line of teMt.
' string in a Java program has no concept of italics, bold face, font family or other
formatting. 9t cares only about the characters that compose it. :ven if you're using an editor
li+e DisusWriter that lets you format teMt files, "Hello Worl!" is identical to "Hello World!" as
far as Java is concerned.
char literals are similar to string literals eMcept they're enclosed in single *uotes and must have
eMactly one character. (or eMample 'c' is a char literal that means the letter c.
true and false are boolean literals that mean true and false.
Dumbers can also be literals. 34 is an int literal and it means the number thirty.four. 1! is a
double literal. 4!", #"4E$ 34.) times -0 to the 2th power" and .&#.0 are also double literals.
&)5 is a long literal and it means the number thirty.four. -.8( is a float literal. )8.4f, 34.):2( and
.&#.0( are also float literals.
Mallikarjun Page 5 5/18/2014
Java Programming
"entifiers in Java
Identifiers are the names of variables, methods, classes, pac+ages and interfaces.
;nli+e literals they are not the things themselves, %ust ways of referring to them. 9n the
HelloWorld program, HelloWorld, <tring, args, main and println are identifiers.
9dentifiers must be composed of letters, numbers, the underscore S and the dollar sign
T. 9dentifiers may only begin with a letter, the underscore or a dollar sign.
:ach variable has a name by which it is identified in the program. 9t's a good idea to give
your variables mnemonic names that are closely related to the values they hold. Nariable
names can include any alphabetic character or digit and the underscore S. The main
restriction on the names you can give your variables is that they cannot contain any white
space. ,ou cannot begin a variable name with a number. 9t is important to note that as in C
but not as in (ortran or 1asic, all variable names are case.sensitive. %y&ariable is not the
same as 'y&ariable. There is no limit to the length of a Java variable name. The following are
legal variable namesJ
/yNariable
myvariable
/,N'69'15:
M
i
Smyvariable
Tmyvariable
S7pins
andros
UVWXYZ
$6eilly
ThisSisSanSinsanelySlongSvariableSnameSthatS%ustS+eepsSgoingSandSgoingSandSgoingSandSwellSyo
uSgetStheSideaSTheSlineSbrea+sSarentSreallySpartSofStheSvariableSnameS9tsS%ustSthatSthisSvariableS
nameSisSsoSridiculouslySlongSthatSitSwon'tSfitSonStheSpageS9ScantSimagineSwhySyouSwouldSneedSs
uchSaSlongSvariableSnameSbutSifSyouSdoSyouScanShaveSit
The following are not legal variable namesJ
/y Nariable ?? Contains a space
7pins ?? 1egins with a digit
a+c ?? The plus sign is not an alphanumeric character
testing-.#.& ?? The hyphen is not an alphanumeric character
$'6eilly ?? 'postrophe is not an alphanumeric character
$6eillySES'ssociates ?? ampersand is not an alphanumeric character
Tip: How to Begin a Variable Name with a Number
9f you want to begin a variable name with a digit, prefiM the name you'd li+e to have e.g. 2ball"
with an underscore, e.g. S2ball. ,ou can also use the underscore to act li+e a space in long
variable names.
Mallikarjun Page 6 5/18/2014
Java Programming
#eywors
[eywords are identifiers li+e public, static and class that have a special meaning inside Java
source code and outside of comments and <trings. (our +eywords are used in Hello World,
public, static, void and class.
[eywords are reserved for their intended use and cannot be used by the programmer for
variable or method names.
There are fifty reserved +eywords in Java -.-, 8- in Java -.#, 8# in Java -.), and 8) in Java
8. The forty.eight that are actually used in are listed below. Fon't worry if the purposes of the
+eywords seem a little opa*ue at this point. They will all be eMplained in much greater detail
later.
Keywords Used in Java 1.1
#eywor Purpose
boolean declares a boolean variable or return type
byte declares a byte variable or return type
char declares a character variable or return type
double declares a double variable or return type
float declares a floating point variable or return type
short declares a short integer variable or return type
void declare that a method does not return a value
int declares an integer variable or return type
long declares a long integer variable or return type
while begins a while loop
for begins a for loop
do begins a do while loop
switch tests for the truth of various possible cases
brea+ prematurely eMits a loop
continue prematurely return to the beginning of a loop
case one case in a switch statement
default default action for a switch statement
if eMecute statements if the condition is true
else signals the code to be eMecuted if an if statement is not true
try attempt an operation that may throw an eMception
catch handle an eMception
finally declares a bloc+ of code guaranteed to be eMecuted
class signals the beginning of a class definition
abstract declares that a class or method is abstract
eMtends specifies the class which this class is a subclass of
final
declares that a class may not be subclassed or that a field or method may not be
overridden
implements declares that this class implements the given interface
import permit access to a class or group of classes in a pac+age
instanceof tests whether an ob%ect is an instanceof a class
interface signals the beginning of an interface definition
Mallikarjun Page 7 5/18/2014
Java Programming
native declares that a method is implemented in native code
new allocates a new ob%ect
pac+age defines the pac+age in which this source code file belongs
private declares a method or member variable to be private
protected declares a class, method or member variable to be protected
public declares a class, method or member variable to be public
return returns a value from a method
static declares that a field or a method belongs to a class rather than an ob%ect
super a reference to the parent of the current ob%ect
synchroni!ed 9ndicates that a section of code is not thread.safe
this a reference to the current ob%ect
throw throw an eMception
throws declares the eMceptions thrown by a method
transient This field should not be seriali!ed
volatile Warns the compiler that a variable changes asynchronously
Two other +eywords, const and goto, are reserved by Java but are not actually implemented.
This allows compilers to produce better error messages if these common C++ +eywords are
improperly used in a Java program.
Java -.# adds the strictfp +eyword to declare that a method or class must be run with eMact
9::: 38) semantics.
Java -.) adds the assert +eyword to specify assertions.
Java 8 adds assert and enu'.
true and false appear to be missing from this list. 9n fact, they are not +eywords but rather
boolean literals. ,ou still can't use them as a variable name though.
Mallikarjun Page 8 5/18/2014
Java Programming
Separators in Java
<eparators help define the structure of a program. The separators used in HelloWorld are
parentheses, ( *, braces, + ,, the period, , and the semicolon, -. The table lists the siM Java
separators nine if you count opening and closing separators as two".
Separator
Purpose
"
:ncloses arguments in method definitions and callingP ad%usts precedence in
arithmetic eMpressionsP surrounds cast types and delimits test eMpressions in flow
control statements
\ ] defines bloc+s of code and automatically initiali!es arrays
^ _ declares array types and dereferences array values
P terminates statements
,
separates successive identifiers in variable declarationsP chains statements in the
test, eMpression of a for loop
.
<elects a field or method from an ob%ectP separates pac+age names from sub.
pac+age and class names
J ;sed after loop labels
$ition of "ntegers in Java
class 'dd9nts \

public static void main <tring args^_" \

int i = -P
int % = #P
<ystem.out.printlnOi is O + i"P
<ystem.out.printlnO% is O + %"P

int + = i + %P
<ystem.out.printlnOi + % is O + +"P
+ = i . %P
<ystem.out.printlnOi . % is O + +"P
]
]
Here's what happens when you run 'dd9ntsJ
T %avac 'dd9nts.%ava
T %ava 'dd9nts
i is -
% is #
i + % is &
i . % is .-
Mallikarjun Page 9 5/18/2014
Java Programming
$ition of ou%les in Java
Foubles are treated much the same way, but now you get to use decimal points in the
numbers. This is a similar program that does addition and subtraction on doubles.
class 'ddFoubles \
public static void main <tring args^_" \
double M = 3.8P
double y = 8.)P
<ystem.out.printlnOM is O + M"P
<ystem.out.printlnOy is O + y"P

double ! = M + yP
<ystem.out.printlnOM + y is O + !"P

! = M . yP
<ystem.out.printlnOM . y is O + !"P
]
]
Here's the resultJ
@ %avac 'ddFoubles.%ava
@ %ava 'ddFoubles
M is 3.8
y is 8.)
M + y is -#.7
M . y is #.0777777777777774
Mallikarjun Page 10 5/18/2014
Java Programming
&ultiplication an ivision in Java
$f course Java can also do multiplication and division. <ince most +eyboards don't have the
times and division symbols you learned in grammar school, Java uses . to mean
multiplication and / to mean division. The syntaM is straightforward as you see below.
class /ultiplyFivide \
public static void main <tring args^_" \
int i = -0P
int % = #P
<ystem.out.printlnOi is O + i"P
<ystem.out.printlnO% is O + %"P

int + = i?%P
<ystem.out.printlnOi?% is O + +"P
+ = i > %P
<ystem.out.printlnOi > % is O + +"P
]
]
Here's the resultJ
@ %avac /ultiplyFivide.%ava
@ %ava /ultiplyFivide
i is -0
% is #
i?% is 8
i > % is #0
(loats and doubles are multiplied and divided in eMactly the same way. When faced with an
ineMact integer division, Java rounds the result down. (or instance dividing -0 by & produces
&.
Mallikarjun Page 11 5/18/2014
Java Programming
'ne(pecte )uotients
#?& = 0
&?# = -
-?0 = 'rithmetic:Mception
0?0 = 'rithmetic:Mception
-.0?0.0 = 9nf
-.0?0 = 9nf
0.0?0.0 = DaD
.-.0?0.0 = .9nf
9nf + - = 9nf
9nf + 9nf = 9nf
9nf . 9nf = DaD
9nf?9nf = DaD
DaD + anything = DaD
DaD . anything = DaD
DaD > anything = DaD
DaD ? anything = DaD
DaD B DaD is false
DaD A DaD is false
DaD B= DaD is false
DaD A= DaD is false
DaD == DaD is false
DaD C= DaD is true
Mallikarjun Page 12 5/18/2014
Java Programming
The *emainer or &oulus Operator in
Java
Java has one important arithmetical operator you may not be familiar with, 0, also
+nown as the modulus or remainder operator. The 0 operator returns the remainder of two
numbers. (or instance 11 0 3 is - because -0 divided by & leaves a remainder of -. ,ou can
use 0 %ust as you might use any other more common operator li+e + or 2.
class 6emainder \
public static void main <tring args^_" \
int i = -0P
int % = &P
<ystem.out.printlnOi is O + i"P
<ystem.out.printlnO% is O + %"P

int + = i @ %P
<ystem.out.printlnOi@% is O + +"P
]
]
Here's the outputJ
@ %avac 6emainder.%ava
@ %ava 6emainder
i is -0
% is &
i@% is -
Rerhaps surprisingly the remainder operator can be used with floating point values as
well. 9t's surprising because you don't normally thin+ of real number division as producing
remainders. However there are rare times when it's useful to as+ eMactly how many times
does -.8 go into 8.8 and what's left overI The answer is that -.8 goes into 8.8 three times
with one left over, and it's that one which is the result of 8.8 @ -.8 in Java.
Mallikarjun Page 13 5/18/2014
Java Programming
Operator Preceence in Java
9t's possible to combine multiple arithmetic eMpressions in one statement. (or instance
the following line adds the numbers one through fiveJ
int m = - + # + & + ) + 8P
' slightly more interesting eMampleJ the following program calculates the energy e*uivalent of
an electron using :instein's famous formula : = mc
#
.
class mc# \
public static void main <tring args^_" \
double mass = 7.-074:.#8P
double c = #.772:2P
double : = mass > c > cP
<ystem.out.println:"P
]
]
Here's the outputJ
T %avac mc#.%ava
T %ava mc#
2.-233-e.02
This is all very obvious. However if you use different operators on the same line it's not
always clear what the result will be. (or instance consider the following code fragmentJ
int n = - . # > & . ) + 8P
9s n e*ual to .#I ,ou might thin+ so if you %ust calculate from left to right. However if you
compile this in a program and print out the result you'll find that Java thin+s n is e*ual to .).
Java got that number because it performs all multiplications before it performs any additions
or subtractions. 9f you li+e you can thin+ of the calculation Java did as beingJ
int n = - . # > &" . ) + 8P
This is an issue of order of evaluation. Within the limited number of operators you've learned
so far here is how Java calculatesJ
-. >, ?, @ Fo all multiplications, divisions and remainders from left to right.
#. +, . Fo additions and subtractions from left to right.
&. = 'ssign the right.hand side to the left.hand side
Mallikarjun Page 14 5/18/2014
Java Programming
Parentheses in Java
<ometimes the default order of evaluation isn't what you want. (or instance, the
formula to change a (ahrenheit temperature to a Celsius temperature is C = 8?7" ( . &#"
where C is degrees Celsius and ( is degrees (ahrenheit. ,ou must subtract &# from the
(ahrenheit temperature before you multiply by 8?7, not after. ,ou can use parentheses to
ad%ust the order much as they are used in the above formula. The neMt program prints a table
showing the conversions from (ahrenheit and Celsius between !ero and three hundred
degrees (ahrenheit every twenty degrees.
?? Rrint a (ahrenheit to Celsius table
class (ahrToCelsius \
public static void main <tring args^_" \

?? lower limit of temperature table
double lower = 0.0P
?? upper limit of temperature table
double upper = &00.0P
?? step si!e
double step = #0.0P

double fahr = lowerP
while fahr B= upper" \
double celsius = 8.0 ? 7.0" > fahr.&#.0"P
<ystem.out.printlnfahr + O O + celsius"P
fahr = fahr + stepP
]
]
]
Mallikarjun Page 15 5/18/2014
Java Programming
Parentheses in Java
's usual here's the outputJ
@ %avac (ahrToCelsius.%ava
@ %ava (ahrToCelsius
0 .-3.3332
#0 .4.44443
)0 ).)))))
40 -8.8884
20 #4.4443
-00 &3.3332
-#0 )2.2227
-)0 40
-40 3-.----
-20 2#.####
#00 7&.&&&&
##0 -0).)))
#)0 --8.884
#40 -#4.443
#20 -&3.332
&00 -)2.227
This program is a little more involved than the previous eMamples. /ostly it's stuff you've seen
before though so a line by line analysis isn't necessary. The line to be concerned with is
celsius = 8.0 ? 7.0" > fahr.&#.0"P
This is a virtual translation of the formula C = 8?7"( . &#" with the single change that a > was
added because Java does not implicitly multiply items in parentheses. The parentheses are
used %ust as they are in regular algebra, to ad%ust the precedence of terms in a formula. 9n fact
the precedence of operations that use the basic arithmetic operators +, ., >, ?" is eMactly the
same as you learned in high school algebra.
6emember, you can always use parentheses to change the order of evaluation. :verything
inside the parentheses will be calculated before anything outside of the parentheses is
calculated. 9f you're in doubt it never hurts to put in eMtra parentheses to clear up the order in
which terms will be evaluated.
&i(ing Data Types
Mallikarjun Page 16 5/18/2014
Java Programming
's well as combining different operations, you can miM and match different numeric
data types on the same line. The program below uses both ints and doubles, for eMample.
class 9nt'ndFouble \
public static void main <tring args^_" \
int i = -0P
double M = #.8P
double +P
<ystem.out.printlnOi is O + i"P
<ystem.out.printlnOM is O + M"P

+ = i + MP
<ystem.out.printlnOi + M is O + +"P
+ = i > MP
<ystem.out.printlnOi > M is O + +"P
+ = i . MP
<ystem.out.printlnOi . M is O + +"P
+ = M . iP
<ystem.out.printlnOM . i is O + +"P
+ = i ? MP
<ystem.out.printlnOi ? M is O + +"P
+ = M ? iP
<ystem.out.printlnOM ? i is O + +"P
]
]
This program produces the following outputJ
@ %ava 9nt'ndFouble
i is -0
M is #.8
i + M is -#.8
i > M is #8
i . M is 3.8
M . i is .3.8
i ? M is )
M ? i is 0.#8
@
Mallikarjun Page 17 5/18/2014
Java Programming
&i(ing Data Types
$rder can ma+e a difference when data types are miMed. (or eMample,
- ? # > &.8 = 0.0
&.8 > - ? # = -.38
&.8 ? # = -.38
,ou cannot assume that the usual mathematical laws of commutativity apply when miMing
data types, especially integer and floating point types.
-.0 ? # > &.8 = -.38
&.8 > -.0 ? # = -.38
- ? #.0 > &.8 = -.38
&.8 > -.0 ? #.0 = -.38
$rithmetic Promotion an +inary
Operations
'n int divided by an int is an int, and a double divided by a double is a double, but what
about an int divided by a double or a double divided by an intI When doing arithmetic on unli+e
types Java tends to widen the types involved so as to avoid losing information. 'fter all & >
8).#:-2 will be a perfectly valid double but much too big for any int.
The basic rule is that if either of the variables in a binary operation addition, multiplication,
subtraction, addition, remainder" are doubles then Java treats both values as doubles. 9f
neither value is a double but one is a float, then Java treats both values as floats. 9f neither is a
float or a double but one is a long, then Java treats both values as longs. (inally if there are no
doubles, floats or longs, then Java treats both values as an int, even if there aren't any ints in
the e*uation. Therefore the result will be a double, float, long or int depending on the types of the
arguments.
Mallikarjun Page 18 5/18/2014
Java Programming
$rithmetic Promotion, $ssignments, an
-asting
9n an assignment statement, i.e. if there's an e*uals sign, Java compares the type of
the left hand side to the final type of the right hand side. 9t won't change the type of the left
hand side, but it will chec+ to ma+e sure that the value it has double, float, int or long" on the
right hand side can fit in the type on the left hand side. 'nything can fit in a double. 'nything
eMcept a double can fit in a float. 'ny integral type can fit in a long, but a float or a double can't,
and ints, shorts, and bytes can fit inside ints. 9f the right hand side can fit inside the left hand
side, the assignment ta+es place with no further ado.
'ssigning long values to int variables or double values to float variables can be e*ually
troublesome. 9n fact it's so troublesome the compiler won't let you do it unless you tell it you
really mean it with a cast. When it's necessary to force a value into a particular type, use a
cast. To cast a variable or a literal or an eMpression to a different data type %ust precede it with
the type in parentheses. (or instanceJ
int i = int" 7.0?).0"P
' cast lets the compiler +now that you're serious about the conversion you plan to ma+e.
When a value is cast down before assignment, series of operations ta+es place to chop the
right hand side down to si!e. (or a conversion between a floating point number and an int or
a long, the fractional part of the floating point number is truncated rounded toward !ero". This
produces an integer. 9f the integer is small enough to fit in the left hand side, the assignment
is completed. $n the other hand if the number is too large, then the integer is set to the
largest possible value of its type. 9f the floating point number is too small the integer is set to
the smallest possible value of its type.
This can be a nasty bug in your code. 9t can also be hard to find since everything may wor+
perfectly 77 times out of a hundred and only on rare occasions will the rounding become a
problem. However when it does there will be no warning or error message. ,ou need to be
very careful when assigning floating point values to integer types.
Java's Primitive Data Types
boolean
-.bit. /ay ta+e on the values true and false only.
Mallikarjun Page 19 5/18/2014
Java Programming
true and false are defined constants of the language and are not the same as True and
False, TRUE and FALSE, !ero and non!ero, - and 0 or any other numeric value.
1ooleans may not be cast into any other type of variable nor may any other variable be
cast into a boolean.
byte
- signed byte two's complement". Covers values from .-#2 to -#3.
short
# bytes, signed two's complement", .&#,342 to &#,343
int
) bytes, signed two's complement". .#,-)3,)2&,4)2 to #,-)3,)2&,4)3. 5i+e all numeric
types ints may be cast into other numeric types byte, short, long, float, double". When
lossy casts are done e.g. int to byte" the conversion is done modulo the length of the
smaller type.
long
2 bytes signed two's complement". 6anges from .7,##&,&3#,0&4,28),338,202 to
+7,##&,&3#,0&4,28),338,203.
float
) bytes, 9::: 38). Covers a range from -.)0-#72)4)&#)2-303e.)8 to
&.)0#2#&)44&28#2240e+&2 positive or negative".
5i+e all numeric types floats may be cast into other numeric types byte, short, long,
int, double". When lossy casts to integer types are done e.g. float to short" the
fractional part is truncated and the conversion is done modulo the length of the smaller
type.
double
2 bytes 9::: 38). Covers a range from ).7)0484)82)-#)48))e.&#)d to
-.37347&-&)24#&-830e+&02d positive or negative".
char
# bytes, unsigned, ;nicode, 0 to 48,8&8
Chars are not the same as bytes, ints, shorts or <trings.
-onverting Strings to .um%ers
Mallikarjun Page 20 5/18/2014
Java Programming
When processing user input it is often necessary to convert a String that the user
enters into an int. The syntaM is straightforward. 9t re*uires using the static
3nteger4alue5f(String s* and int&alue(* methods from the 6a4alang3nteger class. To
convert the String 7887 into the int 88 you would write
int i = 9nteger.value$fO##O".intNalue"P
Foubles, floats and longs are converted similarly. To convert a <tring li+e O##O into the long
value ## you would write
long l = 5ong.value$fO##O".longNalue"P
To convert 788!7 into a float or a double you would writeJ
double M = Fouble.value$fO##.8O".doubleNalue"P
float y = (loat.value$fO##.8O".floatNalue"P
The various value$f" methods are relatively intelligent and can handle plus and minus signs,
eMponents, and most other common number formats. However if you pass one something
completely non.numeric li+e Opretty in pin+,O it will throw a Dumber(ormat:Mception. ,ou haven't
learned how to handle eMceptions yet, so try to avoid passing theses methods non.numeric
data.
,ou can now rewrite the : = mc# program to accept the mass in +ilograms as user input from
the command line. /any of the eMercises will be similar.
class :nergy \
public static void main <tring args^_" \
double c = #.772:2P ?? meters?second
double mass = Fouble.value$fargs^0_".doubleNalue"P
double : = mass > c > cP
<ystem.out.println: + O JoulesO"P
]
]
Here's the outputJ
T %avac :nergy.%ava
T %ava :nergy 0.0)84
).0728&e+-8 Joules
Mallikarjun Page 21 5/18/2014
Java Programming
The char ata type in Java
' char is a single character, that is a letter, a digit, a punctuation mar+, a tab, a space or
something similar. ' char literal is a single one character enclosed in single *uote mar+s li+e
this
char myCharacter = 'g'P
<ome characters are hard to type. (or these Java provides escape se*uences. This is a
bac+slash followed by an alphanumeric code. (or instance '\n' is the newline character. '\t'
is the tab character. '\\' is the bac+slash itself. The following escape se*uences are definedJ
Qb bac+space
Qt tab
Qn linefeed
Qf formfeed
Qr carriage return
QO double *uote, O
Q' single *uote, '
QQ bac+slash, Q
The double *uote escape se*uence is used mainly inside strings where it would otherwise
terminate the string. (or instance
<ystem.out.printlnO'nd then Jim said, QOWho's at the doorIQOO"P
9t isn't necessary to escape the double *uote inside single *uotes. The following line is legal
in Java
char double*uote = 'O'P
Mallikarjun Page 22 5/18/2014
Java Programming
The double quote escape sequence is used mainly
inside strings where it would to Java Flow
Control
if
else
else if
while
for
do while
switch case
brea+
continue
goto is a reserved word. 9t is not implemented.
We'll tal+ about eMception handling later.
herwise terminate the string. (or instance
<ystem.out.printlnO'nd then Jim said, QOWho's at the doorIQOO"P
9t isn't necessary to escape the double *uote inside single *uotes. The following
line is legal in Java
char double*uote = 'O'P
The if statement in Java
Mallikarjun Page 23 5/18/2014
Java Programming
All bu !e mo" rivial #om$uer $rogram" nee% o make %e#i"ion". &!e' e" a #on%iion an% o$erae
%i((erenl' ba"e% on !e ou#ome o( !e e". &!i" i" )uie #ommon in real li(e. *or in"an#e 'ou "i#k
'our !an% ou !e +in%o+ o e" i( i," raining. -( i i" raining !en 'ou ake an umbrella +i! 'ou. -( i
i"n, raining !en 'ou %on,.
All $rogramming language" !ave "ome (orm o( an if "aemen !a e"" #on%iion". -n !e $reviou"
#o%e 'ou "!oul% !ave e"e% +!e!er !ere a#uall' +ere #omman% line argumen" be(ore 'ou rie% o
u"e !em.
Arra'" !ave leng!" an% 'ou #an a##e"" !a leng! b' re(eren#ing !e variable arrayna'elength
.ou e" !e leng! o( !e args arra' a" (ollo+".
// This is the 9ello :rogra' in ;a4a
class 9ello +
:ublic static 4oid 'ain (String args<=* +

if (argslength > 1* +
Syste'out:rintln(79ello 7 + args<1=*-
,
,
,
Syste'out:rintln(args<1=* +a" +ra$$e% in a #on%iional e"/ if (argslength > 1* + ,.
&!e #o%e in"i%e !e bra#e"/ Syste'out:rintln(args<1=*/ no+ ge" e0e#ue% i( an% onl' i( !e
leng! o( !e arg" arra' i" greaer !an 1ero.
&!e argumen" o a #on%iional "aemen like if mu" be a boolean value/ !a i" "ome!ing !a
evaluae" o rue or (al"e. -neger" are no $ermi""ible.
-n Java numeri#al greaer !an an% le""er !an e"" are %one +i! !e > an% ? o$eraor" re"$e#ivel'.
.ou #an e" +!e!er a number i" le"" !an or e)ual o or greaer !an or e)ual o ano!er number +i!
!e ?@ an% >@ o$eraor".
Testing for Equality
Mallikarjun Page 24 5/18/2014
Java Programming
&e"ing (or e)uali' i" a lile ri#kier. .ou +oul% e0$e# o e" i( +o number" are e)ual b' u"ing !e 2
"ign. 3o+ever !e 2 "ign !a" alrea%' been u"e% a" an a""ignmen o$eraor !a "e" !e value o( a
variable. &!ere(ore a ne+ "'mbol i" nee%e% o e" (or e)uali'. Java borro+" 4," %ouble e)ual" "ign/
@@/ (or !i" $ur$o"e.
-," no un#ommon (or even e0$erien#e% $rogrammer" o +rie @@ +!en !e' mean @ or vi#e ver"a. -n
(a# !i" i" a ver' #ommon #au"e o( error" in 4 $rogram". *orunael' in Java/ 'ou are no allo+e% o
u"e @@ an% @ in !e "ame $la#e". &!ere(ore !e #om$iler #an #a#! 'our mi"ake an% make 'ou (i0 i
be(ore 'ou #an run !e $rogram.
3o+ever !ere i" one +a' 'ou #an "ill ge ino rouble5
boolean b @ true-
if (b @ false* +
Syste'out:rintln(7b is false7*-
,
&o avoi% !i"/ "ome $rogrammer" ge in !e !abi o( +riing #on%iion e"" like !i"5
boolean b @ true-
if (false @ b* +
Syste'out:rintln(7b is false7*-
,
6in#e 'ou #an, a""ign o a lieral/ !i" #au"e" a #om$iler error i( 'ou mi"u"e !e @ "ign +!en 'ou mean
o +rie @@.
The else statement in Java
// This is the 9ello :rogra' in ;a4a
class 9ello +
:ublic static 4oid 'ain (String args<=* +

if (argslength > 1* +
Syste'out:rintln(79ello 7 + args<1=*-
,
else +
Syste'out:rintln(79ello Ahoe4er you are7*-
,
,
,
Mallikarjun Page 25 5/18/2014
Java Programming
Else If
B3f "aemen" are no limie% o +o #a"e". .ou #an #ombine an else an% an if o make an
else if an% e" a +!ole range o( muuall' e0#lu"ive $o""ibiliie". *or in"an#e/ !ere," a ver"ion o( !e
3ello $rogram !a !an%le" u$ o (our name" on !e #omman% line5
// This is the 9ello :rogra' in ;a4a
class 9ello +
:ublic static 4oid 'ain (String args<=* +

if (argslength @@ 1* +
Syste'out:rintln(79ello Ahoe4er you are7*-
,
else if (argslength @@ 1* +
Syste'out:rintln(79ello 7 + args<1=*-
,
else if (argslength @@ 8* +
Syste'out:rintln(79ello 7 + args<1= + 7 7 + args<1=*-
,
else if (argslength @@ 3* +
Syste'out:rintln(79ello 7 + args<1= + 7 7 + args<1= + 7 7 + args<8=*-
,
else if (argslength @@ 4* +
Syste'out:rintln(79ello 7 + args<1= +
7 7 + args<1= + 7 7 args<8= + 7 7 + args<3=*-
,
else +
Syste'out:rintln(79ello 7 + args<1= + 7 7 + args<1= + 7 7 args<8=
+ 7 7 + args<3= + 7 and all the restC7*-
,
,
,
.ou #an "ee !a !i" ge" mig!' #om$li#ae% mig!' )ui#kl'. 7o e0$erien#e% Java $rogrammer +oul%
+rie #o%e like !i". &!ere i" a beer "oluion an% 'ou,ll e0$lore i in !e ne0 "e#ion.
The while loop in Java
// This is the 9ello :rogra' in ;a4a

class 9ello +
Mallikarjun Page 26 5/18/2014
Java Programming

:ublic static 4oid 'ain (String args<=* +

Syste'out:rint(79ello 7*- // Say 9ello
int i @ 1- // Declare and initialiEe loo: counter
Ahile (i ? argslength* + // Test and Loo:
Syste'out:rint(args<i=*-
Syste'out:rint(7 7*-
i @ i + 1- // 3ncre'ent Loo: Founter
,
Syste'out:rintln(*- // Finish the line
,

,
The for loop in Java
// This is the Hello program in Java
class 9ello +
:ublic static 4oid 'ain (String args<=* +

Syste'out:rint(79ello 7*- // Say 9ello
for (int i @ 1- i ? argslength- i @ i + 1* + // Test and Loo:
Syste'out:rint(args<i=*-
Syste'out:rint(7 7*-
,
Syste'out:rintln(*- // Finish the line
,
,
ultiple !nitiali"ers and !n#rementers
6omeime" i," ne#e""ar' o iniiali1e "everal variable" be(ore beginning a (or loo$. 6imilarl' 'ou ma'
+an o in#remen more !an one variable. Java le" 'ou %o !i" b' $la#ing a #omma be+een !e
%i((eren iniiali1er" an% in#remener" like !i"5
for (int i @ 1G 6 @ 111- i ? 111- i @ i+1G 6 @ 621* +
Syste'out:rintln(i + 6*-
,
.ou #an,/ !o+ever/ in#lu%e muli$le e" #on%iion"/ a lea" no +i! #omma". &!e (ollo+ing line i"
illegal an% +ill generae a #om$iler error.
for (int i @ 1G 6 @ 111- i ?@ 111G 6 > 1- i @ i21G 6 @ 621* +
To include 'ulti:le tests you need to use the boolean logic o:erators HH
and II Ahich Aill be discussed later
The do while loop in Java
// This is the 9ello :rogra' in ;a4a
Mallikarjun Page 27 5/18/2014
Java Programming

class 9ello +

:ublic static 4oid 'ain (String args<=* +

int i @ 21-
do +
if (i @@ 21* Syste'out:rint(79ello 7*-
else +
Syste'out:rint(args<i=*-
Syste'out:rint(7 7*-
,
i @ i + 1-
, Ahile (i ? argslength*-
Syste'out:rintln(*- // Finish the line
,

,
Booleans
8oolean" are name% a(er 9eorge 8oole/ a nineeen! #enur' logi#ian. :a#! boolean variable !a" one
o( +o value"/ rue or (al"e. &!e"e are no !e "ame a" !e 6ring" ;rue; an% ;(al"e;. &!e' are no !e
"ame a" an' numeri# value like 1 or 0. &!e' are "im$l' rue an% (al"e. 8oolean" are no number"< !e'
are no 6ring". &!e' are "im$l' boolean".
8oolean variable" are %e#lare% ju" like an' o!er variable.
boolean test1 @ true-
boolean test8 @ false-
7oe !a rue an% (al"e are re"erve% +or%" in Java. &!e"e are #alle% !e 8oolean lieral". &!e' are #a"e
"en"iive. &rue +i! a #a$ial & i" no !e "ame a" rue +i! a lile . &!e "ame i" rue o( *al"e an% (al"e.
Relational perators
Mallikarjun Page 28 5/18/2014
Java Programming
Java !a" "i0 relaional o$eraor" !a #om$are +o number" an% reurn a boolean value. &!e relaional
o$eraor" are ?/ >/ ?@/ >@/ @@/ an% C@.
3ere are "ome #o%e "ni$$e" "!o+ing !e relaional o$eraor".
boolean test1 @ 1 ? 8- // True 5ne is less that tAo
boolean test8 @ 1 > 8- // False 5ne is not greater than tAo
boolean test3 @ 3! C@ 1- // True 5ne does not eJual 3!
boolean test4 @ 1#.3! >@ "#1 2 48- //True !K! is greater than !
boolean test! @ K$.!4 ?@ "!4- // True !8K8 is less than "!4
boolean test" @ ".4 @@ 3.$- // True 84 eJuals 84
boolean test# @ ".4 ?@ 3.$- // True 84 is less than or eJual to 84
boolean test$ @ ".4 ? 3.$- // False 84 is not less than 84
&!i"/ !o+ever/ i" an unu"ual u"e o( boolean". Almo" all u"e o( boolean" in $ra#i#e #ome" in
#on%iional "aemen" an% loo$ e"". .ou,ve alrea%' "een "everal e0am$le" o( !i". :arlier 'ou "a+
!i"
if (argslength > 1* +
Syste'out:rintln(79ello 7 + args<1=*-
,
argslength > 1 is a boolean 4alue 3n other Aords it is either true or it is
false Lou could Arite
boolean test @ argslength > 1-
if (test* +
Syste'out:rintln(79ello 7 + args<1=*-
,
in"ea%. 3o+ever in "im$le "iuaion" like !i" !e original a$$roa#! i" #u"omar'. 6imilarl' !e
#on%iion e" in a Ahile loo$ i" a boolean. =!en 'ou +rie Ahile (i ? argslength* !e i ?
argslength i" a boolean.
Relational perator !recedence
Mallikarjun Page 29 5/18/2014
M ? y
>e"" !an &rue i( 0 i" le"" !an '/ o!er+i"e (al"e.
M > y
9reaer !an &rue i( 0 i" greaer !an '/ o!er+i"e (al"e.
M ?@ y
>e"" !an or e)ual o &rue i( 0 i" le"" !an or e)ual o '/ o!er+i"e (al"e.
M >@ y
9reaer !an or e)ual o &rue i( 0 i" greaer !an or e)ual o '/ o!er+i"e (al"e.
M @@ y
:)ual &rue i( 0 e)ual" '/ o!er+i"e (al"e.
M C@ y
7o :)ual &rue i( 0 i" no e)ual o '/ o!er+i"e (al"e.
Java Programming
=!enever a ne+ o$eraor i" inro%u#e% 'ou !ave o a"k 'our"el( +!ere i (i" in !e $re#e%en#e ree. -(
'ou look ba#k a !e e0am$le in !e la" "e#ion/ 'ou,ll noi#e !a i +a" im$li#il' a""ume% !a !e
ari!mei# +a" %one be(ore !e #om$ari"on. ?!er+i"e/ (or in"an#e
boolean test$ @ ".4 ? 3.$- // False 84 is not less than 84
4 @ 3 reurn" (al"e +!i#! +oul% !en be muli$lie% b' "i0 an% eig! +!i#! +oul% generae a #om$ile
ime error be#au"e 'ou #an, muli$l' boolean". Aelaional o$eraor" are evaluae% a(er ari!mei#
o$eraor" an% be(ore !e a""ignmen o$eraor. 22 an% B2 !ave "lig!l' lo+er $re#e%en#e" !an @/ C/ @2
an% C2. 3ere," !e revi"e% or%er5
1. D/ // E Fo all muli$li#aion"/ %ivi"ion" an% remain%er" (rom le( o rig!.
2. G/ H 7e0 %o a%%iion" an% "ubra#ion" (rom le( o rig!.
3. @/ C/ C2/ @2 &!en an' #om$ari"on" (or relaive "i1e.
4. 22/ B2 &!en %o an' #om$ari"on" (or e)uali' an% ine)uali'
5. 2 *inall' a""ign !e rig!H!an% "i%e o !e le(H!an% "i%e
*or e0am$le/
boolean b1 @ # > 3 @@ true-
boolean b8 @ true @@ # > 3- b @ # > 3-
Testing b"ects for Equality
@/ C/ @2 an% C2 #an onl' be u"e% +i! number" an% #!ara#er". &!e' #anno be u"e% +i! 6ring"/
boolean"/ arra'" or o!er #om$oun% '$e" "in#e !ere," no +ellH%e(ine% noion o( or%er (or !e"e
obje#". -" rue greaer !an (al"eI -" ;M' onl' regre i" !a - !ave bu one li(e o give (or m' #ounr';
greaer !an ;- !ave a %ream;I
:)uali' i" a lile ea"ier o e" !o+ever. true i" e)ual o true an% true i" no e)ual o false.
6imilarl' ;M' onl' regre i" !a - !ave bu one li(e o give (or m' #ounr'; i" no e)ual o ;- !ave a
%ream.; 3o+ever 'ou mig! be "ur$ri"e% i( 'ou ran !i" $rogram5
class ;acNAnd;ill +
:ublic static 4oid 'ain(String args<=* +
String s1 @ neA String(7;acN Aent u: the hill7*-
String s8 @ neA String(7;acN Aent u: the hill7*-
if ( s1 @@ s8 * +
Syste'out:rintln(7The strings are the sa'e7*-
,
else if ( s1 C@ s8 * +
Syste'out:rintln(7The strings are not the sa'e7*-
,
,,
&!e re"ul i" The strings are not the sa'e
Testing for Equality with equals#$
Mallikarjun Page 30 5/18/2014
Java Programming
&!a," no +!a 'ou e0$e#e%. &o #om$are "ring" or an' o!er kin% o( obje# 'ou nee% o u"e !e
eJuals(5b6ect o* me!o% (rom 6a4alangString. 8elo+ i" a #orre#e% ver"ion !a +ork" a"
e0$e#e%. &!e rea"on" (or !i" o%% be!avior go (airl' %ee$ ino Java an% !e naure o( obje# %aa '$e"
like "ring".
class ;acNAnd;ill +
:ublic static 4oid 'ain(String args<=* +
String s1 @ neA String(7;acN Aent u: the hill7*-
String s8 @ neA String(7;acN Aent u: the hill7*-
if ( s1eJuals(s8* * +
Syste'out:rintln(7The strings are the sa'e7*-
,
else +
Syste'out:rintln(7The strings are not the sa'e7*-
,
,
,
Brea%
A breaN "aemen e0i" a loo$ be(ore an enr' #on%iion (ail". *or e0am$le/ in !i" variaion on !e
FountOheat $rogram an error me""age i" $rine%/ an% 'ou break ou o( !e for loo$ i( 6 be#ome"
negaive.
class FountOheat +
:ublic static 4oid 'ain (String args<=* +

int total @ 1-
for (int sJuare@1G grains @ 1- sJuare ?@ "4- sJuare++* +
grains .@ 8-
if (grains ?@ 1* +
Syste'out:rintln(7ErrorP 54erfloA7*-
breaN-
,
total +@ grains-
Syste'out:rint(total + 7\t 7*-
if (sJuare 0 4 @@ 1* Syste'out:rintln(*-
,
Syste'out:rintln(7All doneC7*-
,
,
3ere," !e ou$u5
0 6a4ac FountOheat6a4a
0 6a4a FountOheat
Mallikarjun Page 31 5/18/2014
Java Programming
8 " 14 31
"8 18" 8!4 !11
1188 814" 41K4 $1K1
1"3$8 38#"" "!!34 1311#1
8"8148 !848$" 114$!#4 81K#1!1
41K4318 $3$$"1" 1"###814 33!!4431
"#11$$"8 13481##8" 8"$43!4!4 !3"$#1K11
11#3#41$88 814#4$3"4" ErrorP 54erfloA
All doneC
&!e mo" #ommon u"e o( breaN i" in sAitch "aemen".
Continue
- i" "omeime" ne#e""ar' o e0i (rom !e mi%%le o( a loo$. 6omeime" 'ou,ll +an o "ar over a !e
o$ o( !e loo$. 6omeime" 'ou,ll +an o leave !e loo$ #om$leel'. *or !e"e $ur$o"e" Java $rovi%e"
!e breaN an% continue "aemen".
A continue "aemen reurn" o !e beginning o( !e innermo" en#lo"ing loo$ +i!ou #om$leing !e
re" o( !e "aemen" in !e bo%' o( !e loo$. -( 'ou,re in a for loo$/ !e #ouner i" in#remene%. *or
e0am$le !i" #o%e (ragmen "ki$" even elemen" o( an arra'
for (int i @ 1- i ? 'length- i++* +
if ('<i= 0 8 @@ 1* continue-
// :rocess odd ele'ents
,
&!e continue "aemen i" rarel' u"e% in $ra#i#e/ $er!a$" be#au"e mo" o( !e in"an#e" +!ere i,"
u"e(ul !ave "im$ler im$lemenaion". *or in"an#e/ !e above (ragmen #oul% e)uall' +ell !ave been
+rien a"
for (int i @ 1- i ? 'length- i++* +
if ('<i= 0 8 C@ 1* +
// :rocess odd ele'ents
,
,
&!ere are onl' "even u"e" o( continue in !e enire Java 1.0.1 "our#e #o%e (or !e java $a#kage".
&abeled &oops
Mallikarjun Page 32 5/18/2014
Java Programming
7ormall' in"i%e ne"e% loo$" breaN an% continue e0i !e innermo" en#lo"ing loo$. *or e0am$le
#on"i%er !e (ollo+ing loo$".
for (int i@1- i ? 11- i++* +
for (int 6@1- 6 ? 4- 6++* +
if (6 @@ 8* breaN-
Syste'out:rintln(i + 7G 7 + 6*-
,
,
This code frag'ent :rints
1G 1
8G 1
3G 1
4G 1
!G 1
"G 1
#G 1
$G 1
KG 1
be#au"e 'ou break ou o( !e innermo" loo$ +!en j i" +o. 3o+ever !e ouermo" loo$ #oninue".
&o break ou o( bo! loo$"/ label !e ouermo" loo$ an% in%i#ae !a label in !e break "aemen like
!i"5
iloo:P for (int i@1- i ? 3- i++* +
for (int 6@1- 6 ? 4- 6++* +
if (6 @@ 8* breaN iloo:-
Syste'out:rintln(i + 7G 7 + 6*-
,
,
&!i" #o%e (ragmen $rin"
1G 1
an% !en "o$" be#au"e 6 i" +o an% !e ouermo" loo$ i" e0ie%.
The switch statement in Java
6+i#! "aemen" are "!or!an%" (or a #erain kin% o( if "aemen. - i" no un#ommon o "ee a "a#k
o( if "aemen" all relae o !e "ame )uani' like !i"5
if (M @@ 1* doSo'ething1(*-
else if (M @@ 1* doSo'ething1(*-
else if (M @@ 8* doSo'ething8(*-
else if (M @@ 3* doSo'ething3(*-
else if (M @@ 4* doSo'ething4(*-
else doSo'ethingElse(*-
Java !a" a "!or!an% (or !e"e '$e" o( muli$le if "aemen"/ !e sAitch2case "aemen. 3ere," !o+
'ou,% +rie !e above u"ing a sAitch2case5
Mallikarjun Page 33 5/18/2014
Java Programming
sAitch (M* +
case 1P
doSo'ething1(*-
breaN-
case 1P
doSo'ething1(*-
breaN-
case 8P
doSo'ething8(*-
breaN-
case 3P
doSo'ething3(*-
breaN-
case 4P
doSo'ething4(*-
breaN-
defaultP
doSo'ethingElse(*-
,
-n !i" (ragmen M mu" be a variable or e0$re""ion !a #an be #a" o an int +i!ou lo"" o(
$re#i"ion. &!i" mean" !e variable mu" be or !e e0$re""ion mu" reurn an int/ byte/ short or char.
M i" #om$are% +i! !e value o( ea#! !e case "aemen" in "u##e""ion unil one ma#!e". &!i"
(ragmen #om$are" M o lieral"/ bu !e"e oo #oul% be variable" or e0$re""ion" a" long a" !e variable
or re"ul o( !e e0$re""ion i" an int/ byte/ short or char. -( no #a"e" are ma#!e%/ !e %e(aul a#ion i"
riggere%.
?n#e a ma#! i" (oun%/ all "ub"e)uen "aemen" are e0e#ue% unil !e en% o( !e sAitch blo#k i"
rea#!e% or 'ou break ou o( !e blo#k. &!i" #an rigger %e#i%e%l' une0$e#e% be!avior. &!ere(ore i i"
#ommon o in#lu%e !e breaN "aemen a !e en% o( ea#! #a"e blo#k. -," goo% $rogramming $ra#i#e
o $u a breaN a(er ea#! one unle"" 'ou e0$li#il' +an all "ub"e)uen "aemen" o be e0e#ue%.
-," im$oran o remember !a !e sAitch "aemen %oe"n, en% +!en one #a"e i" ma#!e% an% i"
a#ion $er(orme%. &!e $rogram !en e0e#ue" all "aemen" !a (ollo+ in !a sAitch blo#k unil
"$e#i(i#all' ol% o break.
The ' ( operator in Java
Mallikarjun Page 34 5/18/2014
Java Programming
&!e value o( a variable o(en %e$en%" on +!e!er a $ari#ular boolean e0$re""ion i" or i" no rue an%
on no!ing el"e. *or in"an#e one #ommon o$eraion i" "eing !e value o( a variable o !e ma0imum
o( +o )uaniie". -n Java 'ou mig! +rie
if (a > b* +
'aM @ a-
,
else +
'aM @ b-
,
6eing a "ingle variable o one o( +o "ae" ba"e% on a "ingle #on%iion i" "u#! a #ommon u"e o( if2
else !a a "!or#u !a" been %evi"e% (or i/ !e #on%iional o$eraor/ I5. J"ing !e #on%iional o$eraor
'ou #an re+rie !e above e0am$le in a "ingle line like !i"5
'aM @ (a > b* Q a P b-
(a > b* Q a P b- i" an e0$re""ion +!i#! reurn" one o( +o value"/ a or b. &!e #on%iion/ (a > b*/
i" e"e%. -( i i" rue !e (ir" value/ a/ i" reurne%. -( i i" (al"e/ !e "e#on% value/ b/ i" reurne%.
=!i#!ever value i" reurne% i" %e$en%en on !e #on%iional e"/ a > b. &!e #on%iion #an be an'
e0$re""ion +!i#! reurn" a boolean value.
The ' ( operator in Java
&!e #on%iional o$eraor onl' +ork" (or a""igning a value o a variable/ u"ing a value in a me!o%
invo#aion/ or in "ome o!er +a' !a in%i#ae" !e '$e o( i" "e#on% an% !ir% argumen". *or e0am$le/
#on"i%er !e (ollo+ing
if (na'eeJuals(7Ru':lestiltsNin7** +
Syste'out:rintln(7Ri4e bacN child7*-
,
else +
Syste'out:rintln(7Laugh7*-
,
&!i" ma' not be +rien like !i"5
na'eeJuals(7Ru':lestiltsNin7*
Q Syste'out:rintln(7Ri4e bacN child7*
P Syste'out:rintln(7Laugh7*-
*ir" o( all/ bo! !e "e#on% an% !ir% argumen" are voi%. 6e#on%l'/ no a""ignmen i" $re"en o
in%i#ae !e '$e !a i" e0$e#e% (or !e "e#on% an% !ir% argumen" K!oug! 'ou kno+ voi% mu" be
+rongL.
&!e (ir" argumen o !e #on%iional o$eraor mu" !ave or reurn boolean '$e an% !e "e#on% an%
!ir% argumen" mu" reurn value" #om$aible +i! !e value !e enire e0$re""ion #an be e0$e#e% o
reurn. .ou #an never u"e a 4oid me!o% a" an argumen o !e Q P o$eraor.
Mallikarjun Page 35 5/18/2014
Java Programming
&ogical perators in Java
&!e relaional o$eraor" 'ou,ve learne% "o (ar K?/ ?@/ >/ >@/ C@/ @@L are "u((i#ien +!en 'ou onl' nee% o
#!e#k one #on%iion. 3o+ever +!a i( a $ari#ular a#ion i" o be aken onl' i( "everal #on%iion" are
rueI .ou #an u"e a "e)uen#e o( if "aemen" o e" !e #on%iion"/ a" (ollo+"5
if (M @@ 8* +
if (y C@ 8* +
Syste'out:rintln(7Soth conditions are true7*- ,
,
&!i"/ !o+ever/ i" !ar% o +rie an% !ar%er o rea%. - onl' ge" +or"e a" 'ou a%% more #on%iion".
*orunael'/ Java $rovi%e" an ea"' +a' o !an%le muli$le #on%iion"5 !e logi# o$eraor". &!ere are
!ree logi# o$eraor"/ HH/ II an% C.
HH i" logi#al an%. HH #ombine" +o boolean value" an% reurn" a boolean +!i#! i" rue i( an% onl' i(
bo! o( i" o$eran%" are rue. *or in"an#e
boolean b-
b @ 3 > 8 HH ! ? #- // b is true
b @ 8 > 3 HH ! ? #- // b is noA false
II i" logi#al or. II #ombine" +o boolean variable" or e0$re""ion" an% reurn" a re"ul !a i" rue i(
ei!er or bo! o( i" o$eran%" are rue. *or in"an#e
boolean b-
b @ 3 > 8 II ! ? #- // b is true
b @ 8 > 3 II ! ? #- // b is still true
b @ 8 > 3 II ! > #- // noA b is false
&!e la" logi# o$eraor i" C +!i#! mean" no. - rever"e" !e value o( a boolean e0$re""ion. &!u" i( b i"
rue Cb i" (al"e. -( b i" (al"e Cb i" rue.
boolean b-
b @ C(3 > 8*- // b is false
b @ C(8 > 3*- // b is true
&!e"e o$eraor" allo+ 'ou o e" muli$le #on%iion" more ea"il'. *or in"an#e !e $reviou" e0am$le
#an no+ be +rien a"
if (M @@ 8 HH y C@ 8* +
Syste'out:rintln(7Soth conditions are true7*-
,
&!a," a lo #learer.
The rder of Evaluation of &ogic perators
Mallikarjun Page 36 5/18/2014
Java Programming
=!en Java "ee" a HH o$eraor or a II/ !e e0$re""ion on !e le( "i%e o( !e o$eraor i" evaluae% (ir".
*or e0am$le/ #on"i%er !e (ollo+ing5
boolean bG cG d-
b @ C(3 > 8*- // b is false
c @ C(8 > 3*- // c is true
d @ b HH c- // d is false
=!en Java evaluae" !e e0$re""ion d @ b HH c-/ i (ir" #!e#k" +!e!er b i" rue. 3ere b i" (al"e/ "o b
HH c mu" be (al"e regar%le"" o( +!e!er c i" or i" no rue/ "o Java %oe"n, bo!er #!e#king !e value o(
c.
?n !e o!er !an% +!en (a#e% +i! an II Java "!or #ir#ui" !e evaluaion a" "oon a" i en#ouner" a
rue value "in#e !e re"uling e0$re""ion mu" be rue. &!i" "!or #ir#ui evaluaion i" le"" im$oran in
Java !an in 4 be#au"e in Java !e o$eran%" o( HH an% II mu" be boolean" +!i#! are unlikel' o !ave
"i%e e((e#" !a %e$en% on +!e!er or no !e' are evaluae%. 6ill i," $o""ible o (or#e !em. *or
in"an#e #on"i%er !i" #o%e. boolean b @ (n @@ 1* II ('/n > 8*-
:ven i( n i" 1ero !i" line +ill never #au"e a %ivi"ion b' 1ero/ be#au"e !e le( !an% "i%e i"
al+a'" evaluae% (ir". -( n i" 1ero !en !e le( !an% "i%e i" rue an% !ere," no nee% o evaluae !e rig!
!an% "i%e. Ma!emai#all' !i" make" "en"e be#au"e '/1 i" in "ome "en"e in(inie +!i#! i" greaer !an
+o.
&!i" i"n, a $er(e# "oluion !oug! be#au"e ' ma' be 0 or i ma' be negaive. -( ' i" negaive an% n i"
1ero !en '/n i" negaive in(ini' +!i#! i" le"" !an +o. An% i( ' i" al"o 1ero/ !en '/n i" ver'
un%e(ine%.
&!e $ro$er "oluion a !i" $oin %e$en%" on 'our $roblem. 6in#e real +orl% )uaniie" aren, in(inie/
+!en in(iniie" "ar $o$$ing u$ in 'our $rogram"/ nine ime" ou o( en i," a "ign !a 'ou,ve lo" oo
mu#! $re#i"ion. &!e remaining ime" are generall' "ignal" !a 'ou,ve le( ou "ome "mall (a#or in
'our $!'"i#al mo%el !a +oul% remove !e in(ini'.
&!ere(ore i( !ere," a real #!an#e 'our $rogram +ill !ave a %ivi%e b' 1ero error !ink #are(ull' abou
+!a i mean" an% !o+ 'ou "!oul% re"$on% o i. -(/ u$on re(le#ion/ 'ou %e#i%e !a +!a 'ou reall'
+an o kno+ i" +!e!er '/n i" (inie an% greaer !an 1ero 'ou "!oul% u"e a line like !i"
boolean b @ (n C@ 1* HH ('/n > 1*-
$voiding %hort &ir#uits
-( 'ou +an all o( 'our boolean e0$re""ion" evaluae% regar%le"" o( !e ru! value o( ea#!/ !en 'ou
#an u"e H an% I in"ea% o( HH an% II. 3o+ever make "ure 'ou u"e !e"e onl' on boolean e0$re""ion".
Jnlike HH an% II/ H an% I al"o !ave a meaning (or numeri# '$e" +!i#! i" #om$leel' %i((eren (rom
!eir meaning (or boolean".
're#eden#e
*inall' le," a%% !e HH/ II/ H/ I an% Q o$eraor" o !e $re#e%en#e able
Mallikarjun Page 37 5/18/2014
Java Programming
1. D/ // E Muli$li#aive o$eraor"
2. G/ H A%%iive o$eraor"
3. @/ C/ C2/ @2 Aelaional o$eraor"
4. 22/ B2 &!en %o an' #om$ari"on" (or e)uali' an% ine)uali'
5. M 8i+i"e an%
6. N 8i+i"e or
7. MM >ogi#al an%
8. NN >ogi#al or
9. I 5 4on%iional o$eraor
10. 2 A""ignmen o$eraor
)eclaring *rrays
>ike all o!er variable" in Java/ an arra' mu" !ave a "$e#i(i# '$e like byte/ int/ String or
double. ?nl' variable" o( !e a$$ro$riae '$e #an be "ore% in an arra'. ?ne arra' #anno "ore bo!
in" an% 6ring"/ (or in"an#e.
>ike all o!er variable" in Java an arra' mu" be %e#lare%. =!en 'ou %e#lare an arra' variable 'ou
"u((i0 !e '$e +i! <= o in%i#ae !a !i" variable i" an arra'. 3ere are "ome e0am$le"5
int<= N-
float<= yt-
String<= na'es-
&!i" "a'" !a N i" an arra' o( in"/ yt i" an arra' o( (loa" an% na'es i" an arra' o( 6ring". -n o!er
+or%" 'ou %e#lare an arra' like 'ou %e#lare an' o!er variable e0#e$ !a 'ou a$$en% bra#ke" o !e
en% o( !e '$e.
.ou al"o !ave !e o$ion o a$$en% !e bra#ke" o !e variable in"ea% o( !e '$e.
int N<=-
float yt<=-
String na'es<=-
3o+ever/ unlike in 4/ 'ou #anno in#lu%e !e leng! o( !e arra' in !e %e#laraion. &!e (ollo+ing i" a
"'na0 error5
int N<3=-
float yt<#=-
String na'es<111=-
int N<=-
float yt<=-
String na'es<=-
Creating *rrays
Fe#laring arra'" merel' "a'" +!a kin% o( value" !e arra' +ill !ol%. - %oe" no #reae !em. Java
arra'" are obje#"/ an% like an' o!er obje# 'ou u"e !e neA ke'+or% o #reae !em. =!en 'ou #reae
Mallikarjun Page 38 5/18/2014
Java Programming
an arra'/ 'ou mu" ell !e #om$iler !o+ man' #om$onen" +ill be "ore% in i. 3ere," !o+ 'ou,% #reae
!e variable" %e#lare% on !e $reviou" $age5
N @ neA int<3=-
yt @ neA float<#=-
na'es @ neA String<!1=-
&!e number" in !e bra#ke" "$e#i(' !e leng! o( !e arra'< !a i"/ !o+ man' "lo" i !a" o !ol%
value". =i! !e leng!" above N #an !ol% !ree in"/ yt #an !ol% "even (loa" an% na'es #an !ol% (i('
6ring". &!i" "e$ i" "omeime" #alle% allo#aing !e arra' "in#e i "e" a"i%e !e memor' !e arra'
re)uire".
Initiali+ing *rrays
-n%ivi%ual #om$onen" o( an arra' are re(eren#e% b' !e arra' name an% b' an ineger +!i#! re$re"en"
!eir $o"iion in !e arra'. &!e number" 'ou u"e o i%eni(' !em are #alle% "ub"#ri$" or in%e0e" ino
!e arra'.
6ub"#ri$" are #on"e#uive ineger" beginning +i! 0. &!u" !e arra' N above !a" #om$onen" N<1=/
N<1=/ an% N<8=. 6in#e 'ou "ar #ouning a 1ero !ere i" no N<3=/ an% r'ing o a##e"" i +ill !ro+ an
Array3ndeM5ut5fSoundsEMce:tion. .ou #an u"e arra' #om$onen" +!erever 'ou,% u"e a "imilarl'
'$e% variable !a +a"n, $ar o( an arra'. *or e0am$le !i" i" !o+ 'ou,% "ore value" in !e arra'"
above5
N<1= @ 8-
N<1= @ !-
N<8= @ 28-
yt<1#= @ #!f-
na'es<4= @ 7Fred7-
&!i" "e$ i" #alle% iniiali1ing !e arra' or/ more $re#i"el'/ iniiali1ing !e #om$onen" o( !e arra'.
6omeime" !e $!ra"e ;iniiali1ing !e arra'; i" u"e% o mean +!en 'ou iniiali1e all !e #om$onen" o(
!e arra'.
*or even me%ium "i1e% arra'"/ i," un+iel%' o "$e#i(' ea#! #om$onen in%ivi%uall'. - i" o(en !el$(ul
o u"e (or loo$" o iniiali1e !e arra'. 3ere i" a loo$ +!i#! (ill" an arra' +i! !e ")uare" o( !e
number" (rom 0 o 100.
float<= sJuares-
sJuares @ neA float<111=-
for (int i@1- i ?@ 111- i++* +
sJuares<i= @ i.i-
,
&+o !ing" 'ou "!oul% noe abou !i" #o%e (ragmen5
1. =a#! !e (en#e$o""B 6in#e arra' "ub"#ri$" begin a 1ero 'ou nee% 101 #om$onen" i( 'ou
+an o in#lu%e !e ")uare o( 100.
Mallikarjun Page 39 5/18/2014
Java Programming
2. Al!oug! i i" an in/ i i" $romoe% o a (loa +!en i i" "ore% in ")uare"/ "in#e ")uare" i"
%e#lare% o be an arra' o( (loa".
,ystem-arraycopy#$
Al!oug! #o$'ing an arra' i"n, $ari#ularl' %i((i#ul/ i i" an o$eraion +!i#! bene(i" (rom a naive
im$lemenaion. &!ere(ore 6a4alangSyste' in#lu%e" a "ai# Syste'arrayco:y(* me!o% 'ou #an
u"e o #o$' one arra' o ano!er.
:ublic static 4oid arrayco:y(5b6ect sourceG int sourceTositionG
5b6ect destinationG int destinationTositionG int nu'ber5fEle'ents*
Syste'arrayco:y(* #o$ie" nu'ber5fEle'ents elemen" (rom !e arra' source/ beginning +i! !e
elemen a sourceTosition/ o !e arra' destination "aring a destinationTosition. &!e
destination arra' mu" alrea%' e0i" +!en Syste'arrayco:y(* i" #alle%. &!e me!o% %oe" no
#reae i. &!e source an% destination arra'" mu" be o( !e "ame '$e.
*or e0am$le/
int<= unicode @ neA int<"!!3"=-
for (int i @ 1- i ? unicodelength- i++* +
unicode<i= @ i-
,
int<= latin1 @ neA int<8!"=-
Syste'arrayco:y(unicodeG 1G latin1G 1G 8!"*-
.ulti/)imensional *rrays
6o (ar all !e"e arra'" !ave been oneH%imen"ional. &!a i"/ a "ingle number #oul% lo#ae an' value in
!e arra'. 3o+ever "omeime" %aa i" naurall' re$re"ene% b' more !an one number. *or in"an#e a
$o"iion on !e ear! re)uire" a laiu%e an% a longiu%e.
&!e mo" #ommon kin% o( muli%imen"ional arra' i" !e +oH%imen"ional arra'. -( 'ou !ink o( a oneH
%imen"ional arra' a" a #olumn o( value"/ 'ou #an !ink o( a +oH%imen"ional arra' a" a able o( value"
like !i"
#0 #1 #2 #3
r0 0 1 2 3
r1 1 2 3 4
r2 2 3 4 5
r3 3 4 5 6
r4 4 5 6 7
3ere +e !ave an arra' +i! (ive ro+" an% (our #olumn". - !a" +en' oal elemen". 3o+ever +e "a'
i !a" %imen"ion (ive b' (our/ no %imen"ion +en'. &!i" arra' i" no !e "ame a" a (our b' (ive arra'
like !i" one5
Mallikarjun Page 40 5/18/2014
Java Programming
#0 #1 #2 #3 #4
r0 0 1 2 3 4
r1 1 2 3 4 5
r2 2 3 4 5 6
r3 3 4 5 6 7
=e nee% o u"e +o number" o i%eni(' a $o"iion in a +oH%imen"ional arra'. &!e"e are !e elemen,"
ro+ an% #olumn $o"iion". *or in"an#e i( !e above arra' i" #alle% ; !en ;<1=<1= i" 0/ ;<1=<1= i" 1/
;<1=<8= i" 2/ ;<1=<3= i" 3/ ;<1=<1= i" 1/ an% "o on.
3ere," !o+ !e elemen" in a (our b' (ive arra' #alle% % are re(erre% o5
MO0PO0P MO0PO1P MO0PO2P MO0PO3P MO0PO4P
MO1PO0P MO1PO1P MO1PO2P MO1PO3P MO1PO4P
MO2PO0P MO2PO1P MO2PO2P MO2PO3P MO2PO4P
MO3PO0P MO3PO1P MO3PO2P MO3PO3P MO3PO4P
)eclaring0 *llocating and Initiali+ing Two
)imensional *rrays
&+o %imen"ional arra'" are %e#lare%/ allo#ae% an% iniiali1e% mu#! like one %imen"ional arra'".
3o+ever 'ou !ave o "$e#i(' +o %imen"ion" ra!er !an one/ an% 'ou '$i#all' u"e +o ne"e% (or
loo$" o (ill !e arra'.
&!i" e0am$le (ill" a +oH%imen"ional arra' +i! !e "um o( !e ro+ an% #olumn in%e0e"
class FillArray +
:ublic static 4oid 'ain (String args<=* +

int<=<= 'atriM-
'atriM @ neA int<4=<!=-
for (int roA@1- roA ? 4- roA++* +
for (int col@1- col ? !- col++* +
'atriM<roA=<col= @ roA+col-
,
,
,
,
?( #our"e !e algori!m 'ou u"e o (ill !e arra' %e$en%" #om$leel' on !e u"e o +!i#! !e arra' i" o
be $u. &!e ne0 e0am$le #al#ulae" !e i%eni' mari0 (or a given %imen"ion. &!e i%eni' mari0 o(
%imen"ion 7 i" a ")uare mari0 +!i#! #onain" one" along !e %iagonal an% 1ero" in all o!er $o"iion".
class 3D%atriM +
Mallikarjun Page 41 5/18/2014
Java Programming
:ublic static 4oid 'ain (String args<=* +

double<=<= id-
id @ neA double<4=<4=-

for (int roA@1- roA ? 4- roA++* +
for (int col@1- col ? 4- col++* +
if (roA C@ col* +
id<roA=<col=@11-
,
else +
id<roA=<col= @ 11-
,
,
,

,

,
-n +oH%imen"ional arra'" Array3ndeM5ut5fSoundsEMce:tion" o##ur +!enever 'ou e0#ee% !e
ma0imum #olumn in%e0 or ro+ in%e0.
.ou #an al"o %e#lare/ allo#ae/ an% iniiali1e a a +oH%imen"ional arra' a !e "ame ime b' $rovi%ing a
li" o( !e iniial value" in"i%e ne"e% bra#ke". *or in"an#e !e !ree b' !ree i%eni' mari0 #oul% be
"e u$ like !i"5
double<=<= 3D3 @ +
+11G 11G 11,G
+11G 11G 11,G
+11G 11G 11,
,-
&!e "$a#ing an% !e line break" u"e% above are $urel' (or !e $rogrammer. &!e #om$iler %oe"n, #are.
&!e (ollo+ing +ork" e)uall' +ell5
double<=<= 3D3 @ ++11G 11G 11,G+11G 11G 11,G+11G 11G 11,,-
Even 1igher )imensions
Mallikarjun Page 42 5/18/2014
Java Programming
.ou %on, !ave o "o$ +i! +o %imen"ional arra'". Java $ermi" arra'" o( !ree/ (our or more
%imen"ion". 3o+ever #!an#e" are $re' goo% !a i( 'ou nee% more !an !ree %imen"ion" in an arra'/
'ou,re $robabl' u"ing !e +rong %aa "ru#ure. :ven !ree %imen"ional arra'" are e0#e$ionall' rare
ou"i%e o( "#ieni(i# an% engineering a$$li#aion".
&!e "'na0 (or !ree %imen"ional arra'" i" a %ire# e0en"ion o( !a (or +oH%imen"ional arra'". &!e
$rogram belo+ %e#lare"/ allo#ae" an% iniiali1e" a !reeH%imen"ional arra'. &!e arra' i" (ille% +i! !e
"um o( i" in%e0e".
class Fill3DArray +
:ublic static 4oid 'ain (String args<=* +

int<=<=<= %-
% @ neA int<4=<!=<3=-

for (int roA@1- roA ? 4- roA++* +
for (int col@1- col ? !- col++* +
for (int 4er@1- 4er ? 3- 4er++* +
%<roA=<col=<4er= @ roA+col+4er-
,
,
,

,

,
.ou nee% !e a%%iional ne"e% for loo$ o !an%le !e e0ra %imen"ion. &!e "'na0 (or "ill !ig!er
%imen"ion" i" "imilar. Ju" a%% ano!er $air o( bra#ke" an% ano!er %imen"ion.
Unbalan#ed $rrays
>ike 4 Java %oe" no !ave rue muli%imen"ional arra'". Java (ake" muli%imen"ional arra'" u"ing
arra'" o( arra'". &!i" mean" !a i i" $o""ible o !ave unbalan#e% arra'". An unbalan#e% arra' i" a
muli%imen"ional arra' +!ere !e %imen"ion i"n, !e "ame (or all ro+". -n mo" a$$li#aion" !i" i" a
!orrible i%ea an% "!oul% be avoi%e%.
2ee% 3 E4ercises
Mallikarjun Page 43 5/18/2014
Java Programming
1. 6ale" a0 in 7e+ .ork 4i' i" 8.25E. =rie a $rogram !a a##e$" a $ri#e on !e #omman% line
an% $rin" ou !e a$$ro$riae a0 an% oal $ur#!a"e $ri#e.
2. Mo%i(' !e "ale" a0 $rogram o a##e$ an arbirar' number o( $ri#e"/ oal !em/ #al#ulae !e
"ale" a0 an% $rin !e oal amoun.
3. =rie a $rogram !a rea%" +o number" (rom !e #omman% line/ !e number o( !our" +orke%
b' an em$lo'ee an% !eir ba"e $a' rae. &!en ou$u !e oal $a' %ue.
4. Mo%i(' !e $reviou" $rogram o mee !e J.6. Fe$. o( >abor," re)uiremen (or ime an% a !al(
$a' (or !our" over (or' +orke% in a given +eek.
5. A%% +arning me""age" o !e $a'roll $rogram i( !e $a' rae i" le"" !an !e minimum +age
KQ5.15 an !our a" o( 1998L or i( !e em$lo'ee +orke% more !an !e number o( !our" in a +eek.
6. =rie a $rogram !a rea%" an ineger n (rom !e #omman% line an% #al#ulae" nB Kn (a#orialL.
7. &!ere are e0a#l' 2.54 #enimeer" o an in#!. =rie a $rogram !a ake" a number o( in#!e"
(rom !e #omman% line an% #onver" i o #enimeer".
8. =rie !e inver"e $rogram !a rea%" a number o( #enimeer" (rom !e #omman% line an%
#onver" i o in#!e".
9. &!ere are 454 gram" in a $oun% an% 1000 gram" in a kilogram. =rie $rogram" !a #onver
$oun%" o kilogram" an% kilogram" o $oun%". Aea% !e number o be #onvere% (rom !e
#omman% line. 4an 'ou make !i" one $rogram in"ea% o( +oI
10. &!e e)uivalen re"i"an#e o( re"i"or" #onne#e% in "erie" i" #al#ulae% b' a%%ing !e re"i"an#e"
o( !e in%ivi%ual re"i"or". =rie a $rogram !a a##e$" a "erie" o( re"i"an#e" (rom !e
#omman% line an% ou$u" !e e)uivalen re"i"an#e.
11. &!e (ormula (or re"i"or" #onne#e% in $arallel i" a lile more #om$le0. 9iven +o re"i"or" +i!
re"i"an#e" A1 an% A2 #onne#e% in $arallel !e e)uivalen re"i"an#e i" given b' !e inver"e o(
!e "um o( !e inver"e"/ i.e.
18 1
13 ReJui4 @ 22222222
14 1 1
1! 22 + 22
1" R1 R8
-( !ere are more !an +o re"i"or" 'ou #oninue o inver !e "um o( !eir inver"e"< e.g. (or (our
re"i"or" 'ou !ave5
1
ReJui4 @ 222222222222222222
1 1 1 1
22 + 22 + 22 + 22
R1 R8 R3 R4
=rie a $rogram !a #al#ulae" !e re"i"an#e o( a a grou$ o( re"i"or" arrange% in $arallel. &!e
re"i"an#e" +ill all be $a""e% a" #omman% line argumen".
Mallikarjun Page 44 5/18/2014

Potrebbero piacerti anche