36
7/23/2019 DATA TYPES IN JAVA.doc http://slidepdf.com/reader/full/data-types-in-javadoc 1/36 r4r.co.in/java/corejava/topics/basics/13java_Array_contd1.shtml` DATA TYPES IN JAVA Java is a strongly typed language so there must be a data type associated with every variable declared. ainly there are eight primitive data types which are used in the java. !ut o" the eight data types used 4 are integer data types# $ are "loat data types# one is character type and last but not the least is boolean type data type. %ow we shall see all these data types in detail & INTEGER TYPES 'nteger data types are used "or integral numbers i.e. the numbers that do not have "ractional parts. (or 'nteger types there are "our )ind o" data types are used in java# each having di""erent storage capactiy and range and based upon that they can be categorised as under &  *+,- *!A0-  %-- 2+*- A%0-  byte 1 51$6 to 1$7  short $ 53$786 to 3$787  int 4 5$147#463#846 to $147#463#847  long 6 5 9#$$3#37$#:38#6;4#77;#6:6 to 59#$$3#37$#:38#6;4#77;#6: 7 'n java the ranges o" the integer data types does not depend upon the machine on which you are e<ecuting your java code# their ranges are "i<ed# but unli)e# in =>> or = the values o" the integer data types changes i" there is a change in the plat"orm. (ollowing show the way how we can write various integer literals in java & 1. int literals are written in decimal notation as usual li)e 1$3 or 5$344;. $. long literals are written in decimal notation but post"i<ed by an ?# eg $34;;8? or 5;8487778786?.  % & Java does not have unsigned types. FLOATING-POINT TYPES (loating5point types are the numbers that are having "ractional part. ased upon the storage capacity and range they can be categorised into the "ollowing types &  *+,-  *!A0-  %-- 2'% +*-  A%0-

DATA TYPES IN JAVA.doc

  • Upload
    sarma

  • View
    239

  • Download
    0

Embed Size (px)

Citation preview

Page 1: DATA TYPES IN JAVA.doc

7/23/2019 DATA TYPES IN JAVA.doc

http://slidepdf.com/reader/full/data-types-in-javadoc 1/36

r4r.co.in/java/corejava/topics/basics/13java_Array_contd1.shtml`

DATA TYPES IN JAVAJava is a strongly typed language so there must be a data type associated with everyvariable declared. ainly there are eight primitive data types which are used in the java.!ut o" the eight data types used 4 are integer data types# $ are "loat data types# one ischaracter type and last but not the least is boolean type data type. %ow we shall see all

these data types in detail &

INTEGER TYPES'nteger data types are used "or integral numbers i.e. the numbers that do not have"ractional parts. (or 'nteger types there are "our )ind o" data types are used in java# eachhaving di""erent storage capactiy and range and based upon that they can be categorisedas under &

 *+,-

*!A0- %--

2+*-

A%0-

  byte 1 51$6 to 1$7

  short $ 53$786 to 3$787

  int 45$147#463#846 to$147#463#847

  long 6

59#$$3#37$#:38#6;4#77;#6:6to59#$$3#37$#:38#6;4#77;#6:7

'n java the ranges o" the integer data types does not depend upon the machine on whichyou are e<ecuting your java code# their ranges are "i<ed# but unli)e# in =>> or = thevalues o" the integer data types changes i" there is a change in the plat"orm. (ollowingshow the way how we can write various integer literals in java &1. int literals are written in decimal notation as usual li)e 1$3 or 5$344;.$. long literals are written in decimal notation but post"i<ed by an ?# eg $34;;8? or5;8487778786?. % & Java does not have unsigned types.

FLOATING-POINT TYPES

(loating5point types are the numbers that are having "ractional part. ased upon thestorage capacity and range they can be categorised into the "ollowing types &

 *+,-

 *!A0- %-- 2'%+*-

  A%0-

Page 2: DATA TYPES IN JAVA.doc

7/23/2019 DATA TYPES IN JAVA.doc

http://slidepdf.com/reader/full/data-types-in-javadoc 2/36

r4r.co.in/java/corejava/topics/basics/13java_Array_contd1.shtml`

  "loat 4 appro< @3.4:$6$$37->36 (

 double

  6  appro<@1.7978931$468$31;7:->3:6

ere# double corresponds to the "act that# it has double precision than that o" "loat types#thatBs why double are also re"erred as double precision numbers. (or "loating5point types#we mostly use the double types# because o" the "act that "loat has a less precision so itmay be incompatible "or certain type o" calculations that reCuire more precision.(or writing "loat literals we just post"i<es ( a"ter the number as 4343.4;4;;(# and anumber not "ollowed by (# will be simply termed as double by de"ault.

Java TutorialsHARACTER TYPES

Java *utorialsharacter type are the alphabets which are written in single Cuotes. 't is basically a 185bit unicode character# its minimum value is Du::::2which eCuals to : andma<imum is Dn((((2which eCuals to 8;#;3;. ince it is a 185bit unicode character so itta)es $ bytes in the memory upon declaration# while in = a character literal ta)es 1 bytein the memory. (or eg.char BBEis a character.

BOOLEAN TYPESoolean types are usually used "or chec)ing the logical conditions. *hese data types havetwo values true and alse and also you cannot use integers instead o" boolean values in java as you use in = or =>>.'" you will use i"2FG: statement# in = or =>> it will compile but in java it will notcompile and will give compilation error.

'denti"iers represent names which can be assigned to variables# methods# and classes touniCuely identi"y them. 'n java you can be creative in naming identi"iers# but there aresome limitations such as# all Java identi"iers are case5sensitive and must begin with aletter# an underscore 2_# or a dollar sign 2H. ?etters include both upper and lowercaseletters# identi"ier characters can include the numbers "rom : to 9 and "inally we cannotuse Java de"ined )eywords as identi"iers. (or e.g. _shashi7# Hr4remployee# programmer are some valid identi"iers.

LITERALS?iterals are the constant values that are used in a program. *hese can include integers#"loating5point numbers# characters# boolean and string values. (ollowing are thee<amples o" literals &'nteger ?iterals & $# 3# 54# ;(loating point ?iterals & 3.4;# .:967# 943.4;=haracter ?iterals & BhB# B)B#B1B# B$B

Page 3: DATA TYPES IN JAVA.doc

7/23/2019 DATA TYPES IN JAVA.doc

http://slidepdf.com/reader/full/data-types-in-javadoc 3/36

r4r.co.in/java/corejava/topics/basics/13java_Array_contd1.shtml`

oolean ?iterals & true# "alsetring ?iterals & IshashiI# Ir4rI# I1$343I

VARIABLES IN JAVAA variable may be de"ined as a storage location in memory "or storing di""erent data

types. *hus# every variable has a type so we can declare a variable as &int sumEdouble sumEchar nameE

R!LES FOR DECLARING VARIABLES "

1. A variable name is decalared with a letter at begining and then can be a seCuence o"letters and digits.$. ymbols li)e > or cannot be used inside a variable name and also there canBt be anyspace in variable name.

3. All characters in the variable are case sensitive and length is essentially unlimited.4. +ou cannot use java )eywords as variable names.

ASSIGN#ENT AND INITIALI$ATIONA"ter you declare a variable you must initialiFe it e<plicitly# as uninitialiFed varibale cannever be used.int numberE // this is declarationnumberG1:E // this is assignment

'n java you can declare a variable and assigned it value upon declaration# i.e. intialiFationo" variable

int numberG1:E // this is initialiFation+ou cannot declare two varibles o" same name in the same scope.

Java TutorialsONSTANTS IN JAVA

'n java you use the )eyword i%al declare a constant. (or eg.

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

  final int NU ! "#$  int num"! %#$  int num&!&#$  S'stemoutprintln(ultiplication is given b' *(NU+num"+num&))$  ,,

*he )eyword "inal suggests that you can assign the variable once# a"ter that its value is setonce "or all. *he constant name should be in capital letters or upper case.

Page 4: DATA TYPES IN JAVA.doc

7/23/2019 DATA TYPES IN JAVA.doc

http://slidepdf.com/reader/full/data-types-in-javadoc 4/36

r4r.co.in/java/corejava/topics/basics/13java_Array_contd1.shtml`

't is more common in java to declare constants that are available to multiple methods o"the class# such constants are called class constants. +ou can declare a class constant bydeclaring them static "inal. (or eg.

