Static Keyword in Java


 

Keywords in Programming Languages are the reserved words that you cannot use as a variable name or identifier because they have been already defined in the language either as a parameter or a statement.

In java, there are 57 keywords or reserved names and ‘Static’ is one amongst them. Let us talk more about this static keyword with this table of content.

What is statically used for?
Static block
Static method
Static variable
Static Classes
Let us understand the static keyword and its implementation starting with…

What is static used for In Java?

Static keyword can be used within blocks of code, methods, variables, and classes by preceding the member name with ‘static’.Now let’s move on to learn how to use this keyword with each member, starting with

Now that you have understood why we use static keywords, let us see its use cases, beginning with Static Block.

Static Block In Java

The static block is like a constructor, where you can define default values, except that values for all the objects will be the same. The static block gets executed only once, whereas the constructor will be executed as per

the number of objects. A static block can be accessed with an object.

Let me show you an example

// Java program to demonstrate static blocks

class Main

{

// static variables

static int a = 10;

static int b;

 

// static block

static {

System.out.println("changing the b value under the static block.");

b = a * 10;

System.out.println();

}

public static void main(String[] args)

{

System.out.println("under the main function:");

System.out.println("The value of a is "+a);

System.out.println("The value of b is "+b);

}

}
Output for the above program

changing the b value under the static block.

 

under the main function:

The value of a is 10

The value of b is 100
As You noticed the static block gets executed first before the main function, Here is another example to demonstrate static block with a constructor.

// Java program to demonstrate static blocks

class StatTest {

static int a;

int b;

static {

a = 10;

System.out.println("static block executed ");

}

 

StatTest(){

System.out.println("Constructor executed");

}

}

 

class Main {

public static void main(String args[]) {

StatTest st1 = new StatTest();

StatTest st2 = new StatTest();

}

}
Output for the above program

static block executed 

Constructor executed

Constructor executed
Although we have two objects, the static block is executed only once, and the constructor twice. Now that you have understood static blocks, let’s move on to static variables in java.

Static Variable In Java

Static variables can be used to define a common property for all the objects, like a common college name for the students, or the common company name of several employees.

Let’s understand the static variables in java with a token program example. The following program is supposed to give a new token without the use of static variables.

/*Java Program to demonstrate that instance variable get memory each time when we create an object of class */

 

class Token {

int count = 0; //gets memory every time, instance is created

 

Token() {

count++; // incrementing TOken value

System.out.println(count);

}

 

public static void main(String args[]) {

 

// Creating Token objects

 

Token c1 = new Token();

Token c2 = new Token();

Token c3 = new Token();

Token c4 = new Token();

}

}
Output for the above program

1

1

1

1
Now let’s try to implement the same with static variables.

/*Java Program to demonstrate that static variable */

class Token {

static int count = 0; //gets memory once,and retains the value

 

Token() {

count++; // incrementing TOken value

System.out.println(count);

}

 

public static void main(String args[]) {

 

// Creating Token objects

 

Token c1 = new Token();

Token c2 = new Token();

Token c3 = new Token();

Token c4 = new Token();

}

}
Output for the above program

1

2

3

4

Hope you understood static variables in java with the above program, so next up we have static methods in java.

Check out this Complete Java Online Training by FITA. FITA provides a complete Java course including core java and advanced java J2EE, and SOA training, where you will be building real time applications using Servlets, Hibernate Framework, and Spring with Aspect-Oriented Programming (AOP) architecture, Struts through JDBC bundled with, placement support, and certification at an affordable price with an active placement cell, to make you an industry required certified java developer.

Static methods in java

Declaring methods static, would not require you to create an object and then call the method, and instead, you can refer to them using class methods because static methods are of class rather than the objects of the class.

Here is an example to demonstrate the static method in java.

class Company {

int salary;

String name;

String emp_type;

static String company_name = "FITA";

 

// static method for changing the value of a static variable

static void companyname(String c) {

company_name = c;

}

 

// constructor to initialize the variable

Company(int r, String n, String t) {

salary = r;

name = n;

emp_type = t;

}

 

// method to display values

void display() {

System.out.println(name + ":" +salary + ":" + company_name);

}

public static void main(String args[]) {

Company.companyname("FITA Academy");// calling change method to change company name

// creating instances of class Company

Company e1 = new Company(50000, "Shaneela","developer");

Company e2 = new Company(20000, "Kartick","finance controller");

Company e3 = new Company(30000, "Shareef","digital marketer");

 

// calling display method

e1.display();

e2.display();

e3.display();

}

}
Output for the above program

Shaneela:50000: FITA Academy

Kartick:20000: FITA Academy

Shareef:30000: FITA Academy

You might have observed that the main method is declared static so that  JVM does not require to create an object to invoke the main method, which also makes it memory efficient.

There is a restriction that the static methods cannot use or invoke non-static data members or methods directly nor can you use the this and super keyword in a static context. Let me show you an example of this.


class TestStat {

int a = 20;// non static variable

 

public static void main(String args[]) {

System.out.println(a);

}

}

 

// Output for the above program

 

/*Main.java:5: error: non-static variable a cannot be referenced from a static context

System.out.println(a);*/
Hope you understood why we use static methods and when, next up we have static classes in java.

Static Class In Java

