Java Variables WITH SUTABLE EXAMPLE| Add two numbers java variable with example

 

Java Variables


In Java, a variable is a named memory location that stores data of a particular data type. Variables can hold different types of values, such as numbers, characters, and boolean values.

Java variables can be classified into three categories based on their scope:

Local variables: These variables are declared within a method or block of code and are only accessible within that block of code.


Instance variables: These variables are declared within a class but outside of any method or block of code. They are accessible to all methods and blocks within the class.


Class variables: Also known as static variables, these variables are declared with the static keyword within a class and outside of any method or block of code. They are shared by all instances of the class and can be accessed using the class name.


Java variables also have a data type that determines the type of data that can be stored in the variable. For example, the int data type is used for variables that store integer values, while the String data type is used for variables that store strings of characters.


To declare a variable in Java, you must specify its data type, followed by the variable name. For example, to declare an integer variable named "num", you would use the following syntax

You can also initialize the variable at the time of declaration by providing an initial value. For example

Once a variable is declared and initialized, you can use it in your Java code by referring to its name. For example:

java

  intx=5;inty=10;intsum=x + y

System.out.println("The sum of x and y is: "+ sum);

In the above example, the variables x, y, and sum are all of the int data type and are used to perform a simple arithmetic operation and print the result.


In the above example, the variables x, y, and sum are all of the int data type and are used to perform a simple arithmetic operation and print the result.


Java Variable Example: Add Two Numbers

  1. public class Simple{    
  2. public static void main(String[] args){    
  3. int a=10;    
  4. int b=10;    
  5. int c=a+b;    
  6. System.out.println(c);    
  7. }  
  8. }    
  9. Output:

    20
  10. Java Variable Example: Narrowing (Typecasting)

    1. public class Simple{  
    2. public static void main(String[] args){  
    3. float f=10.5f;  
    4. //int a=f;//Compile time error  
    5. int a=(int)f;  
    6. System.out.println(f);  
    7. System.out.println(a);  
    8. }}  

    Output:

    10.5
    10
    

Previous Post Next Post