public class Java TutorialsonstExample{ public static final NU!"#$  public static void main(String args[])  {  int num"!%#$  int num&!&#$  S'stemoutprintln(ultiplication is given b'*(NU+num"+num&))$  ,,

*he class constant is de"ined outside the main method# that means it can be accessed by

all the methods o" the same class.

OPERATORS IN JAVA*he basic arithmetic operators ># K# L# / are used in Java "or addition# subtraction#multiplication and division. *he / operator denotes integer division i" both arguments areintegers# and "loating5point division otherwise. *he mod "unction is denoted by M. (ore<ample# 19 / $ is 9# $1 M $ is 1# and 7.: / $ is 3.;.%ote that integer division by : raisesan e<ception# whereas "loating5point division by : yields an in"inite result.+ou can usethe arithmetic operators in your variable initialiFations&int p G 9int C G $ L pE // *he value o" C is 16

*here is a convenient shortcut "or using binary arithmetic operators in an assignment. (or e.g. p >G 4Eis eCual to p G p > 4E

INCRE#ENT AND DECRE#ENT OPERATORS!ne o" the most common operations with a numeric variable is to increment or decrementit value by 1. Java li)e in = and =>># has both increment and decrement operators& p>> adds 1 to the current value o" the variable p# and p55 subtracts 1 "rom it. (or e.g.int G 8E p>>Echanges p to 7. ecause these operators change the value o" a variable# they cannot beapplied to numbers themselves. (or e<ample# 7>> is not a legal statement in java.*here are actually two "orms o" these operators# in above e<amples we have seen the post"i< "orm o" the operator that is placed a"ter the operand. *here is also a pre"i< "orm# >>p. oth change the value o" the variable by 1. ut there is di""erence between the two

Page 5: DATA TYPES IN JAVA.doc

7/23/2019 DATA TYPES IN JAVA.doc

http://slidepdf.com/reader/full/data-types-in-javadoc 5/36

r4r.co.in/java/corejava/topics/basics/13java_Array_contd1.shtml`

and can only appear when they are used inside e<pressions. *he pre"i< "orm does theaddition "irst# the post"i< "orm evaluates to the old value o" the variable.

int p G 3Eint C G 3E

 p>>E>>CEint < G 4 L pE // < is 1$# p is 6int y G 4 L CE // y is 18# C is 6

&EY'ORDS

Neywords are prede"ined identi"iers reserved by Java "or a speci"ic purpose and are usedonly in a limited# speci"ied manner. Java has a richer set o" )eywords than = or =>>. *he"ollowing )eywords are reserved "or Java&

abstract double int super  boolean else inter"ace switch brea) e<tend long synchroniFed byte "alse native this byvalue "inal new threadsa"ecase "inally null throwcatch "loat pac)age transientchar "or private trueclass goto protected tryconst i" public voidcontinue implements return while

de"ault import short

RELATIONAL AND BOOLEAN OPERATORS

Java has the "ull complement o" relational operators. (or testing the eCuality you use adouble eCual sign ((. (or e<ample# the value o" ; GG 8# is "alse.Oe use a )( "or ineCuality. (or e.g. the value o" the "ollowing evaluates to true3 PG 7 is true. %e<t we have have the Q 2less than# R 2greater than# QG 2less than or eCual# andRG2greater than or eCual operators.

Java also uses SS "or the logical A% operator and TT "or the logical ! operator. As youcan easily remember "rom the PG operator# the e<clamation point P is the logical negationoperator. *he SS and TT operators are evaluated in short circuit "ashion. *his means thatwhen we have an e<pression li)e& p SS Ci" the truth value o" the e<pression p has been determined to "alse# the value "or thee<pression C is not calculated. (or e<ample consider the "ollowing e<pression

Page 6: DATA TYPES IN JAVA.doc

7/23/2019 DATA TYPES IN JAVA.doc

http://slidepdf.com/reader/full/data-types-in-javadoc 6/36

r4r.co.in/java/corejava/topics/basics/13java_Array_contd1.shtml`

int pG7Eint CG1Ei"22pGG8SS2CGG1U pGp>1E

CGC51EV

'n the above e.g. the "irst condition pGG8 is evaluated to "alse# so second condition CGG1is never evaluated.imilarly# i" p evaluates to true# then the value o" p TT C is automatically true# withoutevaluating C.Java also supports the ternary W& operator that is occasionally use"ul. *he e<pressioncondition W p & C evaluates to p i" the condition is true# else it evaluates to C. (or e.g.# p R C W p & Cthe above e<pression gives the value p i" p is greater than C or else it will give C.

BIT'ISE OPERATORS

Ohile wor)ing with any )inds o" the integer types# we have the bitwise operators that candirectly wor) with the bits that ma)e up the integers# i.e. you can use mas)ingtechniCues to get at individual bits in a number. (ollowing are the basic bitwise operatorsthat are commonly used &

1. * +AND, itwise operator & A bitwise A% operation ta)es two binayrepresentations o" same length and then per"orms the logical A% operation on the bitso" the binary numbers. '" 1is logically A%ed with 1 the result is 1# else the result is :.

(or e.g.

  : : 1 :  1 : 1 1  _____________ A%ed : : 1 :

$. +NOT, itwise operator & A %!* itwise operator is a unary operation that per"ormlogical negation on each bit. i.e it per"orms a oneBs complement on the binaryrepresentation o" the integers. *he digits with : becomes 1 and vice5versa. (or e.g.

  : : 1 1 %!*G 1 1 : :

3. . +OR , itwise operator & A bitwise ! operation ta)es two binary representations o"same length and then per"orms logical ! operation on bits o" the binary numbers. '" 1 islogically ! with 1 or : the result is 1 and i" : is ! with : the result is Fero. (or eg.

Page 7: DATA TYPES IN JAVA.doc

7/23/2019 DATA TYPES IN JAVA.doc

http://slidepdf.com/reader/full/data-types-in-javadoc 7/36

r4r.co.in/java/corejava/topics/basics/13java_Array_contd1.shtml`

  : 1 1 :  1 : 1 1  __________ ! G 1 1 1 1

4. / +0OR, itwise operator & A bitwise X! operation ta)es two binary representationo" same length and then per"orms logical X! operation on bits o" the binary numbers.*he result is 1 i" both the binary digits are di""erent else result is :. (or e.g.

  : : 1 1  1 : : 1  _____________ X!G1 : 1 :

*he order o" preceedence "or the bitwise operators starting with the highest preceedence"irst is given by T R Y R S.

*here are also RR and QQ operators# which shi"t a bit pattern to the right or le"t. *heseoperators are o"ten convenient when you need to build up bit patterns to do bit mas)ing.int "ourth_"rom_right G 2p S 21 QQ 3 RR 3E

*here is even a RRR operator that "ills the top bits with Fero# whereas RR e<tends the sign bit into the top bits. *here is no QQQ operator.

Java TutorialsONTROL FLO' IN JAVA

Java supports both conditional statements and loops to determine control "low just li)e =and =>>. (irst we deal with the conditional statements and then move on to loops. 'n end

we discuss the somewhat cumbersome switch statement that we can use when we have totest "or many values o" a single e<pression.

?!=N =!,-A bloc) or compound statement is any number o" simple Java statements that aresurrounded by a pair o" braces. loc)s de"ine the scope o" your variables and can benested inside one another. ere is a bloc) that is nested inside the bloc) o" the mainmethod.

public static void main(String[] args){

int p$ {int -$ , .. -/s scope is upto 0ere,

't is not possible to declare same named variables in two nested bloc)s.

Page 8: DATA TYPES IN JAVA.doc

7/23/2019 DATA TYPES IN JAVA.doc

http://slidepdf.com/reader/full/data-types-in-javadoc 8/36

r4r.co.in/java/corejava/topics/basics/13java_Array_contd1.shtml`

Java *utorials!%'*'!%A? *A*--%**he conditional statement in Java has the "orm i +1o%2itio%, state3e%t# just li)e in =and =>>. 'n Java you will o"ten e<ecute multiple statements when a single condition istrue. (or this you use a bloc) statement that ta)es the "orm&

