BIG
DATA

JAVA

VARIABLES AND DATATYPES IN JAVA

Read more about »
  • Java 9 features
  • Read about Hadoop
  • Read about Storm
  • Read about Storm
 

VARIABLES

A Java variable is a piece of memory that can contain a data value. This data can be any kind of information ranging from texts to numbers, temporary results of operations etc.

Below is an example of a class containg all types of variables.


public class MyClass {
	
	String fileName = "coreJava.txt";
	static int fileSize=1024;

    public void display() {
        String message="Hi, this is a local vaiable";
    }
    
    public void read(String filePath) {
        
    }
}

The Java programming language defines the following kinds of variables:

  • Instance Variables (Non-Static Fields) :Objects store their individual states in "non-static fields", that is, fields declared without the static keyword. Non-static fields are also known as instance variables because their values are unique to each instance of a class (to each object, in other words).

    In the above example code, in String fileName = "coreJava.txt"; 'fileName' is instance variable(Non-Static Field).

  • Class Variables (Static Fields) : A class variable is any field declared with the static modifier; this tells the compiler that there is exactly one copy of this variable in existence, regardless of how many times the class has been instantiated.

    In our code, in static int fileSize=1024; 'fileSize' is class variable(Static Field).See the static keyword before datatype int, thats what it makes class variable.

  • Loacal Variables : Similar to how an object stores its state in fields, a method will often store its temporary state in local variables. The syntax for declaring a local variable is similar to declaring a field (for example, int count = 0;). There is no special keyword designating a variable as local; that determination comes entirely from the location in which the variable is declared — which is between the opening and closing braces of a method. As such, local variables are only visible to the methods in which they are declared; they are not accessible from the rest of the class.

    In String message="Hi, this is a local vaiable"; 'message' is local variable.Scope of this variable is only within method 'display'.Outside this method message variable is not accessible.

  • Parameters : You've already seen examples of parameters, in the main method of the "Hello World!" application. Recall that the signature for the main method is public static void main(String[] args). Here, the args variable is the parameter to this method. The important thing to remember is that parameters are always classified as "variables" not "fields".

    In public void read(String filePath) 'filePath' is a parameter.Scope of this variable is also only within its method 'read'.Inside this method, parameter 'filePath' acts like a local variable.Only differnce is that parameter value is passed when method is being called , whereas in local variable value is defined inside method itself.

Naming conventions of Java Variable

The rules and conventions for naming your variables can be summarized as follows:

  • Variable names are case-sensitive. A variable's name can be any legal identifier — an unlimited-length sequence of Unicode letters and digits, beginning with a letter, the dollar sign "$", or the underscore character "_". The convention, however, is to always begin your variable names with a letter, not "$" or "_". Additionally, the dollar sign character, by convention, is never used at all. You may find some situations where auto-generated names will contain the dollar sign, but your variable names should always avoid using it. A similar convention exists for the underscore character; while it's technically legal to begin your variable's name with "_", this practice is discouraged. White space is not permitted.
  • Subsequent characters may be letters, digits, dollar signs, or underscore characters. Conventions (and common sense) apply to this rule as well. When choosing a name for your variables, use full words instead of cryptic abbreviations. Doing so will make your code easier to read and understand. In many cases it will also make your code self-documenting; fields named tyreSize, speed, and gear, for example, are much more intuitive than abbreviated versions, such as x, y, and i. Also keep in mind that the name you choose must not be a keyword or reserved word.
  • If the name you choose consists of only one word, spell that word in all lowercase letters. If it consists of more than one word, capitalize the first letter of each subsequent word. The names tyreSize and currentGear are prime examples of this convention. If your variable stores a constant value, such as static final int NUM_GEARS = 6, the convention changes slightly, capitalizing every letter and separating subsequent words with the underscore character. By convention, the underscore character is never used elsewhere.

Variable Declaration

