# Data types & Variables

Let us write a simple equation in math to calculate mean of a set of numbers:

a = 15, b = 35, c = 55

mean = (a + b + c) / 3 = 35

To do this simple calculation, you may be using mental math or a calculator. But if you are writing a Java program to do so, then you first have to understand how to declare variables a,b,c and mean, understand the data types (integers, real numbers, text etc..) that can be assigned to your variables and finally, understand the various arithmetic operators that you can use.
In this lesson we will learn all of these simple concepts.

### Primitive Data Types

In Java programming all variables must be first declared, before they can be used:

Example of first declaration and then assignment

int a;
a = 20;

In the above code snippet, first variable a is declared to be of type int and in the next line it is assigned (a.k.a. initialized) a value of 20. If you try to assign a value before declaration, Java compiler throws an error as before any assignment, it should be first declared. Initialization is the way to give a value to the variable. If given no value, Java assumes that the value is "0" for integer and decimal types, false for a boolean and null for String types.

Variables can be of different data types. They represent a memory location and hold a value and can be changed by the program.

Example of declaration and assignment in the same line

int b = 15;

In the above example ‘b’ is a variable, declared to be of type int and is assigned a value 15. Both declaration and assignment is in the same statement.

A variable's data type determines the type and size of values it may contain. The data types in Java can be broadly classified as primitive types and object types. String is an object type.

Java supports seven primitive data types.

• byte: The byte data type is an 8-bit signed two's complement integer. It can hold a minimum value of -128 and a maximum value of 127. Default value is 0.
• short: The short data type is a 16-bit signed two's complement integer. It can hold a minimum value of -32,768 and a maximum value of 32,767 (inclusive).

• int: The int data type is a 32-bit signed two's complement integer. It can hold a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive). For integral values, this data type is generally the default choice.

• long: The long data type is a 64-bit signed two's complement integer. It can hold a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive). Use this data type when you need a range of values wider than those provided by int. If an integer literal ends with the letter L or l then it is long, otherwise it is of type int. You can use either uppercase ‘L’ or lowercase ‘l’ when defining a long literal. It is recommended that you use the uppercase letter L because the lower case letter l is hard to distinguish from the digit 1.

• float: The float data type is a 32-bit decimal number. Its range of values is beyond the scope of this discussion, but is specified in the Floating-Point Types, Formats, and Values section of the Java Language Specification. 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. Numbers and Strings covers BigDecimal and other useful classes provided by the Java platform.

• double: The double data type is a 64-bit decimal number. Its range of values is beyond the scope of this discussion, but is specified in the Floating-Point Types, Formats, and Values section of the Java Language Specification. For decimal values, this data type is generally the default choice. As mentioned above, this data type should never be used for precise values, such as currency.

• 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.

• 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).

A literal is the Java code representation of a value. Literals can be assigned as a value to a primitive data type.

Examples of literals

``````
boolean isEmpty = true;
char capitalC = 'C';
int i = 100000;
byte b = 100;
short s = 10000;
``````

Integer literals can be expressed by these number systems:

• Decimal: Base 10, whose digits consists of the numbers 0 through 9; which is the standard number system in use outside the programming world.

• Hexadecimal: Base 16, whose digits consist of the numbers 0 through 9 and the letters A through F. This system used by programmers mostly and is beyond the scope of this book.

• Binary: Base 2, whose digits consists of the numbers 0 and 1 (you can create binary literals in Java SE 7 and later). Used by programmers and is beyond the scope of this book.

You will use decimal system in this book. However, if you need to use another number system, the following example shows the correct syntax. The prefix 0x indicates hexadecimal and 0b indicates binary:

The number 11, in decimal

int decVal = 11;

int hexVal = 0xB;

The number 11, in binary

int binVal = 0b01011;

#### Example Declarations

Here are some declarations:

``````short myAge ;
double price ;
String myName ;
boolean  likesJava ;
``````

#### Initializing a Variable

Here are examples of initialization:

