For Enquiry: 93450 45466

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:

  • Trending Courses

    JAVA Training In Chennai Software Testing Training In Chennai Selenium Training In Chennai Python Training in Chennai Data Science Course In Chennai Digital Marketing Course In Chennai DevOps Training In Chennai German Classes In Chennai Artificial Intelligence Course in Chennai AWS Training in Chennai UI UX Design course in Chennai Tally course in Chennai Full Stack Developer course in Chennai Salesforce Training in Chennai ReactJS Training in Chennai CCNA course in Chennai Ethical Hacking course in Chennai RPA Training In Chennai Cyber Security Course in Chennai IELTS Coaching in Chennai Graphic Design Courses in Chennai Spoken English Classes in Chennai Data Analytics Course in Chennai

    Spring Training in Chennai Struts Training in Chennai Web Designing Course In Chennai Android Training In Chennai AngularJS Training in Chennai Dot Net Training In Chennai C / C++ Training In Chennai Django Training in Chennai PHP Training In Chennai iOS Training In Chennai SEO Training In Chennai Oracle Training In Chennai Cloud Computing Training In Chennai Big Data Hadoop Training In Chennai UNIX Training In Chennai Core Java Training in Chennai Placement Training In Chennai Javascript Training in Chennai Hibernate Training in Chennai HTML5 Training in Chennai Photoshop Classes in Chennai Mobile Testing Training in Chennai QTP Training in Chennai LoadRunner Training in Chennai Drupal Training in Chennai Manual Testing Training in Chennai WordPress Training in Chennai SAS Training in Chennai Clinical SAS Training in Chennai Blue Prism Training in Chennai Machine Learning course in Chennai Microsoft Azure Training in Chennai Selenium with Python Training in Chennai UiPath Training in Chennai Microsoft Dynamics CRM Training in Chennai VMware Training in Chennai R Training in Chennai Automation Anywhere Training in Chennai GST Training in Chennai Spanish Classes in Chennai Japanese Classes in Chennai TOEFL Coaching in Chennai French Classes in Chennai Informatica Training in Chennai Informatica MDM Training in Chennai Big Data Analytics courses in Chennai Hadoop Admin Training in Chennai Blockchain Training in Chennai Ionic Training in Chennai IoT Training in Chennai Xamarin Training In Chennai Node JS Training In Chennai Content Writing Course in Chennai Advanced Excel Training In Chennai Corporate Training in Chennai Embedded Training In Chennai Linux Training In Chennai Oracle DBA Training In Chennai PEGA Training In Chennai Primavera Training In Chennai Tableau Training In Chennai Spark Training In Chennai Appium Training In Chennai Soft Skills Training In Chennai JMeter Training In Chennai Power BI Training In Chennai Social Media Marketing Courses In Chennai Talend Training in Chennai HR Courses in Chennai Google Cloud Training in Chennai SQL Training In Chennai CCNP Training in Chennai PMP Training in Chennai OET Coaching Centre in Chennai Business Analytics Course in Chennai NextJS Course in Chennai Vue JS Course in Chennai

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

    Adambakkam, Adyar, Akkarai, Alandur, Alapakkam, Alwarpet, Alwarthirunagar, Ambattur, Ambattur Industrial Estate, Aminjikarai, Anakaputhur, Anna Nagar, Anna Salai, Arumbakkam, Ashok Nagar, Avadi, Ayanavaram, Besant Nagar, Bharathi Nagar, Camp Road, Cenotaph Road, Central, Chetpet, Chintadripet, Chitlapakkam, Chengalpattu, Choolaimedu, Chromepet, CIT Nagar, ECR, Eechankaranai, Egattur, Egmore, Ekkatuthangal, Gerugambakkam, Gopalapuram, Guduvanchery, Guindy, Injambakkam, Irumbuliyur, Iyyappanthangal, Jafferkhanpet, Jalladianpet, Kanathur, Kanchipuram, Kandhanchavadi, Kandigai, Karapakkam, Kasturbai Nagar, Kattankulathur, Kattupakkam, Kazhipattur, Keelkattalai, Kelambakkam, Kilpauk, KK Nagar, Kodambakkam, Kolapakkam, Kolathur, Kottivakkam, Kotturpuram, Kovalam, Kovilambakkam, Kovilanchery, Koyambedu, Kumananchavadi, Kundrathur, Little Mount, Madambakkam, Madhavaram, Madipakkam, Maduravoyal, Mahabalipuram, Mambakkam, Manapakkam, Mandaveli, Mangadu, Mannivakkam, Maraimalai Nagar, Medavakkam, Meenambakkam, Mogappair, Moolakadai, Moulivakkam, Mount Road, MRC Nagar, Mudichur, Mugalivakkam, Muttukadu, Mylapore, Nandambakkam, Nandanam, Nanganallur, Nanmangalam, Narayanapuram, Navalur, Neelankarai, Nesapakkam, Nolambur, Nungambakkam, OMR, Oragadam, Ottiyambakkam, Padappai, Padi, Padur, Palavakkam, Pallavan Salai, Pallavaram, Pallikaranai, Pammal, Parangimalai, Paruthipattu, Pazhavanthangal, Perambur, Perumbakkam, Perungudi, Polichalur, Pondy Bazaar, Ponmar, Poonamallee, Porur, Pudupakkam, Pudupet, Purasaiwakkam, Puzhuthivakkam, RA Puram, Rajakilpakkam, Ramapuram, Red Hills, Royapettah, Saidapet, Saidapet East, Saligramam, Sanatorium, Santhome, Santhosapuram, Selaiyur, Sembakkam, Semmanjeri, Shenoy Nagar, Sholinganallur, Singaperumal Koil, Siruseri, Sithalapakkam, Srinivasa Nagar, St Thomas Mount, T Nagar, Tambaram, Tambaram East, Taramani, Teynampet, Thalambur, Thirumangalam, Thirumazhisai, Thiruneermalai, Thiruvallur, Thiruvanmiyur, Thiruverkadu, Thiruvottiyur, Thoraipakkam, Thousand Light, Tidel Park, Tiruvallur, Triplicane, TTK Road, Ullagaram, Urapakkam, Uthandi, Vadapalani, Vadapalani East, Valasaravakkam, Vallalar Nagar, Valluvar Kottam, Vanagaram, Vandalur, Vasanta Nagar, Velachery, Vengaivasal, Vepery, Vettuvankeni, Vijaya Nagar, Villivakkam, Virugambakkam, West Mambalam, West Saidapet

    FITA Velachery or T Nagar or Thoraipakkam OMR or Anna Nagar or Tambaram or Porur or Pallikaranai 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!