Java Static Functions : Conventions and Usage
Static Keyword in Java Language
Java programming language and JVM (Java Virtual Machine) sandbox environment allows defining new types, by class declaration. In Java everything is an object, except for special boxed/unboxed boolean, numeric and string elementary data types. Some Java classes are not instantiable. Let me explain in this blog post, with two key examples of static functions, and static objects in Java language. In the blog post ‘Java Static Functions : Conventions and Usage’ we show conventions of static keyword in Java language, and usage with objects and functions. You can learn more on these lines at introductory programming in Java.
Some of the computer science techniques, patterns if you will, of problem solving are advanced algorithms and design patterns. These are patterns of problem solving that are widely applicable to computer programs used in advanced computer-science algorithms, to those used in GPS systems, and Google Maps for picking your routes. Many of these algorithms use advanced mathematical techniques you can learn.
Several scheduling algorithms that pick best flight routes and ticket prices, like in travel booking websites. Kayak and Priceline use these algorithms. If that all sounds enticing, catch your breath, then read along : this is the beginning of what you can do with computer algorithms and Java.
Overview of Static Objects and Functions
Many design patterns, and one-time, policy enforced resources like standard I/O are designed as classes which contain variables and methods which are static. An easy example is the definition for the output stream in the System package,
public static final PrintStream out
which creates one instance of the output stream that connects to the console.
Static Function Example
Factorial of a number, N, is defined to be the product of numbers from 1 to N; i.e. N! = 1*2*3* … N. Clearly a straightforward way to calculate factorial is using a for-loop where temporary initialized to 1, will have to start incrementing a counter upto N, and keep track of the product. At the end of the iterations the temporary carries the result of the factorial of N.
However yet another equivalent, and accurate, mathematical definition of factorial function is using the recursive notation; i.e. N! = (N-1)!*N
In other words it is a mathematical statement saying, if you want factorial of N, N!, and you know the factorial of (N-1), (N-1)!, then here is how you can calculate the factorial of N.
We can write this program both recursively and iteratively, we choose the recursive way,
class Demo { public static int factorial(int N) { if ( N == 1 ) return 1; return Demo.factorial( N -1 )* N; } public static void main(String [] args) { for( int i = 0; i < 10; i++ ) { System.out.println("Hello world "+Integer.toString(i)); } // simple recursion function System.out.printf(" 1! = %d, 2! = %d, 10! = %d \n", Demo.factorial(1), Demo.factorial(2), Demo.factorial(10)); } }
Compiling the program
Compiling and running this program in Eclipse or Oracle (Sun) Java compiler javac as in Makefile, from Linux platform, using commands
all:
javac Demo.java
java Demo
where, $ javac Demo.java , is the command to compile the code, and then run the program, $java Demo , would give us results like,
Hello world 0 Hello world 1 Hello world 2 Hello world 3 Hello world 4 Hello world 5 Hello world 6 Hello world 7 Hello world 8 Hello world 9 1! = 1, 2! = 2, 10! = 3628800
Execution Model and JVM
The Java Virtual machine executes the program from the contents of the Demo.class file, which is compiled bytecode of your Demo.java program. First it uses the class loaded to find the static ‘main’ function with signature,
public static void main(String [] args)
which is defined in the class Demo, and starts off execution from here. This is one key example of how any Java code designed to be run from the terminal as a separate process needs to have its own main() function.
Static Object Example – Singleton Design Pattern
Let’s say you have to write a program to model a central bank, the Federal Reserve in the USA. You will need to have enforce the policy that the government, the federal reserve, can alone issue bank notes. So anyone who wants to issue notes, in this case, has to request the one instance of the federal reserve. We can manage situations like multiple requests, and remaining balance, freezing accounts etc in this fashion.
Programmers call this design pattern the Singleton. Save the following code as Singleton.java, and compile and run the code just like we did the previous example.
import java.io.*; import java.lang.*; //default include // model the Federal Reserve in the USA. class TheFed { double m_AvailableMoney; private static TheFed s_instance = null; private static TheFed getInstance(){ if ( s_instance == null ) { s_instance = new TheFed(); } return s_instance; } // note c-tor is private private TheFed(){ m_AvailableMoney = 1000e12; //1000 trillion } public static void printNotes(double value) throws Exception { TheFed fed = getInstance(); if ( fed.m_AvailableMoney < 0 ) { throw new Exception("Fed cannot print money; we are under-drafted!"); } if ( (value > fed.m_AvailableMoney) ) { throw new Exception("Fed cannot issue these notes; we will be under-drafted!"); } fed.m_AvailableMoney -= value; System.out.println("We are issuing notes for "+Double.toString(value)); System.out.println("Our available balance is "+Double.toString(fed.m_AvailableMoney)); } } public class Singleton{ public static void main( String [] args) throws Exception { TheFed.printNotes( 1e9 ); // need a billion TheFed.printNotes( 1e12); // need a trillion } } //public static final PrintStream out
And when you compile and run the code as ‘$ java Singleton’ you should see the output,
We are issuing notes for 1.0E9 Our available balance is 9.99999E14 We are issuing notes for 1.0E12 Our available balance is 9.98999E14
However if you modify the code to create an instance, an object of the class TheFed outside the class, you will get a compile time error,
$ javac Singleton.java Singleton.java:38: TheFed() has private access in TheFed TheFed f = new TheFed(); ^ 1 error
Our current example demonstrates static objects which are useful in Java design.
Summary
The two examples in this blog demonstrate static functions and static objects which are useful in Java design for distinct and useful functionality. If you want to learn more and write advanced Java programs some training maybe in order.
Recommended Articles
Top courses in Java
Java students also learn
Empower your team. Lead the industry.
Get a subscription to a library of online courses and digital learning tools for your organization with Udemy Business.