- What is static function in java
- Learn Latest Tutorials
- Preparation
- Trending Technologies
- B.Tech / MCA
- Javatpoint Services
- Training For College Campus
- Why Static in Java? What does this keyword mean? [Solved]
- How to Create a Static Variable in Java
- How to Create a Static Method in Java
- How to Create a Static Block in Java
- Summary
- What is static function in java
What is static function in java
Learn Latest Tutorials
Preparation
Trending Technologies
B.Tech / MCA
Javatpoint Services
JavaTpoint offers too many high quality services. Mail us on h[email protected], to get more information about given services.
- Website Designing
- Website Development
- Java Development
- PHP Development
- WordPress
- Graphic Designing
- Logo
- Digital Marketing
- On Page and Off Page SEO
- PPC
- Content Development
- Corporate Training
- Classroom and Online Training
- Data Entry
Training For College Campus
JavaTpoint offers college campus training on Core Java, Advance Java, .Net, Android, Hadoop, PHP, Web Technology and Python. Please mail your requirement at [email protected].
Duration: 1 week to 2 week
Like/Subscribe us for latest updates or newsletter
Why Static in Java? What does this keyword mean? [Solved]
Ihechikara Vincent Abba
You can use the static keyword in different parts of a Java program like variables, methods, and static blocks.
The main purpose of using the static keyword in Java is to save memory. When we create a variable in a class that will be accessed by other classes, we must first create an instance of the class and then assign a new value to each variable instance – even if the value of the new variables are supposed to be the same across all new classes/objects.
But when we create a static variables, its value remains constant across all other classes, and we do not have to create an instance to use the variable. This way, we are creating the variable once, so memory is only allocated once.
You’ll understand this better with the examples in the sections that follow.
In order to understand what the static keyword is and what it actually does, we’ll see some examples that show its use in declaring static variables, methods, and blocks in Java.
How to Create a Static Variable in Java
To understand the use of the static keyword in creating variables, let’s look at the usual way of creating variables shared across every instance of a class.
I’ll explain what happened in the code above step by step.
We created a class called Student with three variables – studentName , course , and school .
We then created two instances of the Student class:
Student Student1 = new Student(); Student Student2 = new Student();
The first instance – Student1 – which has access to the variables created in its class had these values:
Student1.studentName = "Ihechikara"; Student1.course = "Data Visualization"; Student1.school = "freeCodeCamp";
The second instance had these values:
Student2.studentName = "John"; Student2.course = "Data Analysis with Python"; Student2.school = "freeCodeCamp";
If you look closely, you’ll realize that both students have the same school name – «freeCodeCamp». What if we had to create 100 students for the same school? That means we’d be initializing a variable with the same value 100 times – allocating new memory every time.
While this may not appear to be a problem, in a much larger codebase, it could become a flaw and unnecessarily slow your program down.
To fix this problem, we’ll use the static keyword to create the school variable. After that, all instances of the class can make use of that variable.
In the code above, we created a static variable called school . You’ll notice that the static keyword preceded the data type and the name of the variable: static String school = «freeCodeCamp»; .
Now when we create a new instance of our class, we do not have to initialize the school variable for every instance. In our code, we only assigned a value to the variable in the first instance and it was inherited by the second instance as well.
Note that changing the value of the static variable anywhere in the code overrides the value in other parts of the code where it was declared previously.
So you should only use the static keyword for variables that are supposed to remain constant in the program.
You can also assign a value to the variable when it is created so you don’t have to declare it again when you create a class instance: static String school = «freeCodeCamp»; .
You’ll have this if you use the method above:
In the last section, you’ll see how to initialize static variables using static blocks.
How to Create a Static Method in Java
Before we look at an example, here are some things you should know about static methods in Java:
- Static methods can only access and modify static variables.
- Static methods can be called/used without creating a class instance.
Here’s an example to help you understand:
class EvenNumber < static int evenNumber; static void incrementBy2()< evenNumber = evenNumber + 2; System.out.println(evenNumber); >public static void main(String[] args) < incrementBy2(); // 2 incrementBy2(); // 4 incrementBy2(); // 6 incrementBy2(); // 8 >>
In the code above, we created an integer ( evenNumber ) in a class called EvenNumber .
Our static method is named incrementBy2() . This method increases the value of the evenNumber integer and prints its value.
Without creating a class instance, we were able to call the incrementBy2() method in the program’s main method. Each time we called the method, the value of evenNumber was incremented by 2 and printed out.
You can also attach the name of the class to the method using dot notation while calling the method: EvenNumber.incrementBy2(); . Every static method belongs to the class and not instances of the class.
How to Create a Static Block in Java
Static blocks in Java are similar to constructors. We can use them to initialize static variables, and they are executed by the compiler before the main method.
class Block < static int year; static < year = 2022; System.out.println("This code block got executed first"); >public static void main(String[] args) < System.out.println("Hello World"); System.out.println(year); >>
In the code above, we created a static integer variable year . We then initialized it in a static block:
You can create a static block, as you can see above, using the static keyword followed by curly brackets. In the static block in our code, we initialized the year variable with a value of 2022. We also printed out some text – «This code block got executed first».
In the main method, we printed «Hello World» and the static year variable.
In the console, the code will be executed in this order:
This code block got executed first Hello World 2022
This demonstrates how the code in the static block is executed first before the main method.
Summary
In this article, we talked about the static keyword in Java. It is a keyword which mainly helps us optimize memory in our Java programs.
We saw how to create static variables and methods with examples.
Lastly, we talked about static blocks which you can use to initialize static variables. Static blocks get executed before the main method.
What is static function in java
В этом примере невозможно инициализировать объект List всеми начальными значениями вместе с объявлением, поэтому используется статический блок.
Код ниже демонстрирует особенность статических блоков — они выполняются раньше конструкторов и при создании нескольких объектов класса, статический блок выполняется только один раз.
public class Test < static < System.out.println("Вызов статического блока"); >Test() < System.out.println("Вызов конструктора"); >> class Main < public static void main(String[] args) < Test t1 = new Test(); Test t2 = new Test(); >>
- Если для инициализации статических переменных требуется дополнительная логика, за исключением операции присваивания
- Если инициализация статических переменных подвержена ошибкам и требует обработки исключений
- У класса может быть несколько статических блоков
- Статические поля и статические блоки выполняются в том же порядке, в котором они присутствуют в классе
- Из статического блока нельзя получить доступ к не статическим членам класса
- Статический блок не может пробросить дальше перехваченные исключения, но может их выбросить. При этом всегда будет выкидываться только java.lang.ExceptionInInitializerError
- Статические поля или переменные инициализируются после загрузки класса в память в том же порядке, в каком они описаны в классе
Язык программирования Java позволяет создавать классы внутри другого класса. Такой класс называется вложенным (nested). Вложенный класс группирует элементы, которые будут использоваться в одном месте, сделав тем сам код более организованным и читабельным.
- вложенные классы, объявленные статическими, называются статическими вложенными классами (static nested classes)
- вложенные классы, объявленные без static, называются внутренними классами (inner classes)
Основное различие между этими понятиями состоит в том, что внутренние классы имеют доступ ко всем членам включающего их класса (включая приватные) верхнего уровня, тогда как статические вложенные классы имеют доступ только к статическим членам внешнего класса.
Наиболее широко используемый подход для создания объектов «одиночка» (singleton) — это статический вложенный класс, поскольку он не требует никакой синхронизации, его легко изучить и реализовать:
public class Singleton < private Singleton() <>private static class SingletonHolder < private static final Singleton INSTANCE = new Singleton(); >public static Singleton getInstance() < return SingletonHolder.instance; >>
- Если какой-то класс используются только в одном другом классе, то их можно сгруппировать, поместив в один общий класс. Это усиливает инкапсуляцию
- Если вложенный класс не требует какого-либо доступа к членам экземпляра его класса, то лучше объявить его как статический, потому, что таким образом он не будет связан с внешним классом и, следовательно, будет более оптимальным, поскольку ему не потребуется память в куче или в стеке
- Статические вложенные классы не имеют доступа к какому-либо члену экземпляра внешнего класса — он может получить к ним доступ только через ссылку на объект
- Статические вложенные классы могут получить доступ ко всем статическим членам внешнего класса, включая приватные
- Спецификация Java не позволяет объявлять класс верхнего уровня статическим. Только классы внутри других классов могут быть статическими
- Опять же, этот класс привязан к внешнему классу и если внешний наследуется другим классом, то этот не будет унаследован. При этом данный класс можно наследовать, как и он может наследоваться от любого другого класса и имплементировать интерфейс
- По сути статический вложенный класс ничем не отличается от любого другого внутреннего класса за исключением того, что его объект не содержит ссылку на создавший его объект внешнего класса
- Для использования статических методов/переменных/классов нам не нужно создавать объект данного класса
- Яркий пример вложенного статического класса — HashMap.Entry, который предоставляет структуру данных внутри HashMap. Стоит заметить, также как и любой другой внутренний класс, вложенные классы находятся в отдельном файле .class. Таким образом, если вы объявили пять вложенных классов в вашем главном классе, у вас будет 6 файлов с расширением .class
Говоря о ключевом слове static, нельзя не упомянуть о его применении в определении констант — переменных, которые никогда не изменяются.
В языке Java существует зарезервированное слово «const», но оно не используется, и Java не поддерживает константы на уровне языка. Выход из ситуации имеется: для определения константы необходимо добавить модификаторы «static final» к полю класса.
Константы — это статические финальные поля, содержимое которых неизменно. Это относится к примитивам, String, неизменяемым типам и неизменяемым коллекциям неизменяемых типов. Если состояние объекта может измениться, он не является константой.
Модификатор static делает переменную доступной без создания экземпляра класса, а final делает ее неизменяемой. При этом нужно помнить, что если мы сделаем переменную только static, то ее легко можно будет изменить, обратившись к ней через имя класса. Если переменная будет иметь только модификатор final, то при создании каждого экземпляра класса она может быть проинициализирована своим значением. Соответственно, используя совместно модификаторы static и final, переменная остается статической и может быть проинициализирована только один раз. В Java константой считается не та переменная, которую нельзя изменить в рамках одного объекта, а та, которую не могут изменить ни один экземпляр класса в котором она находится (такая переменная создается и инициализируется один раз для всех экземпляров, сколько бы их не было).