0% found this document useful (0 votes)
346 views7 pages

Understanding Java Static Keyword

The document discusses the static keyword in Java. It explains that static can be used with variables, methods, blocks, and nested classes. Static variables and methods belong to the class rather than objects, and static blocks are used to initialize static variables. It provides examples of using static with variables, methods, and blocks.

Uploaded by

Amália Eirez
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
346 views7 pages

Understanding Java Static Keyword

The document discusses the static keyword in Java. It explains that static can be used with variables, methods, blocks, and nested classes. Static variables and methods belong to the class rather than objects, and static blocks are used to initialize static variables. It provides examples of using static with variables, methods, and blocks.

Uploaded by

Amália Eirez
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

9/10/2015

StatickeywordinJavaJavatpoint

Javastatickeyword
[Link]
keywordwithvariables,methods,[Link]
classthaninstanceoftheclass.
Thestaticcanbe:
1. variable(alsoknownasclassvariable)
2. method(alsoknownasclassmethod)
3. block
4. nestedclass

1)Javastaticvariable
Ifyoudeclareanyvariableasstatic,itisknownstaticvariable.
Thestaticvariablecanbeusedtoreferthecommonpropertyofallobjects(thatisnot
uniqueforeachobject)[Link],collegenameofstudentsetc.
Thestaticvariablegetsmemoryonlyonceinclassareaatthetimeofclassloading.

Advantageofstaticvariable
Itmakesyourprogrammemoryefficient([Link]).

Understandingproblemwithoutstaticvariable
.

classStudent{

introllno

Stringname

Stringcollege="ITS"

}
Supposethereare500studentsinmycollege,nowallinstancedatamemberswillgetmemory
[Link]
[Link],[Link]
static,thisfieldwillgetmemoryonlyonce.

Javastaticpropertyissharedtoallobjects.

Exampleofstaticvariable
.

//Programofstaticvariable

data:text/htmlcharset=utf8,%3Ch1%20class%3D%22h1%22%20style%3D%22margintop%3A%205px%3B%20fontfamily%3A%20erdana%2C%20helv

1/7

9/10/2015

StatickeywordinJavaJavatpoint

