How to declare variables in java?

    Data types are the key elements of any programming language. Generally, any programming language has two categories of datatypes given below.

  • ·       Primitive datatypes
  • ·       Non primitive datatypes

1.Primitive Datatypes:

              Primitive data types are the basic and built in datatypes. These can be classified into numeric and non-numeric.

Eg: Numeric primitive data type: int (byte, short, int, long), float, double.

      Non-Numeric primitive data type: char, Boolean.

2. Non-primitive data types:

        Non Primitive data types are like user defined datatypes.

Eg: Array, String

How to declare these variables???

  • ·       First, create a class in java. Save this file as “myVar.class”. This class includes the primitive data types of variables.

class myVar

{

              public static void main(String args[])

              {

              }

}

  • ·       Let us Create numeric data types variables.

    class myVar

    {

              public static void main(String args[])

              {

                int myInt =10;

                byte myByte = 100;

                short mySh = 100;

                float myFloat =2.3f;

               double myDouble = 3.67;

                char myChar = 'a';

                String myStr = "Java Programming";

                boolean myBool =true;

                System.out.println("Printing integer variable myInt:"+myInt);

                System.out.println("Printing byte variable myByte:"+myByte);

               System.out.println("Printing short variable mysh:"+mySh);

                System.out.println("Printing Boolean variable myBool:"+myBool);

                System.out.println("Printing floating variable myFloat:"+myFloat);

                System.out.println("Printing Double variable myDouble:"+myDouble);

                System.out.println("Printing char variable myChar:"+myChar);

                System.out.println("Printing String variable myStr:"+myStr);

              }

    }

  • ·       Execute this program. You will get the below output.

  • ·       Next Program is to declare variables in non-primitive data types.
  • ·       Here, declare a string variable and integer array. Assign the values and print it.

    import java.util.Arrays;

    class myVar1

    {

     public static void main(String args[])

     {

      String a = "Java Programming";

      int[] b = new int[]{1,2,3,4,5};

      System.out.println("Printing String a:"+a);

      System.out.println(Arrays.toString(b));

    }

    }

  • ·           When executing this program,You get this output.

    These are the ways to create different types of variables in java. Here, primitive and non primitive data type variables are created, assigned with values and displayed using output statements.

No comments:

Post a Comment