{statement"$statement%$ ,1or instance2  if (num 3! "#)  {  S'stemoutprintln(T0e value of num is 4*num)$  ,

'n above e<ample the statements surrounded by the braces will be e<ecuted when num isgreater than or eCual to 1:.

i-else State3e%t

Java# li)e = and =>> also has i"5else conditional statements which ta)es the "orm

 if(condition is true)  {  ..5ill execute statements if condition is true ot0er5isecontrol passes to else bloc6  statment"$  statement%$  ,  else

  {  .. 5ill execute if condition is false  statement&$  ,

i-else i-else State3e%t

Java uses this statement "or the e<ecution o" the multiple alternatives and is Cuitecommon# "or e<ample

 if (totalmar6s 3! 7##)

{8rade ! 9$result ! Excellent$,else if(totalmar6s3!&##){8rade ! :$result ! 8ood$,else if (totalmar6s3!%##)

Page 9: DATA TYPES IN JAVA.doc

7/23/2019 DATA TYPES IN JAVA.doc

http://slidepdf.com/reader/full/data-types-in-javadoc 9/36

r4r.co.in/java/corejava/topics/basics/13java_Array_contd1.shtml`

{8rade ! ;$result ! 9verage$,else{S'stemoutprintln(1ailed)$,

LOOP CONTROL

'n Java there are control structures that let you repeat statements. uch control structuresare called ?oops. ?oops can be "urther categorised as &1. 'ndeterminate ?oops$. eterminate ?oops

'%-*-'%A*- ?!!,?oops in which you do not )now how many times a loop should be processed are called'ndeterminate loops. *wo types o" indeterminate loops are "ollowing as under &

(irstly there is the while loop that only e<ecutes the body o" the loop while a condition istrue. 'ts general "orm is&45ile +1o%2itio%,

 U 

statement1E  statement$E V*he while loop will never e<ecute i" the condition is "alse. 'ts structure is Cuite verysimilar to other languages li)e = and =>>.

econdly there is the do5while loop that e<ecutes the body o" the loop at least onceirrespective o" the condition is true or "alse. Just li)e other languages it has the "ollowing"orm &2o

Ustatement1Estatement$EV45ile+1o%2itio%,6

-*-'%A*- ?!!,

*he "or loop is a very common construct to support iteration that is controlled by acounter or similar variable that is updated a"ter every iteration. ?i)e other languages ithas the "orm &or+i%t 7(86 79:86 7;;,

U  ystem.out.println2jEV*he above program prints numbers "rom :59.

Page 10: DATA TYPES IN JAVA.doc

7/23/2019 DATA TYPES IN JAVA.doc

http://slidepdf.com/reader/full/data-types-in-javadoc 10/36

r4r.co.in/java/corejava/topics/basics/13java_Array_contd1.shtml`

'n general# the "irst slot o" the "or loop contains the counter initialiFation# second "ortesting the condition given and the last one is "or updating the counter. Java li)e =# allowsalmost any e<pression in the various slots o" a "or loop# but itBs an unwritten rule that thethree slots o" a "or statement should only initialiFe# test# and update the same countervariable.

S'ITCH STATE#ENT

imilar to the i"5else branch# the switch statement is speci"ically designed to conditionallyswitch among multiple alternatives. *he synta< "or the switch statement "ollows&

s5itc0 (input) {Java Tutorialsase label"4Statement"$brea6$Java Tutorialsase label%4Statement%$brea6$<default4=efaultStatement$,

*he switch branch evaluates and compares input to all o" the case label and branches the programZs e<ecution to the matching case statement list. '" no case label matches input#the program branches to the e"aulttatement# i" one has been de"ined 2e"aulttatementis optional. 'n switch a statement list is simply a series# or list# o" statements. [nli)e thei"5else branch# which directs program "low to a simple or compound statement# the switchstatement directs the "low to list o" statements. Ohen the program e<ecution moves into

a case statement list# it continues "rom there in a seCuential manner. %ote that the case labels must be integers. +ou cannot test strings. (or e<ample# the"ollowing is an error&

String input ! an'value$s5itc0 (input) .. 5rong2 s0o5 error{Java Tutorialsase p4 ..5rong2 5ill s0o5 error brea6$ ,

!si%< =rea>? 1o%ti%ue or =rea>i%< t5e Co%trol Flo4

=rea> State3e%t'n Java we have goto as a reserved )eyword# but the designers o" java decided not toinclude it in the language. 'n general# goto statements are considered poor style o" programming. ut some programmers argue that goto is use"ul "or an occasional jumpout o" a loop. *he Java designers gave it a nod and added a new statement to support this

Page 11: DATA TYPES IN JAVA.doc

7/23/2019 DATA TYPES IN JAVA.doc

http://slidepdf.com/reader/full/data-types-in-javadoc 11/36

r4r.co.in/java/corejava/topics/basics/13java_Array_contd1.shtml`

 programming style# the labeled brea). ?et us "irst loo) at the unlabeled brea) statement.*he brea) statement that you use to e<it a switch can also be used to brea) out o" a loop.(or e<ample#

Java Tutorialslass =emoUnlabeled:rea6{

  public static void main (String args[]){

  int i ! #$  do

{  S'stemoutprintln(>demobrea6?)$  i**$  if (i 3 @#)  brea6$  ,  50ile (true)$  ,,

'n above e<ample# an in"inite do5while loop is created by setting the loop condition totrue. ut here we incorporate the brea) statement to e<it the loop when i is incremented past ;:.

Java also o""ers a labeled brea) statement that lets you brea) out o" multiple nested loops.!ccasionally something weird happens inside a deeply nested loop. 'n that case# you maywant to brea) completely out o" all the nested loops. 't is inconvenient to program thatsimply by adding e<tra conditions to the various loop tests.

Java Tutorialslass =emoAabel:rea6

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

  int i ! BntegerparseBnt(args[#])$  labelbrea64

50ile(true){

  for(i!#$iC@"$i**){

  S'stemoutprintln(>demobrea6?)$  i**$  if (i 3 @#)  brea6 labelbrea6$  ,

  ,  S'stemoutprintln(Undesired value of i)$

,,

'n above program i" the value o" i is greater than ;: is inputted by user than control willcome out o" the loop and will pass to the very ne<t statement a"ter the loop.

Page 12: DATA TYPES IN JAVA.doc

7/23/2019 DATA TYPES IN JAVA.doc

http://slidepdf.com/reader/full/data-types-in-javadoc 12/36

r4r.co.in/java/corejava/topics/basics/13java_Array_contd1.shtml`

Java Tutorialso%ti%ue State3e%tAnother use"ul statement that wor)s similarly to the brea) statement is the continuestatement. [nli)e brea)# the continue statement is only use"ul when wor)ing with loopsand has no relation to the switch branch. *he continue statement wor)s li)e the brea)statement in that it jumps out o" the current iteration o" a loop. *he di""erence with

continue is that program e<ecution is restored to the test condition o" the loop while brea)  jumps completely out o" a loop. [se brea) when you want to jump out and terminate aloop# and use continue when you want to jump immediately to the ne<t iteration o" theloop.

Java Tutorialslass Java Tutorialsontinued{

public static void main(String args[]){int a!#$for(int i!#$iC"#$i**){

if(i3D)Java Tutorialsontinue$a!i$S'stemoutprintln(T0e value of a is4*a)$,,,

*he output o" the program will print values : to 7# a"ter the value o" i become greaterthan 7 ne<t statement a"ter continue will not be e<ecuted and its control will pass to theheader o" the loop i.e in case o" "or loop the control will pass to incrementing slot till theloop terminates.

BIG N!#BERS IN JAVAOhile programming i" the precision o" the integers and "loating point number is notaccording to the reCuirements# then we can use the big numbers de"ined in java. Actually#the big numbers are contained in 7ava@3at5 a1>a<e# ig'nteger is used "ormanipulating the precision o" the integral values while igecimal is used "or the"loating point numbers. *he method value!"2# de"ined in the pac)age can turn anyordinary number to a big number. (or e<ample#

:igBnteger num ! :igBntegervaluef(&##)$

'n this e<ample we have converted a simple integer 3:: to a ig'nteger type value andassigned it to the num. Also note that we cannot use basic operators li)e ># 5# /# L directlyon the big numbers# in"act we have to use prede"ined methods li)e add2# multiply2 inorder to combine the big numbers. (or e.g.

:igBnteger num ! :igBntegervaluef(&##)$:igBnteger p ! numadd(:igBntegervaluef(%##))$ .. it goes asp!num*%##! &##*%##!@##

Page 13: DATA TYPES IN JAVA.doc

7/23/2019 DATA TYPES IN JAVA.doc

http://slidepdf.com/reader/full/data-types-in-javadoc 13/36

r4r.co.in/java/corejava/topics/basics/13java_Array_contd1.shtml`

ome o" the methods which are de"ined in java.math.ig'nteger class and used morecommonly are &

:igBnteger add(:igBnteger second) .. returns t0e sum

of current :igBnteger 5it0 t0e second:igBnteger multipl'(:igBnteger second) .. returns t0emultiplication of current :igBnteger 5it0 t0e second:igBnteger divide(:igBnteger second) .. returns t0edivision of current :igBnteger 5it0 t0e second:igBnteger subrtact(:igBnteger second) .. returns t0esubtraction of current :igBnteger 5it0 t0e second:igBnteger mod(:igBnteger second) .. return t0e modvalue of current :igBnteger 5it0 t0e second

int Java TutorialsompareTo(:igBnteger second)

't compares the value o" the current ig'nteger with the second and then returns an

integral value. '" current number is greater than second than it will give a positive integer#i" eCual it will return :# else it will return a negative value.

static :igBnteger valuef(Aong p)

't converts an integer number to the ig 'nteger type number.

imilarly we can use igecimal class to manipulating the precision o" the "loating pointnumbers. *he "reCuent methods which are de"ined in the java.math.igecimal classare &

:ig=ecimal add(:ig=ecimal second) .. returns t0e sumof current :ig=ecimal 5it0 t0e second:ig=ecimal multipl'(:ig=ecimal second) .. returns t0emultiplication of current :ig=ecimal 5it0 t0e second:ig=ecimal divide(:ig=ecimal second2 int roundoff mode)..returns t0edivison of current :ig=ecimal 5it0second one 5it0 roundoff digits:ig=ecimal subrtact(:ig=ecimal second) .. returns t0esubtraction of current :ig=ecimal 5it0 t0e secondint Java TutorialsompareTo(:ig=ecimal second) ..return an integer after comparing t0e t5o :ig=ecimal t'pe numbersstatic :ig=ecimal valuef(Aong p) .. convert ansimple number to t0e :ig=ecimal t'pe numberstatic :ig=ecimal valuef(Aong p2 int scale) .. converts an simpleto t0e :ig=ecimal number x ."#Fscale

ARRAYS

An array is a data structure that stores a collection o" homogeneous2same type values.+ou can access each individual value o" the array through an integer inde<. (or e<ample#i" arr is an array o" integers# then arr\i] is the ith integer in the array. +ou can declare anarray variable by speci"ying the array type which is the element type "ollowed by \] and

Page 14: DATA TYPES IN JAVA.doc

7/23/2019 DATA TYPES IN JAVA.doc

http://slidepdf.com/reader/full/data-types-in-javadoc 14/36

r4r.co.in/java/corejava/topics/basics/13java_Array_contd1.shtml`

the array variable name. (or e<ample we can delare an array variable arr asint\] arrE //please pre"er this oneor int arr\]EAbove statement only declares the variable arr. 't doesnBt intiailiFe the arr with an actual

array# "or that we have to use new operator to declare an array. (or instance#int\] arr G new int\;:]E

Above declaration creates an array o" integer type which can accomodate ;: integers. 'nJava too# li)e other programming languages# the inde< o" array starts "rom : to 2length51.'n this case array enteries are numbered "rom : to 49. Also Java doesnZt allow you tospeci"y the siFe o" an empty array when declaring the array. +ou always must e<plicitlyset the siFe o" the array with the new operator or by assigning a list o" items to the arrayon creation. '" you try to access the element arr\;:] 2or any other inde< outside the range: ..49# then your program will terminate with an ^array inde< out o" bounds e<ception.As in other languages li)e = and =>> once you create an array# you cannot change its

siFe.

ANONY#O!S ARRAYS

Java can directly create an array object and supply initial values at the same time just li)eother languagaes. (or e.g.int\] numbers G U $# 3# 4# ;# 8# 7# 6 VE+ou do not call new when you declare an array using this approach.+ou can eveninitialiFe an anonymous array in java li)e the "ollowing one&new int\] U 11# 1$# 13# 14# 1;# 18# 17VEAbove declaration allocates a new array and "ills it with the values inside the braces and

counts the number o" initial values then sets the array siFe accordingly. +ou can use thissynta< to reinitialiFe an array without creating a new variable. (or e<ample#

numbers G new int\] U 11# 1$# 13# 14# 1;# 18# 17 VEis a shorthand "or int\] anonymousarr G U 11# 1$# 13# 14# 1;# 18# 17 VEnumbers G anonymousarrE!nce an array is created you can access its elements throught its inde< values.(orcalculating the length o" an array we use length2 method viF. arrayname.length# gives thelength o" the array. (ollowing code snippet shows the very same&

Java Tutorialslass ArrayAccess{  public static void main(String[] args)  {  int[] numbers!{%2 &2 72 @2 G2 D2 H,$  S'stemoutprintln(T0e elements of t0e arra' are 4)$  for(int i!#$iCnumberslengt0$i**)  {  S'stemoutprintln(a[i])$  ,

Page 15: DATA TYPES IN JAVA.doc

7/23/2019 DATA TYPES IN JAVA.doc

http://slidepdf.com/reader/full/data-types-in-javadoc 15/36

r4r.co.in/java/corejava/topics/basics/13java_Array_contd1.shtml`

  ,,

ere# we have use numbers. length to calculate the length o" the array and a\i] gives theelements o" the array.

SORTING AN ARRAY

'n java i" you want to sort an array# you can use sort2 method de"ined in the java.util.Arrays class. +ou can use the method both on the primitive type as well as onthe object type arrays. (or e<ample#

int \] arr G new int\1::]E/L some  logic L/Arrays.sort2arrE

(ollowing program shows how to use sort2 method "or sorting an array &

import Iavautil9rra's$Java Tutorialslass sort{public static void main(String args[]){String[] arr!ne5 String[]{s0as0i2 emplo'ee2 r7r2 soft5are2engineer,$

9rra'ssort(arr)$for(int i!#$ iCarrlengt0$i**)S'stemoutprintln(arr[i])$,,

Java TutorialsOPYING ARRAYS'n java i" you want to copy all values o" one array to another# you have to use thearraycopy method de"ined in the java.lang.ystem class. *he general "orm to call thismethod is &

ystem.arraycopy2copy"romarray# startinginde<# copytoarray# "rominde<#numbero"elementsE

(ollowing e<ample gives you the brie" )nowledge about how to use arraycopy2 method&

Java Tutorialslass Java Tutorialsop'arr{public static void main(String args[]){

Page 16: DATA TYPES IN JAVA.doc

7/23/2019 DATA TYPES IN JAVA.doc

http://slidepdf.com/reader/full/data-types-in-javadoc 16/36

r4r.co.in/java/corejava/topics/basics/13java_Array_contd1.shtml`

String[] arr!ne5 String[]{s0as0i2 emplo'ee2 r7r2 soft5are2engineer,$String[] arr"!ne5 String[&]$S'stemarra'cop'(arr2#2arr"2#2&)$S'stemoutprintln(T0e contents of ne5 arra' 4)$for(int i!#$iCarr"lengt0$i**)S'stemoutprintln(arr"[i])$ ,,

SEARCH IN ARRAYS'n java "or searching an element in an array we have a prede"ined method in the java.util.Arrays class# which searches "or the element by using the binary searchtechniCue. 'ts general synta< is given as &

static int binaryearch2type\] arr# valuetobesearchedE

(or searching the above method ta)es a sorted array o" any data type and the value to be

searched as parameters. *his method will return an integer value# which will be inde< o"the element i" it e<ists in the array# otherwise# it will give a negative value at which theelement can be stored. (ollowing code snippet will help you understand the concept better &

import Iavautil9rra's$Java Tutorialslass sort{public static void main(String args[]){

  String[] arr!ne5 String[]{s0as0i2 emplo'ee2 r7r2 soft5are2engineer,$  9rra'ssort(arr)$for(int i!#$iCarrlengt0$i**)

  {  S'stemoutprintln(arr[i])$  ,  int I!9rra'sbinar'Searc0(arr2r7r)$  S'stemoutprintln(T0e element is at*I)$  S'stemoutprintln(T0e element is4*arr[I])$ ,,

'n above program we have stored the value returned by the binaryearch2 method in aninteger variable i.e j and then we printed the inde< o" the element and its value.

Java TutorialsO##AND LINE ARG!#ENTS IN JAVA

-very Java program has a main method in which a string o" array i.e.#tring\] args is passed as a parameter# and thus arguments can speci"ied on the command line.i.e. at theruntime. (ollowing code snippet describes how to pass command line arguments in java&

Page 17: DATA TYPES IN JAVA.doc

7/23/2019 DATA TYPES IN JAVA.doc

http://slidepdf.com/reader/full/data-types-in-javadoc 17/36

r4r.co.in/java/corejava/topics/basics/13java_Array_contd1.shtml`

Java Tutorialslass Java Tutorialsmdparameters{  public static void main(String[] args)  {  int num"2 num%$  int sum$$  num" ! BntegerparseBnt(args[#])$  num% ! BntegerparseBnt(args["])$  sum ! num" * num%$  S'stemoutprintln(ou 0ave passed command linearguments 4*args[#]*2*args["])$  S'stemoutprintln(T0e sum of t0e numbers is given b' 4*sum)$  ,,

'5at are 1lasses a%2 o=7e1ts i% 7ava'n object5oriented programming languages li)e Java# a class is a construct that is used as

a template to create objects o" that class. *his construct describes the state and behaviourthat the objects o" the class share. ince in Java we cannot do anything without class# sowhen we write a source code in java we are actually creating a class but not object.Oriting a class is called implementing a class and has two main components &the classdeclaration and the class body. =lass declaration contains name o" the class and otherattributes li)e access modi"iers# whereas class body consists o" various methods#variables# and the logic o" the code. *he body o" a class is contained within thecurlyUVbraces# can be declared as &

 access5modi"ier class =lass%ameU

  //some variables  // methods // logic o" codeV

!bjects in java are the entities in the real world problem# and are the building bloc)s o"any Java program. Ohenever we write a source code# we are writting a class and code "or creating the objects "rom that class. *hus# when a program is running objects are created"or doing their speci"ic jobs "or which they have been created. *hus# we can say that aclass is a template that we write and objects are created "rom the class. 'n technical termswe can say that an object is instantiated "rom a class and this process is called

instantiation# thatBs why objects are also called the instances o" the class.

'5at are 3ai% 1o3o%e%ts o a 1lass -very class in Java have the "ollowing components &iel2s" (ields are variables that held data speci"ic to each object. (or e.g.# a student mayhave an ' number# also )nown as member variables.3et5o2s" ethods per"orm operations on an object. (or e.g.# a student may have to seehis/her mar)s.

Page 18: DATA TYPES IN JAVA.doc

7/23/2019 DATA TYPES IN JAVA.doc

http://slidepdf.com/reader/full/data-types-in-javadoc 18/36

r4r.co.in/java/corejava/topics/basics/13java_Array_contd1.shtml`

stati1 iel2s tatic "ields are common to any object o" the same class# only one static "ielde<ists "or one class.stati1 3et5o2s" tatic methods are methods that do not a""ect a speci"ic object.%este2 1lasses"'t is use"ul to contain a class within another one i" it cannot be accessedoutside o" the class.

Java Tutorialso%stru1tors" 't is a special method that generates a new object and havesame name as o" a class.

-<ample#

Java Tutorialslass S0o5;lass{private static int i!#$ ..defined a static fieldint I!"$S0o5;lass(){ ..default constructor declaration,

public static void s0o5() ..defined a static met0od{S'stemoutprintln(T0e value of i is 4*i)$..S'stemoutprintln(T0e value of I is 4*I)$ ..t0is statement5ill cause compilation error2 since I is nonKstatic,public static void main(String args[]){S0o5;lass sc!ne5 S0o5;lass()$s0o5()$ ..5e don/t 0ave tocreate an obIect to call a static met0odscs0o5()$,

,

'5at are 2iere%t tes o 1lasses i% 7ava Java possesses "ive di""erent types o" class constructs and it is good to )now where to useeach type. *he various class types used in java are the "ollowing &

:@ To Level Classes " A top level class is the one that is present on the top in thehierarchy o" class design as without it one can not develop so"tware at all. An e<ample o"top level class is given as#

Java Tutorialslass r7r .. top level class{ public static void main(String args[])  {  .. some logic  ,,

@ Stati1 I%%er Classes " tatic member classes are the most common type o" nestedclasses. A nested class is de"ined inside the body o" an enclosing class and should only be

Page 19: DATA TYPES IN JAVA.doc

7/23/2019 DATA TYPES IN JAVA.doc

http://slidepdf.com/reader/full/data-types-in-javadoc 19/36

r4r.co.in/java/corejava/topics/basics/13java_Array_contd1.shtml`

 present to assist the enclosing class. *here is no boundation to the depth o" nesting o"classes but it is Cuite very rare to see more than one level o" such classes. tatic memberclasses are also )now as static inner classes.*he synta< o" static member classes is shownin "ollowing code snippet#

Java Tutorialslass BnnerStatic;lassExample.. main class{public static void main(String args[]){s0apeLectangle obI!ne5 s0apeLectangle(72D)$ .. creatingobIect for inner class Lectangle2 using dot notationobIarea()$..calculating t0e area of LectangleS'stemoutprintln(T0e value of x is4 *ta)$..printing t0e variable defined in LectangleobIne5 Java Tutorialsircle(D)area()$..calculating t0e area of circle using t0e obIect of LectangleS'stemoutprintln(T0e value of ' is 4*obIne5 Java

Tutorialsircle(D)')$ ..printing t0e value of ',Java Tutorialslass S0ape..top level class{public static class Lectangle ..staticKinner class2 50ose enclosing class is S0ape{int a!"#$int lengt0$int breadt0$public Lectangle(int lengt02 int breadt0)..constructor of Lectangle

{t0islengt0!lengt0$t0isbreadt0!breadt0$,public void area() ..t0ismet0od calculates t0e area of rectangle{S'stemoutprintln(T0e area of rectangle is 4*lengt0+breadt0)$,public class Java Tutorialsircle ..simple member class ;ircle2 50ose enclosing class is Lectangle 50ic0 isstatic{int radius$

int '!%D$public Java Tutorialsircle(int radius) ..constructor of ;ircle{t0isradius!radius$,public void area(){S'stemoutprintln(T0e area of circle is4 *at0MB+radius+radius)$

Page 20: DATA TYPES IN JAVA.doc

7/23/2019 DATA TYPES IN JAVA.doc

http://slidepdf.com/reader/full/data-types-in-javadoc 20/36

r4r.co.in/java/corejava/topics/basics/13java_Array_contd1.shtml`

,,,,,

@ No%-Stati1 I%%er+3e3=er, Classes " *here is a very little di""erence between thestatic inner classes and non5static inner classes# but in terms o" their "unctionalities bothare very di""erent. 'n java each instance o" the inner class is implicitly associated with aninstance o" its enclosing class which allows the inner class to directly access the non5static member variables and "unctions o" its enclosing class. A non5static inner classmaintains a re"erence to its enclosing class# an instance o" a non5static inner class can not be created unless there is an instance o" the enclosing class. 'nstances o" the inner classmaintain a re"erence to their enclosing instance which is assigned automatically uponobject creation. '" your member class doesnBt reCuire access to the enclosing instancema)e it static to save resources. ecause a non5static inner class cannot e<ist without anenclosing classBs instance it is very rare to see non5static inner classes that arenBt privateor pac)age protected. tatic member classes are "reCuently declared public. *he synta<and usage o" non5static inner classes can be shown via the "ollowing code snippet#

Java Tutorialslass NonStaticBnnerExample{  public static void main(String args[])  {  ne5 9ddition()sum()$ .. creating t0e obIect of9ddition class and calling sum met0od on it  ne5 9ddition()ne5 9ddition"()sum()$ .. creating t0eobIect of 9ddition" class using t0e obIect of

9ddition classint d!ne5 9ddition()a$ .. storingvalue of a in d  int e!ne5 exem()ne5 9ddition"()c$ .. storing value ofc in e  S'stemoutprintln(t0e value of a in outer class is4*d)$..printing values of d and e  S'stemoutprintln(t0e value of c in inner class is4*e)$  ,,Java Tutorialslass 9ddition .. enclosing ortop level class{  int a!"#$

  int b!%#$  void sum()  {  S'stemoutprintln(t0e sum of t5o numbers in enclosing class is4*(a*b))$  ,  Java Tutorialslass 9ddition" .. NonKStaticmember class  {

Page 21: DATA TYPES IN JAVA.doc

7/23/2019 DATA TYPES IN JAVA.doc

http://slidepdf.com/reader/full/data-types-in-javadoc 21/36

r4r.co.in/java/corejava/topics/basics/13java_Array_contd1.shtml`

  int Java Tutorials!D#$  void sum()  {

S'stemoutprintln(T0e sum of t0ree numbers in inner classis 4*(a*b*c))$  ,  ,,

@ Lo1al Classes " A local class is a class that is de"ined within a bloc) o" Java code. Alocal class is declared inside a method body while member classes are declared inside aclass. 't is only accessible only to the method in which it is declared# which ma)es localclasses less generally use"ul than non5static inner classes. Ohile local classes are probably most "reCuently de"ined within methods and constructors# they can also bede"ined inside static initialiFer bloc)s and instance initialiFers. ince an object o" a localclass must be internally lin)ed to an object o" the enclosing class#there"ore object o" the

local class cannot e<ist in the absence o" an object o" the enclosing class# thus a localclass is truly an inner class.

*he most important bene"it o" using local classes has to do with accessing the memberso" enclosing classes. Just li)e with member classes# methods o" a local class have directaccess to all the members o" the enclosing classes# including private members. *hus# theuse o" local classes may eliminate the reCuirement to connect objects together viaconstructor parameters. *he methods in a local class can access local variables andmethod parameters only i" they are declared "inal. As with local variables# local classescannot be declared public# protected# private# or static. (ollowing code will show thesynta< o" local classes.

Java Tutorialslass S0ape .. top class{ int i!@$Java Tutorialslass Lectangle .. member class {  int a!"#$ .. ta6en a variable a  int lengt0$  int breadt0$  public Lectangle(int lengt02 int breadt0) .. constructordeclaration for Lectangle class  {  t0islengt0!lengt0$  t0isbreadt0!breadt0$  ,  public void 9rea() .. defined a met0od 9rea()2 in50ic0 5e defined a local class ;ircle  {  S'stemoutprintln(T0e area of rectangle is 4*lengt0+breadt0)$ 

Java Tutorialslass Java Tutorialsircle..local class declaration

Page 22: DATA TYPES IN JAVA.doc

7/23/2019 DATA TYPES IN JAVA.doc

http://slidepdf.com/reader/full/data-types-in-javadoc 22/36

r4r.co.in/java/corejava/topics/basics/13java_Array_contd1.shtml`

  {  int radius$  int '!%D$  public Java Tutorialsircle(int radius) .. constructor oflocal class  {  t0isradius!radius$  ,  public void 9rea() ..met0od 9rea defined in local class  {  S'stemoutprintln(T0e area of circle is4*at0MB+radius+radius)$ ..printing area of circle  S'stemoutprintln(T0e value of a is given b' 4*a)$.. printing t0e valueof a and i defined in Lectangle and s0ape  S'stemoutprintln(T0e value of i is given b' 4*i)$.. 50ic0 s0o5s local classes 0ave access to members of enclosing class

, .. closing

9rea() met0od  , .. closinglocal class ;irclefinal Java Tutorialsircle obI!ne5 Java Tutorialsircle(D)$ ..creating obIect of ;ircle classobI9rea()$ .. calling 9rea() met0odS'stemoutprintln(T0e class pat0 of enclosing class is givenb' 4*get;lass()getName())$ ..printingt0e class name for Lectangle classS'stemoutprintln(T0e class pat0 is givenb' 4*obIget;lass()getName())$ ..printingt0e class name for local class ;ircleS'stemoutprintln(T0e value of a declared in Lectangle is givenb' 4*Lectanglet0isa)$ ..printing t0evalue of variable a defined in class,,,

Java Tutorialslass man% .. controllingclass{  public static void main(String args[])  {  ne5 S0ape()ne5 Lectangle(72@)9rea()$ ..invo6ing 9rea()met0od defined in class Lectangle, ..b' associating

its obIect 5it0 top class S0ape,

@ A%o%3ous Classes " Anonymous classes in the Java programming language are

the classes without names thus# we can say# an anonymous class is essentially a local

Page 23: DATA TYPES IN JAVA.doc

7/23/2019 DATA TYPES IN JAVA.doc

http://slidepdf.com/reader/full/data-types-in-javadoc 23/36

r4r.co.in/java/corejava/topics/basics/13java_Array_contd1.shtml`

class without a name. *he main advantage o" using an anonymous class is -ncapsulation.An anonymous class is# in a way# the ultimate in private object oriented encapsulation. 'tis de"ined e<actly where it is needed# it can never be used anywhere else# and it is havinga total local scope. Anonymous classes provide a very clear synta< "or implementingevent listeners in 0[' programming# and are very much use"ul "or implementing method

 parameters and returning objects.

!ne o" the )ey advantages o" using anonymous classes is that it relieves the programmer"rom de"ining large numbers o" special purpose classes. uch classes are used only onceand are de"ined right where the action is ta)ing place# and never used again. Also#anonymous classes have access to all data and methods o" their containing classes#including private members which means that "or small highly localiFed tas)s# theygenerally need less initialiFation. *he synta< o" anonymous classes have one o" the two"orms which are shown below &

1. 'nter"ace ased & *he synta< "or declaring inter"ace based anonymous class is given as#

  new 'nter"ace%ame2  U  // =lassody  V

An inter"ace based anonymous class has to implement the entire inter"ace on which it is based upon# to understand it better# ta)e a loo) at the "ollowing code snippet &

Java Tutorialslass 9non'mous;lassExample{

 public static void main(String args[])  {  Lunnable obI ! ne5 Lunnable() .. anon'mous class isdefined 0ere  {  private static final int 9LL9ABBT !@#$  private int[] arr ! ne5 int[9LL9ABBT]$  .. instance intialiOation code  {  for(int i!#$ iC arrlengt0$ i**)  arr[i] ! i$  ,  public void run()  {  int sum ! #$  for(int i!#$ iC9LL9ABBT$ i**)  sum ! sum * arr[i]$  S'stemoutprintln(T0e sum of t0earra' elements is 4*sum)$ .. printing t0e sum of arra'  ,

,$ .. anon'mous class ends 0ere

Page 24: DATA TYPES IN JAVA.doc

7/23/2019 DATA TYPES IN JAVA.doc

http://slidepdf.com/reader/full/data-types-in-javadoc 24/36

r4r.co.in/java/corejava/topics/basics/13java_Array_contd1.shtml`

  obIrun()$  ,,

$. =lass ased Anonymous =lass & *he synta< "or class based anonoymous class is#

new =lass%ame 2optional Argument_?istU// =lass odyV

A class based anonymous class has access to its base class methods and members and itcan override itZs members# just li)e any other subclass. *o understand more ta)e a loo) atthis code snippet#

Java Tutorialslass 9non'mous;lassExample%

{  S0o5essage anon'mousobI ! ne5 S0o5essage(L7L Example)  {

  public void displa'()  { 

S'stemoutprintln(anon'mous override*member displa' S0o5essageutput 4*msg)$

  ,,$

 

public 9non'mous;lassExample%(){

 S0o5essage obI ! ne5 S0o5essage(0iPPPPPP)$ obIdispla'()$S0o5essage anon'mousobI% !ne5 S0o5essage(0iPPPPPPP)

{ public void

displa'(){

 S'stemoutprintln(anon'mous override*local displa' S0o5essageoutput 4*msg)$

,,$

anon'mousobI%displa'()$

t0isanon'mousobIdispla'()$,public static void main(String args[]){9non'mous;lassExample% example ! ne5 9non'mous;lassExample%()$

,,Java Tutorialslass S0o5essage{

Page 25: DATA TYPES IN JAVA.doc

7/23/2019 DATA TYPES IN JAVA.doc

http://slidepdf.com/reader/full/data-types-in-javadoc 25/36

r4r.co.in/java/corejava/topics/basics/13java_Array_contd1.shtml`

String msg!$public S0o5essage(String msg){t0ismsg!msg$,public void displa'(){S'stemoutprintln(Simple;lass output 4*msg)$,,

'5at are a11ess 3o2iiers i% 7ava Access modi"iers determines the accessibility scope o" the Java elements that are beingmodi"ied. '" we not e<plicitly use an access modi"ier with a Java element# the elementimplicitly has the de"ault access modi"ier. *he e<plicit access modi"iers may be used witha class and its members. *hey cannot be used with the variables inside a method.*he Java has three e<plicit access modi"iers viF. public# private and protected# and alsohas a de"ault modi"ier# which is used when you do not e<plicitly speci"y a modi"ier.

u=li1 3o2iier " *he public modi"ier ma)es an element most visible# it can be appliedto various classes and their members 2instance variable and methods@ *he elementsdeclared public can be accessed "rom anywhere in the java application. *hat is why youdeclare the main method o" any application public so that it may be invo)ed "rom anyJava runtime environment. *he synta< "or declaring and using public modi"iers within java program can be shown as&

Java Tutorialslass odifier=emo{ public int i$

 public odifier=emo(int i){

  t0isi!i$ S'stemoutprintln(t0e value of i is 4*i)$

  ,,

Java Tutorialslass Mublicodifier{

public static void main(String[] args){

odifier=emo obI!ne5 odifier=emo("#)$

,,

rivate 3o2iier " *he private modi"ier is used to ma)e a java element least visible. *he private modi"ier cannot be used "or a top5level class# and can be applied only to themembers o" a top5level class viF. instance variables# methods. A private member o" aclass can only be accessed "rom the code inside the same class in which this member is

Page 26: DATA TYPES IN JAVA.doc

7/23/2019 DATA TYPES IN JAVA.doc

http://slidepdf.com/reader/full/data-types-in-javadoc 26/36

r4r.co.in/java/corejava/topics/basics/13java_Array_contd1.shtml`

declared. 't cannot be accessed "rom any other class or "rom a subclass o" the class inwhich it is declared*he code snippet shows the synta< "or using private modi"ier#

Java Tutorialslass odifier=emo {

 private int i!"#$ public int I!@$ ,

Java Tutorialslass Mublicodifier{

public static void main(String[] args){

odifier=emo obI!ne5 odifier=emo()$  S'stemoutprintln(T0e value of i is 4*obIi)$ .. cause

a compile error as i/s defined privateS'stemoutprintln(T0e value of I is 4*obII)$ ..

print t0e value of I !@

,,

*he accessibility o" i have been )ept private so we canBt directly access it merely bycreating the object o" the class in which it is de"ined# so it will cause a compiler error# buti" we comment out this line "rom prog. then we will get the value o" jG; as output.

rote1te2 3o2iier " *he protected modi"ier ma)es a class member more visible than private modi"ier but less accessible than public modi"ier. *his modi"ier may be appliedonly to class members viF. variables# methods# and inner classesbut not to the classitsel". A class member declared protected is visible to the "ollowing elements&1.*he classes in the same pac)age that contains the class that owns the protected member.$.*he subclasses o" the class that owns the protected member. *hese subclasses haveaccess even i" they are not in the same pac)age as the parent class.

*he usage o" protected modi"ier can be shown as#

Java Tutorialslass odifier=emo { private int i!"#$ protected int I!@$ ,

Java Tutorialslass Mublicodifier extends odifier=emo{

public static void main(String[] args){

Mublicodifier obI!ne5 Mublicodifier()$  S'stemoutprintln(T0e value of i is 4*obIi)$ .. cause

a compile error as i/s defined private

Page 27: DATA TYPES IN JAVA.doc

7/23/2019 DATA TYPES IN JAVA.doc

http://slidepdf.com/reader/full/data-types-in-javadoc 27/36

r4r.co.in/java/corejava/topics/basics/13java_Array_contd1.shtml`

S'stemoutprintln(T0e value of I is 4*obII)$ ..print t0e value of I !@2 as I is declared protected

,,

2eault 3o2iier " 'n java we cannot speci"y any modi"ier "or the variables inside a

method# and also we cannot speci"y the protected modi"ier "or a class. Ohen we do notspeci"y any access modi"ier "or an element# it is implied that the access is de"ault. 't can be applied to a class# a variable# or a method. A class or a class member declared de"aulti.e. with no access modi"ier speci"ied is accessible "rom anywhere in the same pac)age inwhich the accessed class e<ists. =onsider the "ollowing code "ragment&

pac6age example$Java Tutorialslass S0o5Example {private int i!"#$

 void S0o5(){ S'stemoutprintln(T0e value of i is 4*i)$,,

Above code contains a method o" de"ault modi"ier show returning void# and it iscontained in a pac)age called e<ample.

pac6age example%$Java Tutorialslass Levie5Example extends S0o5Example{

S0o5()$ .. 5ill cause compiler error,

*he how2 method called in class eview-<ample causes a compiler error# as how2method is declared de"ault in how-<ample which is in a totally di""erent pac)age and#it is obvious that a de"ault method cannot be accessed "rom a di""erent pac)age other thanin which it is de"ined.

'5at are !sa<e #o2iiers i% 7ava 'n java there are some modi"iers that are not access modi"iers# still they can modi"y theway a class or a class member is to be used# we call such modi"iers the usage modi"iers.

(ollowing are usage modi"iers used in java &

:@ T5e i%al #o2iier " *he "inal modi"ier can be applied to a class# a method or avariable. 'n general i" the an element declared "inal# is a variable# it means that the valueo" the variable is constant# and cannot be changed. '" a class is declared "inal# it means theclass cannot be inherited# and also the "inal method cannot be overridden. 't can bedeclared as#

Page 28: DATA TYPES IN JAVA.doc

7/23/2019 DATA TYPES IN JAVA.doc

http://slidepdf.com/reader/full/data-types-in-javadoc 28/36

r4r.co.in/java/corejava/topics/basics/13java_Array_contd1.shtml`

"inal int i G ;E"inal double d G $.;Ethe above declaration tell us that the values o" i and d will remain constant throughoutthe course o" the program and cannot be changed. (or understanding the "inal modi"ier interms o" classes and methods# consider the "ollowing code snippet#

Java Tutorialslass S0o51inal{ private final int i!"#$ void Java Tutorialsalculate(int i){S'stemoutprintln(T0e value of i is4*i)$,,Java Tutorialslass 1inalExample{public static void main(String args[]){

 final S0o51inal obI!ne5 S0o51inal()$..obIi!D$ ..compilation error as value of i is final can/t bec0angedobI;alculate("#)$,,

@ T5e stati1 #o2iier " *he static modi"ier can be applied to variables# methods# and a bloc) o" code inside a method. *he static elements o" a class are visible to all theinstances o" that class. *hus# i" one instance o" the class ma)es a change to a staticelement# all the instances will see that change. A static variable belongs to the class# notto a speci"ic instance o" the class# there"ore# is initialiFed when the class is loaded. A

static variable may be re"erenced by an instance o" the class in which it is declared or bythe class name itsel". (or better understanding# consider the "ollowing code snippet#

Java Tutorialslass Staticodifier{ static int staticcounter!#$ int Java Tutorialsounter !#$ public Staticodifier(){staticcounter**$S'stemoutprintln(T0e value of static counter is 4*staticcounter)$Java Tutorialsounter**$S'stemoutprintln(T0e value of normal counter is 4*counter)$

,, Java Tutorialslass StaticodifierExample{public static void main(String args[]){ Staticodifier obI!ne5 Staticodifier()$ .. staticcounter value!"2counter !"

Page 29: DATA TYPES IN JAVA.doc

7/23/2019 DATA TYPES IN JAVA.doc

http://slidepdf.com/reader/full/data-types-in-javadoc 29/36

r4r.co.in/java/corejava/topics/basics/13java_Array_contd1.shtml`

 Staticodifier obI"!ne5 Staticodifier()$ .. staticcounter value!%2counter !"..Since t0e modifier of staticcounter is static2 50ic0 is available toall t0e instances of t0e class2.. t0e c0ange in value of staticcounter in an' of t0e instance 5ill bereflected in ot0er instances.. 50ile t0e counter value 5ill remain constant 50enever an' instanceis created as it is not declared static,,

Just li)e a static variable# a static method also belongs to the class in which it is de"inedand not to a speci"ic instance o" the class. *here"ore# a static method can only access thestatic members o" the class. 'n other words# a method declared static in a class cannotaccess the non5static variables and methods o" the class. ecause a static method does not belong to a particular instance o" the class in which it is de"ined# it can be called even be"ore a single instance o" the class e<ists. (or e<ample# every Java application has amethod main2# which is the entry point "or the application e<ecution. 't is e<ecutedwithout instantiating the class in which it e<ists. *his can be e<plained by the "ollowing

e<ample#Java Tutorialslass StaticodifierExample%{static int a!"#$static int b!%#$ static void sum()

{S'stemoutprintln(T0e value of sum of t5o numbers is 4*(a*b))$,public static void main(String args[]){ sum()$ .. static met0od is called before instantiating an'obIect of StaticodifierExample%,,

@ T5e a=stra1t #o2iier " *he abstract modi"ier may be applied to a class or a method# but not to a variable. A class which is declared abstract cannot be instantiated .i.e. itsobject cannot be created because it is not "ully implemented. *here is a relationship between an abstract class and an abstract method which is# i" a class has one or moreabstract methods# it must be declared abstract. A class may de"ine abstract methods in anyo" the "ollowing ways&1. A class may have one or more abstract methods de"ined in it.$. A class might have inherited one or more abstract methods "rom its superclass# and has

not provided implementation "or all or some o" them.3. A class declares that it implements an inter"ace# but does not provide implementation"or at least one method in the inter"ace.'n above shown cases# the class must be declared abstract.ut# i" there is no abstractmethod in the class# it could still be declared abstract but in this case the class cannot beinstantiated.

(ollowing code snippet will give a good idea about the abstract modi"ier#

Page 30: DATA TYPES IN JAVA.doc

7/23/2019 DATA TYPES IN JAVA.doc

http://slidepdf.com/reader/full/data-types-in-javadoc 30/36

r4r.co.in/java/corejava/topics/basics/13java_Array_contd1.shtml`

abstract class S0ape .. declaring an abstract class{ abstract void 9rea()$ .. an abstract met0od 5it0 no bod' void Mrintan't0ing() .. a simple met0od  {  S'stemoutprintln(0elloPP S0as0i ;0aud0ar' Q r7r)$  ,,Java Tutorialslass Lectangle extends S0ape .. defined a class50ic0 is in0eriting S0ape class{int lengt0$int breadt0$ Lectangle(int lengt02 int breadt0)  {  t0islengt0!lengt0$  t0isbreadt0!breadt0$  , void 9rea() .. implementing t0e 9rea() met0od

defined in S0ape class {  S'stemoutprintln(T0e area of rectangle is given b' 4*(lengt0+breadt0))$ .. displa'ing area of rectangle ,,Java Tutorialslass Java Tutorialsircle extends S0ape{  int radius$  Java Tutorialsircle(int radius)  {

  t0isradius!radius$  ,void 9rea() .. Bmplementing t0e 9rea() met0oddefined in class S0ape {  S'stemoutprintln(T0e area of circle is given b' 4*(at0MB+radius+radius))$ .. displa'ing area of circle ,,Java Tutorialslass 9bstractodifierExample{ public static void main(String args[]) {  .. S0ape s0p ! ne5 S0ape()$ .+ 5ill cause compilation error as S0apeis defined abstract

  Lectangle obIrect ! ne5 Lectangle(D2@)$  Java Tutorialsircle obIcirc ! ne5 Java Tutorialsircle(D)$  obIrect9rea()$  obIcirc9rea()$  obIcircMrintan't0ing()$ .. accessing t0e met0od definedin class S0ape t0roug0 ;ircle/s instance  obIrectMrintan't0ing()$ .. accessing t0e met0od defined inclass S0ape t0roug0 Lectangle/s instance ,,

Page 31: DATA TYPES IN JAVA.doc

7/23/2019 DATA TYPES IN JAVA.doc

http://slidepdf.com/reader/full/data-types-in-javadoc 31/36

r4r.co.in/java/corejava/topics/basics/13java_Array_contd1.shtml`

A abstract class is some what opposite to the "inal class. A "inal class cannot be e<tendedor inherited# whereas an abstract class must be e<tended# be"ore it can be instantiated. Anabstract class or an abstract method means itZs not "ully implemented .i.e i" you want touse it# you have to implement it.

@ T5e %ative #o2iier " 'n java applications# sometimes we will want to use a methodthat e<ists outside the J. 'n this scenario# the native modi"ier can help# native modi"ier can only apply to a method. Just as the abstract )eyword# the native )eyword indicatesthat the implementation o" the method e<ists elsewhere. 'n case o" abstract# theimplementation o" a method may e<ist in a subclass o" the class in which the abstractmethod is declared.ut in the case o" native# the implementation o" the method e<ists in a library outside theJ. *he native method is usually implemented in a non5Java language such as = or =>>. e"ore a native method can be invo)ed# a library that contains the method must beloaded and that library is loaded by ma)ing the "ollowing system call&

ystem.load?ibrary2Ilibrary%ameIE

*o declare a native method# precede the method with the native modi"ier# but do notde"ine any body "or the method. (or e<ample&

 public native void %ativemethod2 E

A"ter you declare a native method# you must write the native method and "ollow acomple< series o" steps to lin) it with your Java code. (or e<ample# the "ollowing code"ragment presents an e<ample o" loading a library named %ativeethode" whichcontains a method named %ativeethod2&

Java Tutorialslass NativeodifierExample{

  native void Nativeet0od()$  static

{  S'stemloadAibrar'(Nativeet0od=ef)$  ,  ,

 %ote that the library is loaded in a static code bloc) which suggest that the library isloaded at the class load time# so it is there when a call to the native method is made. !necan use the native method in the same way as we use a non5native method. (or e<ample#

the "ollowing two lines o" code would invo)e the native method#

NativeodifierExample obI ! ne5 NativeodifierExample()$obINativeet0od()$

@ T5e tra%sie%t #o2iier " 'n an java based application# while is in running mode# theobjects are put in the random access memory 2A o" the computer.*hat determines thescope and li"e o" the object. owever# i" an object may be stored in persistent storage

Page 32: DATA TYPES IN JAVA.doc

7/23/2019 DATA TYPES IN JAVA.doc

http://slidepdf.com/reader/full/data-types-in-javadoc 32/36

r4r.co.in/java/corejava/topics/basics/13java_Array_contd1.shtml`

outside the J# "or later use by the same application or by some another application.*he process o" storing an object is called serialiFation. (or an object to be serialiFable#the corresponding class must implement the inter"ace erialiFable. *hus# the transientmodi"ier is related to storing an object in persistant storage. uch storage is called theobjectZs persistent state. A variable declared transient is not stored# and hence does not

 become part o" the objectZs persistent state.*he transient modi"ier can be used to preventa security5sensitive piece o" data "rom copying to a source where there is no securitymechanism e<ists.*he transient modi"ier can only be applied to instance variables. Ohen you are declaringan instance variable transient# you are telling the Java irtual achine not to store thisvariable when the object# in which it is declared# is serialiFed. *hus# when an instancevariable is declared as transient# then its value need not persist when an object is stored.(or e<ample#

Java Tutorialslass Transientodifier{

  transient int num"$ .. variable 5ill not persist

 int num%$ .. variable 5ill persist,

@ T5e volatile #o2iier " 'n java the volatile modi"ier only applies to instance variables just li)e the transient modi"ier. *he variables declared volatile are subject toasynchronous modi"ications. *hus we can say that# declaring a variable volatile tells thecompiler that this variable might be changed une<pectedly by other parts o" the program.o# the compiler ta)es some special precautions to )eep this variable properly updated#volatile variables are generally used in multithreaded or multiprocessor environments.*he volatile modi"ier tells the accessing thread that it should synchroniFe its private copyo" the variable with the original copy in the memory. =onsider the "ollowing e<ample "or

the better understanding#

Java Tutorialslass Rolatileodifier extends T0read  {  private volatile static int someRal$ .. declared a volatilevariable  Rolatileodifier(String str)  {  super(str)$  ,  public void run() .. implementing t0e run met0od fort0reads  {  for (int I!#$ ICD$ I**)  {  tr'  {  S'stemoutprintln(getName() * K3*i)$  if(getName()e-uals(r7r t0read"))  {  someRal!D$  ,  if(getName()e-uals(r7r t0read%))

Page 33: DATA TYPES IN JAVA.doc

7/23/2019 DATA TYPES IN JAVA.doc

http://slidepdf.com/reader/full/data-types-in-javadoc 33/36

r4r.co.in/java/corejava/topics/basics/13java_Array_contd1.shtml`

  {  S'stemoutprintln(T0e value of volatile variableis 4*someRal)$  ,  T0readsleep(%###)$  ,

Java Tutorialsatc0(BnterruptedException e)  {  eprintStac6Trace()$  ,

,

,

Java Tutorialslass RolatileodifierExample{public static void main(String args[]){T0read t!ne5 Rolatileodifier(r7r t0read")$ .. creating a t0readobIect

T0read t"!ne5 Rolatileodifier(r7r t0read%)$tstart()$ .. starting t0eexecution of t0readt"start()$,,

@ T5e s%15ro%ie2 #o2iier " *he synchroniFed modi"ier is used in multithreaded programming to control access to critical sections in the program. *he synchroniFed)eyword used to indicate that a method can be accessed by only one thread at a time. *hesynchroniFed modi"ier is generally used mainly in threading environment. Oe willdiscuss about it in detail in threading. 'ts declarative synta< is#public s'nc0roniOed void 9n'met0od()

{  .. some logic  ,

'5at is Gar=a<e Colle1tio% i% 7ava An application running on a system computer uses some memory# which ma)es memorymanagement a signi"icant issue "or any programming language. As Java is comparativelyhigh5level language# the memory management in Java is automatic. *o ma)e it moree""icient# we need to understand garbage collection# i.e. "reeing memory "rom objects thatare no longer in use.Gar=a<e 1olle1tio% is the process o" automatically "reeing objects that are no longer

re"erenced by the program. *his "rees a programmer "rom having to )eep trac) o" whento "ree allocated memory# thus preventing many potential bugs and problems.

'5at is a Gar=a<e Colle1tor Ohen we create an object by instantiating a class# the object is put on the heap# that is# ituses some memory. A Java application creates and uses objects. A"ter an object inmemory has been used and is no longer needed# it is sensible to "ree memory "rom thatobject.*he 0arbage =ollector in Java initiates the memory management by "reeing up the

Page 34: DATA TYPES IN JAVA.doc

7/23/2019 DATA TYPES IN JAVA.doc

http://slidepdf.com/reader/full/data-types-in-javadoc 34/36

r4r.co.in/java/corejava/topics/basics/13java_Array_contd1.shtml`

memory "rom objects that are no longer re"erenced. *he importance o" this is that you donot need to code the memory management into your application program# also you haveno control over when the garbage collector runs. Ohile coding in some application wecan do "ollowing things in order to help the memory management through the garbagecollector &

1. (irstly# ma)e an object eligible "or the garbage collection# as garbage collector willonly "ree memory "rom an eligible object.$. Also ma)e a reCuest "or garbage collection by ma)ing a system call to the garbagecollector via# ystem.gc2E.

Oe can also invo)e the gc2 method by using an instance o" the untime class that arunning program always has. 't is contained in java.lang pac)age# we can get hold o" thisinstance by calling the static method getuntime2 o" the untime class. *he "ollowinge<ample will show how we can invo)e gc2 method via untime class and some otherruntime tas)s#

Java Tutorialslass garc{  public static void main(String args[])  {  Luntime runtimeobIect ! LuntimegetLuntime()$ .. creating anobIect of Luntime class  .. t0is statement returns t0e total memor' available in b'tes toIvm  S'stemoutprintln(T0e value of total memor' of Ivmis 4*runtimeobIecttotalemor'())$

.. t0is statement returns t0e free memor' available in b'tes to Ivm  S'stemoutprintln(T0e value of free memor' availabe to Ivmis 4*runtimeobIectfreeemor'())$

runtimeobIectgc()$ .. calling gc met0od on Luntime obIect

  S'stemoutprintln(T0e amount of memor' allocated to Ivm aftercalling gc is 4*runtimeobIectfreeemor'())$

  ,,

't should be noted that a call to the garbage collector gives no guarantee that the memorywill be "ree. *here can be a situation that the J in which your program is running didnot even implement the gc2 method. *he Java language also allows a dummy gc2method# the basic reCuirement "or garbage collection is that you must ma)e your objecteligible "or garbage collection. An object is considered eligible "or garbage collection i"there is no re"erence pointing to it. Oe can remove the re"erences to an object in two

ways&1. y setting the object re"erence variable pointing to the object to null# such as#0=class object G new 0=class2Eobject G nullE$. econdly by reassign a re"erence variable o" an object to another object i.e. i" are"erence variable object is pointing to an object o" the 0=class# you can "ree this object"rom this re"erence by pointing the re"erence to another object by the "ollowing statementmy!bject G new 0=$class2E

Page 35: DATA TYPES IN JAVA.doc

7/23/2019 DATA TYPES IN JAVA.doc

http://slidepdf.com/reader/full/data-types-in-javadoc 35/36

r4r.co.in/java/corejava/topics/basics/13java_Array_contd1.shtml`

 %ow# the object re"erence 0=object is pointing to an object o" the class 0=$class and notto an object o" 0=class# to which it was pointing earlier.

'n java i" an object has no object re"erences pointing to it# can be deleted by the garbage

collector to regain the memory. !n the other hand# i" an object has a "inaliFe2 methodthen it will be e<ecuted be"ore regaining the memory in order to give the object a lastchance to clean up itsel" i.e. to release all the resources that the object was using. *he"inaliFe2 method is inherited "rom the !bject class by any class you de"ine. *he synta<o" the "inaliFe2 method declaration is shown below#

 protected void "inaliFe2

'nside this "inaliFe2 method you must speci"y the actions that are needed to be per"ormed be"ore an object is recycled. *he "inaliFe2 is only called just prior to garbage collectionto i" any resource was le"t to be released .'t is advised that not use "inaliFe2 method just

to be on a sa"er side. *he program must release the resources in program itsel"# sincegarbage collectors run is not guaranteed# so "inaliFe2 e<ecution will also not beguaranteed. *he Java programming language speci"ies that the "inaliFe2 method will becalled be"ore the object memory is reclaimed# but it does not guarantee e<actly when itwill happen. %ote that the "inaliFe2 method which a class inherited does not doanything#thus# i" you want your object to clean up itsel"# you have to override the"inaliFe2 method. Also remember that# the "inaliFe2 method is never invo)ed more thanonce by a Java virtual machine "or any given object. 0enerally# it is considered a good programming practice to invo)e the "inaliFe2 o" the superclass# i.e.#

 protected void "inaliFe2

Usuper ."inaliFe2E// some other logicV

*he "ollowing code snippet will guide you how to use "inaliFe2 method during thegarbage collection#

Java Tutorialslass Using1inaliOe{

  public static void main(String[] args)

{  Luntime rt ! LuntimegetLuntime()$  S'stemoutprintln(Total availablememor'4*rttotalemor'())$  S'stemoutprintln(9vailable 1ree emor'4 *rtfreeemor'())$  for(int I!#$ IC"###$ I** )

{  1inaliOeet0od obI ! ne5 1inaliOeet0od(I)$

,

Page 36: DATA TYPES IN JAVA.doc

7/23/2019 DATA TYPES IN JAVA.doc

http://slidepdf.com/reader/full/data-types-in-javadoc 36/36

r4r.co.in/java/corejava/topics/basics/13java_Array_contd1.shtml`

  S'stemoutprintln(1ree emor' before call to gc()4 *rtfreeemor'())$

  S'stemrun1inaliOation()$  S'stemgc()$  S'stemoutprintln( 1ree emor' after call to gc()4 *

rtfreeemor'())$

,,

Java Tutorialslass 1inaliOeet0od{

  String str$  int id$  1inaliOeet0od(int id)

{  t0isstr ! ne5 String(r7r tefsoft solutions)$

t0isid ! id$  ,

  protected void finaliOe()  {

  S'stemoutprintln(1inaliOeet0od obIect * id * 0as beenfinaliOed)$  ,

  ,