Tutorial Playlist
191 Lessons1. Introduction to Java
2. What is Java?
3. History of Java
4. Java Tutorial for Beginners
5. How Do Java Programs Work?
6. JDK in Java
7. C++ Vs Java
8. Java vs. Python
9. Java vs. JavaScript
10. From Java Source Code to Executable
11. How to Install Java in Linux
12. How to Install Java in Windows 10
13. Java Hello World Program
14. Structure of Java Program and Java Syntax
15. Operators in Java
16. Java If-else
17. Switch Case In Java
18. Loops in Java
19. Infinite loop in Java
20. For Loop in Java
21. For Each Loop in Java
22. Constructor in Java
23. Constructor Overloading in Java
24. Copy Constructor in Java
25. Default Constructor in Java
26. Parameterized Constructors in Java
27. Constructor Chaining In Java
28. Finalize Method in Java
29. Static Method in Java
30. Equals Method in Java
31. Abstract Method in Java
32. toString() Method in Java
33. Difference between equals method in Java
34. Inheritance in Java
35. Multiple Inheritance in Java
36. Hierarchical Inheritance in Java
37. Java Classes and Objects
38. Scanner Class in java
39. All classes in java are inherited from which class
40. What is Nested Class in Java
41. POJO Class in Java
42. Anonymous Class in Java
43. Final Class in Java
44. Object Class in Java
45. Packages in Java
46. Access Modifiers in Java
47. Static Keyword In Java
Now Reading
1 mins read
48. Final Keyword in Java
49. Checked and Unchecked Exceptions in Java
50. User Defined Exception in Java
51. Error vs. Exception in Java
52. Java Collection
53. Collections in Java
54. Garbage Collection in Java
55. Generics In Java
56. Java Interfaces
57. Functional Interface in Java
58. Marker Interface in Java
59. Streams in Java
60. Byte stream in java
61. File Handling in Java
62. Thread in Java
63. Thread Lifecycle In Java
64. Daemon Thread in Java
65. Thread Priority in Java
66. Deadlock in Java
67. String Pool in Java
68. Java Database Connectivity(JDBC)
69. Design Patterns in Java
70. Functional Programming in Java
71. OOP vs Functional vs Procedural
72. Heap Memory and Stack Memory in Java
73. Applet in Java
74. Java Swing
75. Java Frameworks
76. Hibernate Framework
77. JUnit Testing
78. How to Install Eclipse IDE for Java?
79. Command line arguments in Java
80. Jar file in Java
81. Java Clean Code
82. OOPs Concepts in Java
83. Java OOPs Concepts
84. Overloading vs Overriding in Java
85. Java 8 features
86. String in Java
87. String to int in Java
88. Why String Is Immutable in Java?
89. Primitive Data Types in Java
90. Non-Primitive Data Types in Java
91. This and Super Keyword in Java
92. HashMap in Java
93. Comparable And Comparator in Java
94. Type Casting in Java
95. Arrays Sort in Java with Examples
96. Variable Hiding and Variable Shadowing in Java
97. Enum in Java
98. Substring in Java
99. Pattern Programs in Java
100. Hashcode in Java
101. What is ByteCode in Java?
102. How To Take Input From User in Java
103. GCD of Two Numbers in Java
104. Linked List in Java
105. Arithmetic Operators in Java
106. Conditional Operators in Java
107. Stack and Queue in Java
108. Array Length in Java
109. Number Pattern Program in Java
110. Split in java
111. Map In Java
112. Difference Between Throw and Throws in Java
113. Difference Between Data Hiding and Abstraction
114. HashSet in Java
115. String Length in Java
116. Factorial Using Recursion in Java
117. DateFormat in Java
118. StringBuilder Class in java
119. Instance variables in Java
120. Java List Size
121. Java APIs
122. Reverse an Array in Java
123. StringBuffer and StringBuilder Difference in Java
124. Java Program to Add Two Numbers
125. String to Array in Java
126. Regular Expressions in Java
127. Identifiers in Java
128. Data Structures in Java
129. Set in Java
130. Pass By Value and Call By Reference in Java
131. Try Catch in Java
132. Bubble Sort in Java
133. Caesar Cipher Program in Java
134. Queue in Java
135. Object Creation in Java
136. Multidimensional Array in Java
137. How to Read a File in Java
138. String Comparison in Java
139. Volatile Keyword in Java
140. Control Statements in Java
141. Jagged Array in Java
142. Two-Dimensional Array in Java
143. Java String Format
144. Replace in Java
145. charAt() in Java
146. CompareTo in Java
147. Matrix Multiplication in Java
148. Static Variable in Java
149. Event Handling in Java
150. parseInt in Java
151. Java ArrayList forEach
152. Abstraction in Java
153. String Input in Java
154. Logical Operators in Java
155. instanceof in Java
156. Math Floor in Java
157. Selection Sort Java
158. int to char in Java
159. Stringtokenizer in java
160. Implementing and Manipulating Abs in Java
161. Char array to string in java
162. Convert Double To String In Java
163. Deque in Java
164. Converting a List to an Array in Java
165. The Max function in java
166. Removing whitespace from string in java
167. String arrays in Java
168. Strings in Java Vs Strings in Cpp
169. Sum of digits of a number in Java
170. Art of Graphical User Interfaces
171. Trim in Java
172. RxJava
173. Recursion in Java
174. HashSet Java
175. Difference Between Java and Python
176. Square Root in Java
177. Reverse A String in Java
178. Even Odd Program in Java
179. Fibonacci Series in Java
180. Prime Number Program in Java
181. Java Program to Print Prime Numbers in a Given Range
182. Java Leap Year Program
183. Swapping of Two Numbers in Java
184. LCM of Two Numbers in Java
185. Math.sqrt() Function in Java
186. Area of Triangle in Java
187. Sort a String In Java
188. Factorial Program in Java
189. Javafx
190. Lambda expression in java
191. Setup Java Home and IDE on macOS
The Java programming language has a powerful feature referred to as the static keyword. This plays an essential part in defining class-level entities that are shared by all instances of a class. This in-depth write-up dives into the ins and outs of the static keyword in Java, helping the enthusiasts of this programming language study its properties, applications, and advantages. By understanding the intricacies of the static keyword, including its relationship with the public static void main in Java, individuals can unlock its full potential and optimize their programs.
The static keyword in Java serves as a crucial element when it comes to defining class-level members such as variables, methods, and nested classes. By marking a member as static, it becomes associated with the class itself rather than any specific instance of it. As a result, all objects of that particular class share the same copy of the static member, regardless of the number of instances created.
As a beginner, you may wonder why we use static keyword in Java. The main reason is that it helps save memory. Java’s static keyword possesses distinct characteristics that set it apart, and they are mentioned below.
1. Class Association: Static members can be accessed by using the class name because they are linked to the class. This suggests that modifications to one are applied to all instances of the class and that the class name can be used to access static members rather than an object reference.
2. Lifetime: Static members are present from the point at which the class is loaded into memory to the instance at which the program ends.
3. Direct Access: Static members can be accessed directly without the need to construct a class object, making them easily usable. Thanks to this feature, they can then offer constants and useful functions that can be utilized throughout the program.
4. Shared memory allocation: During program execution, memory is only allocated once for static variables and methods. Since all instances of a class share this memory space, static members are necessary for maintaining the global state or shared functionality.
5. Accessibility: The availability of non-static members is restricted because static methods and variables are not connected to a particular instance of the class.
6. Static methods can be overloaded, allowing the development of many methods with the same name but different parameters. These cannot be overridden because they are associated with the class rather than a specific instance of the class.
A member can be accessed without referencing an object and before any objects of its class are created if it is declared static. In the following Java code, for instance, the static method m1() is obtained without creating an instance of the Test class.
// Java program to demonstrate that a static member
// can be accessed before instantiating a class
class Test
{
// static method
static void m1()
{
System.out.println("from m1");
}
public static void main(String[] args)
{
// calling m1 without creating
// any object of class Test
m1();
}
}
Output
from m1
Static Blocks:
Static blocks are utilized to initialize static variables or perform other static operations. They are executed when the class is loaded into memory, even before the creation of any objects. They are enclosed within a pair of curly braces and preceded by the static keyword. Further, the static keyword is used when one needs to perform one-time initialization. Here's an example:
java
public class MyClass {
static {
System.out.println("Static block executed!");
}
public static void main(String[] args) {
System.out.println("Inside the main method");
}
}
Output:
scss
Static block executed!
Inside the main method
Static Variables:
Static variables, also known as class variables, are shared among all instances of a class. They retain their values throughout the execution of the program. Here's an example:
java
public class MyClass {
static int count = 0;
public MyClass() {
count++;
}
public static void main(String[] args) {
MyClass obj1 = new MyClass();
MyClass obj2 = new MyClass();
System.out.println("Count: " + count);
}
}
Output:
makefile
Count: 2
Static Methods:
Static methods in Java belong to the class itself and can be invoked directly without creating an object. They are commonly used for utility functions or operations that don't require instance-specific data. Here's an example:
java
public class MathUtils {
public static int add(int a, int b) {
return a + b;
}
public static void main(String[] args) {
int result = MathUtils.add(5, 3);
System.out.println("Result: " + result);
}
}
Output:
makefile
Result: 8
Static variables and methods are suitable in various scenarios. Let’s study the use of static variables and static methods in Java with examples.
1. Utility Methods: When a method doesn't rely on any instance-specific data, it can be made static for easy access. For example, consider a MathUtils class that provides mathematical operations:
java
public class Main {
public static void main(String[] args) {
int sum = MathUtils.add(5, 3);
int product = MathUtils.multiply(2, 4);
System.out.println("Sum: " + sum);
System.out.println("Product: " + product);
}
}
Output:
makefile
Sum: 8
Product: 8
In this example, the add method is called with arguments 5 and 3, and the multiply method is called with arguments 2 and 4. The returned values are then printed to the console, resulting in the output shown above.
You can access these static methods directly using the class name, such as MathUtils.add(5, 3) or MathUtils.multiply(2, 4).
2. Counters: Static variables are useful for counting the number of instances created for a class. Let's say you have a Car class, and you want to keep track of the total number of cars created:
public class Car {
private static int totalCars = 0;
public Car() {
totalCars++;
}
public static int getTotalCars() {
return totalCars;
}
}
public class Main {
public static void main(String[] args) {
Car car1 = new Car();
Car car2 = new Car();
Car car3 = new Car();
System.out.println("Total cars created: " + Car.getTotalCars());
}
}
Output:
mathematica
Total cars created: 3
The totalCars variable is static and increments each time a new Car object is created.
3. Constants: Static variables can be used to store constants that remain the same across all instances. Let us consider a class representing the mathematical constant pi:
java
public class MathConstants {
public static final double PI = 3.14159;
public static final double E = 2.71828;
// Other constants...
}
Using the class name MathConstants.PI or MathConstants.E, these ultimate static variables are accessible anywhere in the program.
By utilizing static variables and methods in these circumstances, you can improve Java program code organization, efficiency, and reusability.
Java allows the creation of static nested classes, which are declared as static within another class. These classes can access only the static members of the enclosing class. Here's an example:
java
public class OuterClass {
static class NestedClass {
void display() {
System.out.println("Nested class display");
}
}
public static void main(String[] args) {
OuterClass.NestedClass nestedObj = new OuterClass.NestedClass();
nestedObj.display();
}
}
Output:
kotlin
Nested class display
The output "Nested class display" is generated because the `display()` method of the `NestedClass, nested within the `OuterClass, is invoked through an instance of the nested class.
The static keyword offers several advantages:
1. Memory Efficacy: You can store static members in a single location in memory, reducing memory consumption.
2. Convenient Access: Static members can be accessed directly using the class name without the need for object creation.
3. Code Reusability: Static methods and variables allow for code reuse across multiple instances of a class.
4. Static members can be accessed more swiftly and effectively than their non-static counterparts because they are associated with the class rather than with individual instances.
5. Utility methods that don't need access to an object's state can be contained in static methods. This can improve the organization of the code and make it easier for utility methods to be reused across different classes.
6. Constants: Static final variables can be used to define program-wide constants.
7. Static methods can be used to implement class-level functionality, such as factory methods and utility functions that don't need access to an object's state.
Before concluding this Static keyword in Java tutorial, investigating static blocks and classes, let's discuss a few distinctions between static and non-static variables and methods in Java.
Static Variables | Non-static Variables |
They can be accessed using the class names | Objects can be accessed using non-static variables. |
They can be accessed using either static or non-static methods | Accessing them is restricted to non-static methods. |
They only receive a single memory allocation when the class is launched | Each object is allocated its own memory. |
All instances or objects of the class share the same variables | The non-static variables are duplicated for each object. |
The scope of static variables is global | The scope of non-static variables is local. |
Static Method | Non-static Method |
These methods support early or compilation-time binding. | They may facilitate runtime, dynamic, or late binding. |
These methods can only access the static variables of their own class and other classes. | They have access to both static and dynamic members. |
No static method overrides are allowed. | They can be bypassed. |
Since only a single memory allocation is performed when the class is launched, less memory is consumed | Each object has its own memory allocation. |
The static keyword in Java provides considerable benefits and is critical in class design and implementation. By learning its properties and applications, you can use its capabilities to optimize your code and enhance efficiency.
While the static keyword has numerous benefits, it is important to understand its restrictions. Static members cannot directly access non-static variables, and static methods cannot be overridden. However, you can still deal with non-static data within static contexts by supplying the non-static keyword in Java, such as non-static variables as method parameters or using other techniques.
In essence, the Java static keyword enables programmers to create class-level members that are accessible by all class instances. You can improve code reusability, optimize memory usage, and simplify access to class-level entities by exploiting its capabilities. Understanding the subtleties of the static keyword is essential for good Java programming and can have a big impact on the quality and efficiency of your product.
Q1. In which portion of memory are static variables stored?
All static variables are stored in the heap memory's PermGen space.
Q2. What distinguishes a static variable from an instance variable?
The distinctive features of static and instance variables are the following:
a) Class variables can be accessed within static blocks, instance blocks, static methods, instance methods, and inner class methods, whereas instance variables can only be accessed within instance members and inner class methods.
b) Class variables are always resolved at compile time, while instance variables are fixed at runtime.
c) In Java, static variables cannot be serialized, whereas it is possible with instance variables.
Q3. Why is a static method also known as a class method?
A static method is also referred to as a class method because it is associated with a class rather than a specific instance of a class. Therefore, it is not necessary to construct an instance of the class in order to invoke and execute static methods.
Q1: What is the difference between the static and final keywords in Java?
The static keyword is used to define class-level members, while the final keyword is used to declare constants or prevent modification of variables, methods, or classes.
Q2: Why is it important to use the static keyword in the main method?
A Java program's main method serves as its entry point, and the JVM needs to declare it as static in order to access it without first creating an instance of the class.
Q3: Are static variables thread-safe in Java?
Static variables are not inherently thread-safe. If multiple threads modify the same static variable concurrently, synchronization mechanisms need to be implemented to ensure thread safety.
PAVAN VADAPALLI
Director of Engineering
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working …Read More
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...