The Java programming language is statically-typed, which means that all variables must first be declared before they can be used. This involves stating the variable's type and name. In Java you declare a variable like below:
type name;
In above instead of the word type, you replace with data type of variable.Similarly, instead of the word name you write the name you want the variable to have. Like for example,
String myVar;
If a vaiable is of static type, then add keyword static before datatype. static String myVar;

Variable Assignment

In Java you can assign a variable like below:
variableName = value;
Like for example,
myVar="corejavaguru";
fileSize=1024;
amount=99.9;

You can also declare and assign a variable in single line, like this:
String myVar="corejavaguru";

Variable Reading

You can read the value of a Java variable by using its name anywhere a variable can be used in the code. For instance, as the right side of a variable assignment, as parameter to a method call, or inside a arithmetic expression. For instance:

int fileSize = 1024;
int newFileSize = fileSize;
newFileSize = fileSize * 4;
System.out.println(newFileSize);

DATATYPES

Data types specify size and the type of values that can be stored in an variable.In java, data types are classified into two catagories :

  • Non-Primitive Data type
  • Primitive Data type
Non-Primitive(Reference) Data type

A reference data type is used to refer to an object.We will discuss about reference data type in later chapters.

Primitive Data type

A variable of a primitive data type contains the value of the variable directly in the memory allocated to the variable.Once a primitive data type has been declared its type can never change, although its value can change. The Java language contains 8 primitive data types, which can be grouped into 4:

Integer
  • byte: The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). The byte data type can be useful for saving memory in large arrays, where the memory savings actually matters. They can also be used in place of int where their limits help to clarify your code.
    Default value of byte is zero. Example: byte b=9;
  • short: The short data type is a 16-bit signed two's complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive). As with byte, the same guidelines apply: you can use a short to save memory in large arrays, in situations where the memory savings actually matters.
    Default value of short is zero. Example: short s=9;
  • int: By default, the int data type is a 32-bit signed two's complement integer, which has a minimum value of -231 and a maximum value of 231-1. In Java SE 8 and later, you can use the int data type to represent an unsigned 32-bit integer, which has a minimum value of 0 and a maximum value of 232-1.
    Default value of int is zero. Example: int i=9;
  • long: The long data type is a 64-bit two's complement integer. The signed long has a minimum value of -263 and a maximum value of 263-1. In Java SE 8 and later, you can use the long data type to represent an unsigned 64-bit long, which has a minimum value of 0 and a maximum value of 264-1. Use this data type when you need a range of values wider than those provided by int.
    Default value of long is zero. Example: long l=9000;
Floating-Point Number
  • float: The float data type is a single-precision 32-bit IEEE 754 floating point.As with the recommendations for byte and short, use a float (instead of double) if you need to save memory in large arrays of floating point numbers. This data type should never be used for precise values, such as currency. For that, you will need to use the java.math.BigDecimal class instead.
    Default value of float is 0.0f. Example: float ff=99.9f;
  • double: The double data type is a double-precision 64-bit IEEE 754 floating point.As mentioned above, this data type should never be used for precise values, such as currency.
    Default value of double is 0.0d. Example: double db=99.123;
Characters
  • char: The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).
    Example: char ch='a';
Boolean
  • boolean: The boolean data type has only two possible values: true and false. Use this data type for simple flags that track true/false conditions. This data type represents one bit of information, but its "size" isn't something that's precisely defined.
    Default value of boolean is false. Example: boolean b=true;

In addition to the eight primitive data types listed above, the Java programming language also provides special support for character strings via the java.lang.String class. Enclosing your character string within double quotes will automatically create a new String object; for example, String s = "this is a string";. String objects are immutable, which means that once created, their values cannot be changed. The String class is not technically a primitive data type, but considering the special support given to it by the language, you'll probably tend to think of it as such. You'll learn more about the String class in Strings.

Default Values

It's not always necessary to assign a value when a field is declared. Fields that are declared but not initialized will be set to a reasonable default by the compiler.The following chart summarizes the default values for the above data types.

Data Type Default Value
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d
char '\u0000'
String (or any object)   null
boolean false