Only a nested class can be made static so that nested classes do not need a reference to an outer class. Although inner classes can access all the static and non-static members, the static class can only access static members of the class. Let me show you an example.


public class Main {

private static String name = "FITA";

private String str= "Academy";

// Static class

static class Employee {

String com_name;

Employee(String t) {

com_name = t;

}

// non-static method

public void display() {

// System.out.println(str);

System.out.println(name);

System.out.println(com_name);

}

}

 

public static void main(String args[]) {

Main.Employee e1 = new Main.Employee("Academy");

e1.display();

 

}

}
Output for the above program

FITA
Academy

The commented line to print str would cause an error saying, “non-static variable name cannot be referenced from a static context” if executed.

This was all about a static block, static method, static variables, and static classes in java, their implementations and use cases along with example programs. To get in-depth knowledge of core Java and advanced java, J2EE  SOA training along with its various applications and real-time projects using Servlets, Spring with Aspect-Oriented Programming (AOP) architecture, Hibernate Framework, and Struts through JDBC you can enroll in Certified Java Training in Chennai or Certified Java Training in Bangalore by FITA or a virtual class for this course, at an affordable price, bundled with real-time projects, certification, support, and career guidance assistance and an active placement cell, to make you an industry required certified java developer.

FITA’s courses training is delivered by professional experts who have worked in the software development and testing industry for a minimum of 10+ years, and have experience of working with different software frameworks and software testing designs.




Recent Post:


Quick Enquiry

Please wait while submission in progress...


Contact Us

Chennai

  93450 45466

Bangalore

 93450 45466

Coimbatore

 95978 88270

Online

93450 45466

Madurai

97900 94102

Pondicherry

93635 21112

For Hiring

 93840 47472
 hr@fita.in

Corporate Training

 90036 23340


Read More Read less

FITA Academy Branches

Chennai

Bangalore

Coimbatore

Other Locations

FITA Academy - Velachery
Plot No 7, 2nd floor,
Vadivelan Nagar,
Velachery Main Road,
Velachery, Chennai - 600042
Tamil Nadu

    :   93450 45466

FITA Academy - Anna Nagar
No 14, Block No, 338, 2nd Ave,
Anna Nagar,
Chennai 600 040, Tamil Nadu
Next to Santhosh Super Market

    :   93450 45466

FITA Academy - T Nagar
05, 5th Floor, Challa Mall,
T Nagar,
Chennai 600 017, Tamil Nadu
Opposite to Pondy Bazaar Globus

    :   93450 45466

FITA Academy - Tambaram
Nehru Nagar, Kadaperi,
GST Road, West Tambaram,
Chennai 600 045, Tamil Nadu
Opposite to Saravana Jewellers Near MEPZ

    :   93450 45466

FITA Academy - Thoraipakkam
5/350, Old Mahabalipuram Road,
Okkiyam Thoraipakkam,
Chennai 600 097, Tamil Nadu
Next to Cognizant Thoraipakkam Office and Opposite to Nilgris Supermarket

    :   93450 45466

FITA Academy - Porur
17, Trunk Rd,
Porur
Chennai 600116, Tamil Nadu
Above Maharashtra Bank

    :   93450 45466

FITA Academy Marathahalli
No 7, J J Complex,
ITPB Road, Aswath Nagar,
Marathahalli Post,
Bengaluru 560037

    :   93450 45466

FITA Academy - Saravanampatty
First Floor, Promenade Tower,
171/2A, Sathy Road, Saravanampatty,
Coimbatore - 641035
Tamil Nadu

    :   95978 88270

FITA Academy - Singanallur
348/1, Kamaraj Road,
Varadharajapuram, Singanallur,
Coimbatore - 641015
Tamil Nadu

    :   95978 88270

FITA Academy - Madurai
No.2A, Sivanandha salai,
Arapalayam Cross Road,
Ponnagaram Colony,
Madurai - 625016, Tamil Nadu

    :   97900 94102

FITA Academy - Pondicherry
410, Villianur Main Rd,
Sithananda Nagar, Nellitope,
Puducherry - 605005
Near IG Square

    :   93635 21112

Read More Read less
  • Are You Located in Any of these Areas

    Adyar, Adambakkam, Anna Salai, Ambattur, Ashok Nagar, Aminjikarai, Anna Nagar, Besant Nagar, Chromepet, Choolaimedu, Guindy, Egmore, K.K. Nagar, Kodambakkam, Koyambedu, Ekkattuthangal, Kilpauk, Meenambakkam, Medavakkam, Nandanam, Nungambakkam, Madipakkam, Teynampet, Nanganallur, Navalur, Mylapore, Pallavaram, Purasaiwakkam, OMR, Porur, Pallikaranai, Poonamallee, Perambur, Saidapet, Siruseri, St.Thomas Mount, Perungudi, T.Nagar, Sholinganallur, Triplicane, Thoraipakkam, Tambaram, Vadapalani, Valasaravakkam, Villivakkam, Thiruvanmiyur, West Mambalam, Velachery and Virugambakkam.

    FITA Velachery or T Nagar or Thoraipakkam OMR or Anna Nagar or Tambaram or Porur branch is just few kilometre away from your location. If you need the best training in Chennai, driving a couple of extra kilometres is worth it!