![]() |
![]() |
Java if statement | |
Java if-else statement | |
Java nested if-else | |
Java else-if ladder | |
Java Switch case statement | |
Java Nested Switch Case | |
Java Ternary/Conditional operator |
Java while loop | |
Java do-while loop | |
Java for loop | |
Java Enhanced loop/for each loop | |
Java Labelled for loop | |
Java Nesting of loops | |
Java Break and Continue |
Java Programs | |
Java Keywords Dictionary | |
Java Interview Questions | |
In Java, we can declare the variables in different ways based on their use in the program.
There are 3 types of variables in Java
What is instance variable
public class InstanceVar { String Brand = "HP"; String series ="Spectre"; float screen_size = 34.5f; byte ram_size = 8; void display() { System.out.println("Brand Name : "+Brand); System.out.println("Series : "+series); System.out.println("Screen size : "+screen_size+" cm"); System.out.println("RAM Size : "+ram_size+" GB"); } public static void main(String[] args) { InstanceVar iv = new InstanceVar(); iv.display(); } }
What is class variable?
public class ClassVar { static String RestName = "Eleven Madison Park"; // static variable String cust_name; // instance var int totalOrders; // instance var void display() { System.out.println("\nRestaurant : "+RestName); System.out.println("Customer Name : "+cust_name); System.out.println("Total Orders : "+totalOrders); } public static void main(String[] args) { ClassVar c1 = new ClassVar(); ClassVar c2 = new ClassVar(); ClassVar c3 = new ClassVar(); c1.cust_name = "Niko"; c1.totalOrders = 3; c2.cust_name = "Alex"; c2.totalOrders = 2; c3.cust_name="Emma"; c3.totalOrders = 2; c1.display(); c2.display(); c3.display(); } }
What is Local variable?
NOTE : Java doesn't support global variables like in C and C++ |
public class LocalVar { void display(int getPrice,String itemName) // local var { System.out.println("Item name : "+itemName); System.out.println("Price : "+getPrice); } void display(String itemName, int getPrice) // local var { System.out.println("Item name : "+itemName); System.out.println("Price : "+getPrice); } public static void main(String[] args) { LocalVar local = new LocalVar(); local.display(1200, "Travel Bag"); local.display("Glasses", 600); } }
Scope of the variables is nothing but the life time of a variable. It depends upon the where in the program that variable is declared.
“the area of the program where the variable is accessible is called its scope
”.
In above types, the local variables have only limited scope within it's block.All other types of variables are accessed anywhere.