Please disable adblock to view this page.

← Go home

All about static snippet (Java)

April 27, 2016
Published By : Pratik Kataria
Categorised in:

import java.util.Random;

public class Emp {

	//To get a unique employee id i.e. it doesn't starts with 0
	static private int empId;		
	private int actualEmpid;
	private String empName;
	private int empSal;
	static private String compName;		
	static private int totalEmp = 0;
	//Java has 3 things: Static data, static function and static block
		//This is executed just after creation of object. After object creation, static datas are created n then static block.
		System.out.println("Static block created...");			
		Random random = new Random();		
		//Random number in the range 0-1000
		empId = random.nextInt( 1000 );		
	Emp(){		//Constructor
		//Post increment so that it is assigned first and then incremented
		this.actualEmpid = empId++;		

	public String getEmpName() {
		return empName;

	public void setEmpName(String empName) {
		this.empName = empName;

	public int getEmpSal() {
		return empSal;

	public void setEmpSal(int empSal) {
		this.empSal = empSal;

	public static String getCompName() {
		return compName;

	public static void setCompName(String compName) {
		Emp.compName = compName;

	public static int getTotalEmp() {
		return totalEmp;

	public static void setTotalEmp(int totalEmp) {
		Emp.totalEmp = totalEmp;
	public void display(){
		System.out.println("Emp. ID : " + this.actualEmpid + " Name: " + empName + " Emp. Salary: " + empSal + " Company Name: " + Emp.compName);
public static void main(String [] args){
		//because of static we can do this before creation of any object.
		Emp e1 = new Emp();
		Emp e2 = new Emp();
		System.out.println("The total number of employees registered are: " + Emp.getTotalEmp());


Static block created…
Emp. ID : 905 Name: Pratik Emp. Salary: 5000 Company Name: Rambo
Emp. ID : 906 Name: Rohit Emp. Salary: 6000 Company Name: Rambo
The total number of employees registered are: 2

View Article Page

Pratik Kataria is currently learning Springboot and Hibernate.
Technologies known and worked on: C/C++, Java, Python, JavaScript, HTML, CSS, WordPress, Angular, Ionic, MongoDB, SQL and Android.
Softwares known and worked on: Adobe Photoshop, Adobe Illustrator and Adobe After Effects.