You are here:   HomeJava ProgrammingJava MethodsClass variables and methods in Java
by Dinesh Thakur Category: Java Methods

To create a class variable or method, include the word static in front of the method's name. The modifier static typically comes after any protection modifiers. Given below is an example that illustrates how a class variable may be created in a program.

Declaring variables and methods.

 

import java.io.*;

public class CircleClass

{

           public static float pi = 3.14f;

           public static float area(float r)

         {

                  return pi * r * r;

          }

           public static float perimeter(float r)

         {

                 return 2 * pi * r;

         }

         public static void main(String args[ ]) throws IOException

        {

                float A1, P1;

                System.out.println("Enter the radius of the Circle:");

                BufferedReader br = new BufferedReader(new InputStreamReader(Sytem.in));

                int n = Integer.parselnt(br.readLine());

                A1 = area(n);

                System.out.println("Area of the Circle is:" +A1);

                P1 = perimeter(n);

                System.out.println("Perimeter of the Circle is:"+P1);

        }

}

The output of Program is as shown below:

   Enter the radius of the Circle:

    5

            Area of the Circle is: 78.5

            Perimeter of the Circle is: 31.400002

Both class variables and methods can be accessed using standard dot notation by placing either the. class name or an object to the left side of the dot; however, the convention that is followed is always to use the name of the class and not that of the object, to clarify that a class variable is being used and to help the reader to know instantly that the variable is global to all instances. This is as shown in the following example.

float circumference = 2 * Circle.pi * getRadius();

float randomNumer = Math.random();

An interesting example of using class variables, which brings out how their properties can be used effectively is now discussed. Program shows a class called StudentClass that uses class and instance variables to keep track of number of students in a particular course.

Effectively using class and instance variables.

 

import java.io.*;

public class StudentClass

{

        private static int numberOfStudents=O;

        private static void newStudent()

       {

                numberOfStudents++;

       }

        StudentClass() // Defining Constructor

        {

                StudentClass.newStudent();

        }

         protected static void showStudentCount()

       {

              System.out.println("The number of Students is"+numberOfStudents);

       }

        public static void main(String args[ ])

       {

                System.out.println("INITIALLY");

                Student.showStudentCount();

                int no_students =10, num=0;

                while(num<10)

                {

                    new StudentClass();

                    num++;

                 }

                 System.out.println("AFTER ADDING MORE STUDENTS");

                 StudentCiass =new StudentClass();

                  st.showStudentCount();

         }

}

         The output of Program is shown beiow:

       

          INITIALLY

         The number of Students is 0

         AFTER ADDING MORE STUDENTS

         The number of Students is 11

In Program, the class StudentClass has class variable numberOfStudents which holds the number of students in a course. A class variable is initialized whenever its class is created. It is declared static because the count of the students is required to be retained across the creation of objects. It is also declared private so that it can only be accessed by the member methods and not by any method outside the class. Initially, the variable numberOfStudents is initialized to 0. Two methods are defined: method newStudent() increases the count of the number of students and method showStudentCount() prints the number of students.

In the main method, the count of the students is printed and then new instances of class Student are created (in the while loop). During creation of instances of class StudentClass, the constructor StudentClass() automatically increments the count of the students.





Subscribe To Free Daily Newsletter!

Get Free News Updates Delivered Directly To Your Inbox
About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular Computer Notes blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to contact us.



What's New and Popular