Variables & its Declaration

Java Identifiers 
  • All Java variables must be identified with unique names.
  • These unique names are called identifiers.
  • Identifiers can be short names (like x and y) or more descriptive names (age, sum, total).
Identifiers Rules:
  • Names can contain letters, digits, underscores, and dollar signs.
  • Names must begin with a letter.
  • Names should start with a lowercase letter and it cannot contain whitespace.
  • Names can also begin with $ and _.
  • Names are case-sensitive ("myVar" and "myvar" are different variables)
  • Reserved words cannot be used as names.
Variables:
  • Variables are placed in memory to storing values.
  • In Java, there are different types of variables.
  • For example:
    • String - stores text
    • int - stores integers 
    • float - stores floating point numbers
    • char - stores single characters
    • boolean - stores : true or false
  • Declaring (Creating) Variables
    • To create a variable, you must specify the type and assign it a value.
    • Synatx:
      • datatype variable_name;
      • datatype variable_name = value;
    • Example:
      • int age;
      • int age=101;
    • To declare more than one variable of the same type, use a comma-separated list.
    • Syntax:
      • datatype var1, var2, var3,...;
      • datatype var1= value1, var2=value2, var3=value3...;
    • Example:
      • int f1,f2,f3;
      • int p1=10,p2=20,p3=30;
    • Where datatype is one of Java's data types and variable_name is the name of the variable. 
    • The equal sign is used to assign values to the variable.
  • Declaring Final Variables
    • However, you can add the final keyword if you don't want others (or yourself) to overwrite existing values (read-only).
    • Syntax: final datatype variable_name = value;
    • Example: final int myNum = 15;
  • Display Variables
    • The println() method is often used to display variables.
      • Example: System.out.println(myNum);
    • The print() method is used to display value on same line.
      • Example: System.out.print(myNum);
    • To combine both text and a variable, use the + character:
      • Example: System.out.println("My Number value" + myNum);


Thanks a lot for query or your valuable suggestions related to the topic.

Previous Post Next Post

Contact Form