``````myAge  = 14 ;
price  = 12.95 ;
myName = "Fred Durst" ;
likesJava  = false ;
``````

Variables can be declared and initialized in the one line. In this way we use a single statement to do both, there by, reducing the lines of code. This is the recommended way of writing code.

``````short  myAge = 14 ;
double price = 12.95 ;
String myName = "Fred Durst" ;
boolean likesJava = false ;
``````

### More Examples

Number Variables

int used to represent integers

int year = 2003;

double used to represent numbers with a decimal point

double price = 12.45 ;

double pi = 3.412 ;

String used to represent Text- a sequence of characters.

String myName = "Jayashree Ravi" ;

String gameType = "Modding101";

boolean - boolean - is either true or false

boolean isLearningJava = true ;

boolean likesIceCream = false ;

All the above types are also called primitive data types except for String. String is considered an object. You will learn more about objects in Chapter 5.

#### Variable Names

The rules for creating variable names are similar to the rules for creating identifiers as described in the previous chapter. However from the naming conventions perspective, variable names are noun forms (similar to class names) and start with a small case letter except for constants. Constants are created using upper case letters and underscores to separate words.

Constants are special type of variables which are assigned a value which does not change during the entire execution of the program. For e.g., to keep the value of the number of days in a year (which never changes for any year) you could create a constant and assign the value 365 once and it never changes after that:

int NUMBER_OF_DAYS_IN_YEAR = 365;

Declaration and initialization of the variables should be done prior to its usage in the program. As a convention, you typically keep all variable declarations and initialization as the first set of statements in a block of code.

#### Points to remember!

• Before you assign a value to a variable, it should first be declared.
• When you declare a variable and do not assign a value, the default value is 0 for all numerical types, false value for boolean type and null for String type. You will learn about Strings in the next chapter.
• Before you choose the type, think through the maximum and minimum value that variable may be assigned to.

Sometimes you want to explain your program to others by adding simple sentences in your program. You can do that using comments. Comments are for documentation purposes only and are ignored by the compiler. There are three ways comments can be added to your program:

1. Single line comments inserted after two backslashes `\\`.

2. Multi line comments inserted between a back slash and an asterisk and asterisk and a back slash. `/* ...... */`

3. Javadoc comments are inserted between a back slash and least two asterisks and at least one asterisk and a slash. `/** ..... */`

All the three ways are shown below

``````// This single line comment cannot spill to the next line
public void myFirstMethod(){
....
}
/*
This multiline comment can spill to many lines.
Be sure to enclose with the matching ending comment tag
*/
as shown
*/
public void mySecondMethod(){
....
}
/**
This comment will appear in javadocs when javadoc tool is run against this program. Typically
you never get to use this type of comment unless you are writing a common library or open source software which will be used by
many programmers.
*/
public  void  myThirdMethodWhichHasDocumentation(){
...
}
``````

Before you learn about Javadoc let us first understand the different types of Java API's.

Java Application Programming Interface (a.k.a. core Java API) is a rich library of many classes and methods bundled in many packages. There are two main flavors of core Java API; the official core Java API and OpenJDK both provided by Oracle. The difference between official core API and OpenJDK are minimal and is beyond the scope for this book. OpenJDK is the open sourced version of the official Java API and Google uses OpenJDK for Android.

Apart from the core Java API, there are many open source libraries written for Java which also contain thousands of classes and methods. It is humanly impossible to remember the usage of all classes and methods that any API contains. Reading the documentation of any class as needed, is the only right way of learning and using them in your programs.

Javadoc is a tool which helps build this documentation for every class and method in HTML format for any Java class which contains Javadoc comments for the respective classes and methods. Here is the link to the full documentation (a.k.a docs or Javadocs) for official Java 8 API: https://docs.oracle.com/javase/8/docs/api/

Every programmer should have a cursory glance at the various packages and should refer to the docs as needed while using any class or method of the API.

Although the latest version of Java is 10, Android only supports Java 8 as of this writing.