Static Function or Method and Its Usage in Java
On this page (10sections)
Introduction
Static Function or Method and Its Usage in is a classic Java console program that demonstrates the concept with complete source code and sample output. These programs cover your first Java class, constructors, methods and simple OOP building blocks.
This tutorial walks through the program line by line, explains how the logic works, and highlights best practices you can apply in your own code.
Static Function Overview
- Static method or variable belongs to the class and not to object.
- Static method or variable can be used to all Objects created from the same class.
- Static variables initialized only once in the time of class loading.
- It Can use Static method or variable without instance creation.
- Static methods can be overloaded.But can not be overridden.
Syntax
class ClassName{
public <ReturnType> static methodName() {
//Do Something
}
}
Static Function or Method and Its Usage in Java Example Program
public class StaticMethodAndUsages {
public static int staticMethod(){
int num1 = 100, num2 = 200,result;
result = num1+num2;
return result;
}
public static void main(String[] args) {
System.out.println("Result from static method is : "+staticMethod());
}
}
Sample Output
Result from static method is : 300
When to use
Use this static function or method and its usage in example when learning or revising core Java syntax.
How it works
-
Execution begins in the
mainmethod — the JVM calls this method when you run the class. -
int num1 = 100, num2 = 200,result;updates a variable used in the calculation or output. -
result = num1+num2;updates a variable used in the calculation or output. -
A
println/printcall writes text to the console — part of the sample output below. -
Compare your console output with the sample output for Static Function or Method and Its Usage in to confirm the program behaves correctly.
Best Practices
- Name classes in PascalCase and follow one public class per file when starting out.
- Keep
mainshort — delegate work to other methods as programs grow.
Common Mistakes
- Copying code without understanding each line — practice by changing one statement at a time.
- Mismatching the public class name and the
.javafilename. - Forgetting semicolons at the end of statements.