classStudent8{

introllno

Stringname

staticStringcollege="ITS"

Student8(intr,Stringn){

rollno=r

name=n

voiddisplay(){[Link](rollno+""+name+""+college)}

publicstaticvoidmain(Stringargs[]){

Student8s1=newStudent8(111,"Karan")

Student8s2=newStudent8(222,"Aryan")

[Link]()

[Link]()

}
TestitNow
Output:111KaranITS
222AryanITS

data:text/htmlcharset=utf8,%3Ch1%20class%3D%22h1%22%20style%3D%22margintop%3A%205px%3B%20fontfamily%3A%20erdana%2C%20helv

2/7

9/10/2015

StatickeywordinJavaJavatpoint

Programofcounterwithoutstaticvariable
Inthisexample,wehavecreatedaninstancevariablenamedcountwhichisincrementedinthe
[Link],eachobject
willhavethecopyoftheinstancevariable,ifitisincremented,itwon'treflecttootherobjects.
Soeachobjectswillhavethevalue1inthecountvariable.
.

classCounter{

intcount=0//willgetmemorywheninstanceiscreated

Counter(){

count++

[Link](count)

publicstaticvoidmain(Stringargs[]){

Counterc1=newCounter()

Counterc2=newCounter()

Counterc3=newCounter()

data:text/htmlcharset=utf8,%3Ch1%20class%3D%22h1%22%20style%3D%22margintop%3A%205px%3B%20fontfamily%3A%20erdana%2C%20helv

3/7

9/10/2015

StatickeywordinJavaJavatpoint

}
TestitNow
Output:1
1
1

Programofcounterbystaticvariable
Aswehavementionedabove,staticvariablewillgetthememoryonlyonce,ifanyobject
changesthevalueofthestaticvariable,itwillretainitsvalue.
.

classCounter2{

staticintcount=0//willgetmemoryonlyonceandretainitsvalue

Counter2(){

count++

[Link](count)

publicstaticvoidmain(Stringargs[]){

Counter2c1=newCounter2()

Counter2c2=newCounter2()

Counter2c3=newCounter2()

}
TestitNow
Output:1
2
3

2)Javastaticmethod
Ifyouapplystatickeywordwithanymethod,itisknownasstaticmethod.
Astaticmethodbelongstotheclassratherthanobjectofaclass.
Astaticmethodcanbeinvokedwithouttheneedforcreatinganinstanceofaclass.
data:text/htmlcharset=utf8,%3Ch1%20class%3D%22h1%22%20style%3D%22margintop%3A%205px%3B%20fontfamily%3A%20erdana%2C%20helv

4/7

9/10/2015

StatickeywordinJavaJavatpoint

staticmethodcanaccessstaticdatamemberandcanchangethevalueofit.

Exampleofstaticmethod
.

//Programofchangingthecommonpropertyofallobjects(staticfield).

classStudent9{

introllno

Stringname

staticStringcollege="ITS"

staticvoidchange(){

college="BBDIT"

Student9(intr,Stringn){

rollno=r

name=n

voiddisplay(){[Link](rollno+""+name+""+college)}

publicstaticvoidmain(Stringargs[]){

[Link]()

Student9s1=newStudent9(111,"Karan")

Student9s2=newStudent9(222,"Aryan")

Student9s3=newStudent9(333,"Sonoo")

[Link]()

[Link]()

[Link]()

}
TestitNow
Output:111KaranBBDIT
222AryanBBDIT
333SonooBBDIT

Anotherexampleofstaticmethodthatperformsnormalcalculation
data:text/htmlcharset=utf8,%3Ch1%20class%3D%22h1%22%20style%3D%22margintop%3A%205px%3B%20fontfamily%3A%20erdana%2C%20helv

5/7

9/10/2015

StatickeywordinJavaJavatpoint

//Programtogetcubeofagivennumberbystaticmethod

classCalculate{

staticintcube(intx){

returnx*x*x

publicstaticvoidmain(Stringargs[]){

intresult=[Link](5)

[Link](result)

}
TestitNow
Output:125

Restrictionsforstaticmethod
[Link]:
1. Thestaticmethodcannotusenonstaticdatamemberorcallnonstaticmethoddirectly.
2. thisandsupercannotbeusedinstaticcontext.

classA{

inta=40//nonstatic

publicstaticvoidmain(Stringargs[]){

[Link](a)

}
TestitNow
Output:CompileTimeError

Q)whyjavamainmethodisstatic?
Ans)becauseobjectisnotrequiredtocallstaticmethodifitwerenonstaticmethod,jvm
createobjectfirstthencallmain()methodthatwillleadtheproblemofextramemory
allocation.

3)Javastaticblock

data:text/htmlcharset=utf8,%3Ch1%20class%3D%22h1%22%20style%3D%22margintop%3A%205px%3B%20fontfamily%3A%20erdana%2C%20helv

6/7

9/10/2015

StatickeywordinJavaJavatpoint

3)Javastaticblock
Isusedtoinitializethestaticdatamember.
Itisexecutedbeforemainmethodatthetimeofclassloading.

Exampleofstaticblock
.

classA2{

static{[Link]("staticblockisinvoked")}

publicstaticvoidmain(Stringargs[]){

[Link]("Hellomain")

}
TestitNow
Output:staticblockisinvoked
Hellomain

Q)Canweexecuteaprogramwithoutmain()method?
Ans)Yes,oneofthewayisstaticblockbutinpreviousversionofJDKnotinJDK1.7.
.

classA3{

static{

[Link]("staticblockisinvoked")

[Link](0)

}
TestitNow
Output:staticblockisinvoked(ifnotJDK7)

InJDK7andabove,outputwillbe:

Output:Error:MainmethodnotfoundinclassA3,pleasedefinethemainmethodas:
publicstaticvoidmain(String[]args)

data:text/htmlcharset=utf8,%3Ch1%20class%3D%22h1%22%20style%3D%22margintop%3A%205px%3B%20fontfamily%3A%20erdana%2C%20helv

7/7

You might also like