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
  • 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. If you already know the value to initialize with when a variable is declared, then this is the preferred way of coding; declare the variable and initialize the value in the same statement instead of using two separate statements.

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.

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

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

Values in Other Number Systems

All the examples above used the below defined decimal, base 10 number system for initializing the integer values;

  • Decimal: Base 10, whose digits consists of the numbers 0 through 9; is the standard number system familiar to almost everyone.

However, Java also provides Hexadecimal and Octal number systems as well as described below;

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

The number 11, in hexadecimal

int hexVal = 0xB;

The number 11, in binary

int binVal = 0b01011;

More Example Declarations

Here are some declarations:

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

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.

Java Comment Lines

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() {
     ...
}

What is Javadoc?

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 15 API: https://docs.oracle.com/en/java/javase/15/docs/api/java.base/module-summary.html

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 15, Android only supports Java 8 as of this writing.

What is a package?

Package is nothing but a folder structure into which related classes are added. Typically the package path is created under src/main/java/ folder. In other words, all the folders that are created as children of src/main/java would become a package structure. And 'src/main/java' would be marked as the build-path. Build path is used by the compiler to start searching for all the .java files in various packages to create the .class files for them during the build process. When the .class files are created during the build process, they are added in the respective packages of the .java files. Although the .class and .java are placed in the same package, the root of their packages will be different. .java packages will be under src folder and .class packages will be under build or target folder.

How to compile a Java file that is having a package declaration?

package com.mbcc.tutorial;

public class MyClass {
    public static void main(String[] args) {
        // other java code go here. Here is an example statement
        System.out.println("hello");
    }
}

javac -d . MyClass.java

The -d option will take the directory where the compiled file should be placed. Giving a '.' compiles the file in the current directory. If the class is declared in a package then a directory structure corresponding to the package is created. In the above example, it creates a 'com' folder that has a 'mbcc' folder that has a 'tutorial' folder.

To run the program you execute

java com.mbcc.tutorial.MyClass

What is a API?

API stands for Application Programming Interface. An API provides a simple entry point for using complex programs behind the scenes allowing developers to harness an available set of programs even if they have no expertise in the underlying system of the API. APIs allow developers to work more efficiently by reusing valuable functionality or data. By using the APIs to identify and find existing solutions for common problems, a developer is not only saving time but is also writing elegant code. There is no point in reinventing the wheel when a group of brilliant developers have invented it and exposed the usage of it in the most elegant fashion! Of course after understanding the underlying programs of the API solution, if you are able to find a better solution then you are justified in not using the API but for the most part, the solutions that are found by most popular APIs are well thought out off and would most likely be the best possible solution.

results matching ""

    No results matching ""