0% found this document useful (0 votes)
243 views

Static Keyword in Java - Javatpoint

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
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
243 views

Static Keyword in Java - Javatpoint

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
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

9/10/2015

StatickeywordinJavaJavatpoint

Javastatickeyword
Thestatickeywordinjavaisusedformemorymanagementmainly.Wecanapplyjavastatic
keywordwithvariables,methods,blocksandnestedclass.Thestatickeywordbelongstothe
classthaninstanceoftheclass.
Thestaticcanbe:
1. variable(alsoknownasclassvariable)
2. method(alsoknownasclassmethod)
3. block
4. nestedclass

1)Javastaticvariable
Ifyoudeclareanyvariableasstatic,itisknownstaticvariable.
Thestaticvariablecanbeusedtoreferthecommonpropertyofallobjects(thatisnot
uniqueforeachobject)e.g.companynameofemployees,collegenameofstudentsetc.
Thestaticvariablegetsmemoryonlyonceinclassareaatthetimeofclassloading.

Advantageofstaticvariable
Itmakesyourprogrammemoryefficient(i.eitsavesmemory).

Understandingproblemwithoutstaticvariable
.

classStudent{

introllno

Stringname

Stringcollege="ITS"

}
Supposethereare500studentsinmycollege,nowallinstancedatamemberswillgetmemory
eachtimewhenobjectiscreated.Allstudenthaveitsuniquerollnoandnamesoinstancedata
memberisgood.Here,collegereferstothecommonpropertyofallobjects.Ifwemakeit
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(){System.out.println(rollno+""+name+""+college)}

publicstaticvoidmain(Stringargs[]){

Student8s1=newStudent8(111,"Karan")

Student8s2=newStudent8(222,"Aryan")

s1.display()

s2.display()

}
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
constructor.Sinceinstancevariablegetsthememoryatthetimeofobjectcreation,eachobject
willhavethecopyoftheinstancevariable,ifitisincremented,itwon'treflecttootherobjects.
Soeachobjectswillhavethevalue1inthecountvariable.
.

classCounter{

intcount=0//willgetmemorywheninstanceiscreated

Counter(){

count++

System.out.println(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++

System.out.println(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(){System.out.println(rollno+""+name+""+college)}

publicstaticvoidmain(Stringargs[]){

Student9.change()

Student9s1=newStudent9(111,"Karan")

Student9s2=newStudent9(222,"Aryan")

Student9s3=newStudent9(333,"Sonoo")

s1.display()

s2.display()

s3.display()

}
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=Calculate.cube(5)

System.out.println(result)

}
TestitNow
Output:125

Restrictionsforstaticmethod
Therearetwomainrestrictionsforthestaticmethod.Theyare:
1. Thestaticmethodcannotusenonstaticdatamemberorcallnonstaticmethoddirectly.
2. thisandsupercannotbeusedinstaticcontext.

classA{

inta=40//nonstatic

publicstaticvoidmain(Stringargs[]){

System.out.println(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{System.out.println("staticblockisinvoked")}

publicstaticvoidmain(Stringargs[]){

System.out.println("Hellomain")

}
TestitNow
Output:staticblockisinvoked
Hellomain

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

classA3{

static{

System.out.println("staticblockisinvoked")

System.exit(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