Skip to content

Commit 7a29954

Browse files
authored
Merge pull request #688 from javaistic/static-keyword
Add `static` keyword docs
2 parents bc8d2be + ea4ee66 commit 7a29954

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

src/navs/documentation.js

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,4 +28,5 @@ export const documentationNav = {
2828
pages['continue-statement'],
2929
],
3030
'Java Arrays': [pages['arrays']],
31+
'Java OOPS': [pages['static-keyword']],
3132
}

src/pages/docs/static-keyword.mdx

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
---
2+
title: Java static keyword
3+
description: In this tutorial, we will learn how to use the Java static keyword.
4+
---
5+
6+
## What is a `static` keyword in Java?
7+
8+
In Java, if we want to access class members, we must first create an instance of the class. But there will be situations where we want to access class members without creating any variables.
9+
In those situations, we can use the `static` keyword in Java. If we want to access class members without creating an instance of the class, we need to declare the class members static.
10+
The `Math` class in Java has almost all of its members static. So, we can access its members without creating instances of the Math class.
11+
12+
### Example 1
13+
14+
```java
15+
public class Main {
16+
public static void main( String[] args ) {
17+
18+
// accessing the methods of the Math class
19+
System.out.println("Absolute value of -12 = " + Math.abs(-12));
20+
System.out.println("Value of PI = " + Math.PI);
21+
System.out.println("Value of E = " + Math.E);
22+
System.out.println("2^2 = " + Math.pow(2,2));
23+
}
24+
}
25+
```
26+
### Output:
27+
28+
```bash
29+
Absolute value of -12 = 12
30+
Value of PI = 3.141592653589793
31+
Value of E = 2.718281828459045
32+
2^2 = 4.0
33+
```
34+
In the above example, we have not created any instances of the Math class. But we are able to access its methods: `abs()` and `pow()` and variables: `PI` and `E`.
35+
36+
It is possible because the methods and variables of the Math class are static.

0 commit comments

Comments
 (0)