Please disable adblock to view this page.

← Go home

Final/Const in Java


May 2, 2017
Published By : Pratik Kataria
Categorised in:

Why use final / constant variable?

  • Currently in Java, developers create constant variables i.e. variables whose value don’t change with the help of ‘final’ keyword.
  • Such constant variables are named in all uppercase letters.
  • The use of these variables makes the coding easier and the code robust.
  • If you by mistake write incorrect value for constant variable then it is easy to fix as the change needs to be done only once in declaration. file in folder path: K:\Final\model

package model;

public class Bike {

	public static final String HONDA = "Honda";
	public static final String YAMAHA = "Yamaha";

	private String name = "Honda";
	private long color = 0x2E0456;
	private int gearOrNot = 1;

	public Bike() {} //does nothing but must be defined and public

	public Bike(String name, long color, int gearOrNot) { = name; 
		this.color = color;
		this.gearOrNot = gearOrNot;

	public String getName() { return name; }

	public long getColor() { return color; }

	public int getGearOrNot() { return gearOrNot; }

} file in folder path: K:\Final

import model.Bike;
import java.util.List;
import java.util.ArrayList;

public class Vehicle {
	public static void main( String[] args ){

		List<Bike> bikes = new ArrayList<>();

		bikes.add(new Bike(Bike.HONDA, 0x2E0456, 1));
		bikes.add(new Bike(Bike.YAMAHA, 0x2E0854, 1));
		bikes.add(new Bike(Bike.YAMAHA, 0x2E0555, 1));

		for(Bike b: bikes) {
		 	System.out.println(b.getName() +" " + b.getColor() + " " + b.getGearOrNot());