diff --git a/src/navs/documentation.js b/src/navs/documentation.js index 980e2103..a25d09e5 100644 --- a/src/navs/documentation.js +++ b/src/navs/documentation.js @@ -28,4 +28,5 @@ export const documentationNav = { pages['continue-statement'], ], 'Java Arrays': [pages['arrays']], + 'Java OOPS': [pages['static-keyword']], } diff --git a/src/pages/docs/static-keyword.mdx b/src/pages/docs/static-keyword.mdx new file mode 100644 index 00000000..ee43672a --- /dev/null +++ b/src/pages/docs/static-keyword.mdx @@ -0,0 +1,36 @@ +--- +title: Java static keyword +description: In this tutorial, we will learn how to use the Java static keyword. +--- + +## What is a `static` keyword in Java? + +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. +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. +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. + +### Example 1 + +```java +public class Main { + public static void main( String[] args ) { + + // accessing the methods of the Math class + System.out.println("Absolute value of -12 = " + Math.abs(-12)); + System.out.println("Value of PI = " + Math.PI); + System.out.println("Value of E = " + Math.E); + System.out.println("2^2 = " + Math.pow(2,2)); + } +} +``` +### Output: + +```bash +Absolute value of -12 = 12 +Value of PI = 3.141592653589793 +Value of E = 2.718281828459045 +2^2 = 4.0 +``` +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`. + +It is possible because the methods and variables of the Math class are static.