Data types, Variables and Arithmetic Operators

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;

The number 11, in hexadecimal

int hexVal = 0xB;

The number 11, in binary

int binVal = 0b01011;

Example Declarations

Here are some declarations:

int 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:

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

More Examples

Number Variables

int used to represent whole numbers

int age = 9; 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 likesIceCreams = 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 8.

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.

Comments

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

The Arithmetic Operators

Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. The following table lists the arithmetic operators:

Assume integer variable a = 10 and variable b = 20, then:

Operator Description Example
+ Addition - Adds values on either side of the operator a + b will give 30
- Subtraction - Subtracts right hand operand from left hand operand a - b will give -10
* Multiplication - Multiplies values on either side of the operator a * b will give 200
/ Division - Divides left hand operand by right hand operand b / a will give 2
% Modulus - Divides left hand operand by right hand operand and returns remainder b % a will give 0
++ Increment - Increases the value of operand by 1 b++, ++b gives 21 equivalent to b = b +1;
-- Decrement - Decreases the value of operand by 1 b-- , --b gives 19 Equivalent to b = b-1;

The Relational Operators

Following are the relational operators supported in Java language

Assume variable a = 10 and variable b = 20, then:

Examples

Operator Description Example
== Checks if the values of two operands are equal or not, if yes then condition becomes true. (a == b) is not true.
!= Checks if the values of two operands are equal or not, if values are not equal then condition becomes true. (a != b) is true.
> Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true. (a > b) is not true.
< Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. (a < b) is true.
>= Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true. (a >= b) is not true.
< = Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true. (a < = b) is true.

The Logical Operators

The following table lists the logical operators:

Assume Boolean variables a = true and variable b = false, then:

Examples

Operator Description Example
&& Called Logical AND operator. If both the operands are non-zero, then the condition becomes true. (a && b) is false.
|| Called Logical OR Operator. If any of the two operands are non-zero, then the condition becomes true. (a || b) is true.
! Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true then Logical NOT operator will make false. !(a && b) is true.

The Shorthand Assignment Operators:

These are the shorthand assignment operators supported in Java:

Examples

Operator Description Example
+= Add AND assignment operator, It adds right operand to the left operand and assign the result to left operand c += a
is same as
c = c + a
-= Subtract AND assignment operator, It subtracts right operand from the left operand and assign the result to left operand c -= a
is same as
c = c - a
*= Multiply AND assignment operator, It multiplies right operand with the left operand and assign the result to left operand c *= a
is same as
c = c * a
/= Divide AND assignment operator, It divides left operand with the right operand and assign the result to left operand c /= a
is same as
c = c / a
%= Modulus AND assignment operator, It takes modulus using two operands and assign the result to left operand c %= a
is same as
c = c % a

Points to remember!

  • The result of any division operation is a double type
  • Use shorthand notations where ever possible
  • Java uses the standard PEMDAS (Parenthesis, Exponents, Multiplication and Division, Addition and Subtraction) order when evaluating several operators in the same expression. When there are multiple instances of the same precedence, Java reads from left to right.

Using Scanner

Scanner is a very useful class present in java.util package used to obtain input from the user. You have so far been able to pass input to your program as a program argument. When you send input this way, you have to run your program every time you want to change your argument. Using Scanner, you can send input to your program, when the program is running.

To create an object of Scanner class, you generally pass System.in argument, which represents the standard input stream.

Here is an example of using Scanner:

import java.util.Scanner; //notice the import statement for scanner!

public class ScannerDemo{

    public static void main(String[] args){

        Scanner sc = new Scanner(System.in);

        System.out.println("Hi, please input your name");

        String name = sc.nextLine(); // get a String value
        System.out.println("Hi " + name);

        System.out.println(name + ", please input your age");
        int age = sc.nextInt(); // get an int value
        System.out.println("Glad to know you are " + age + " old!");

        System.out.println(name + ", please input your height in inches");

        double height = sc.nextDouble(); // get a double value
        System.out.println("Glad to know you are " + height + "inches tall!");    
    }
}

To use the scanner you have to first import it in your code. Import statements always come on the top of your class name. Any class which is not in of java.lang package should be important. Any class which is within the java.lang package does not need an import statement.

Here is the javadoc for Scanner: https://docs.oracle.com/javase/9/docs/api/java/util/Scanner.html Can you study the documentation and figure out what method to use to get an integer value from the console using Scanner? If you did not find the method name from the documentation, the next example will show you.

Conditional Operator ( ? : )

Conditional operator is also known as the ternary operator. This operator consists of three operands and is used to evaluate Boolean expressions. The goal of the operator is to decide which value should be assigned to the variable. The operator is written as:

variable x = (expression) ? value if true : value if false

Following is the example:

import java.util.Scanner; 

public class OddEvenFinder {
   public static void main(String args[]){

       Scanner sc = new Scanner(System.in);
       System.out.println("Please enter a number and our little program will tell you if you entered an odd or even number");
       int a = sc.nextInt(); // this method will expect you to input an integer value on the console.
       String kind =  (a % 2 == 0) ? "even": "odd";

       System.out.println(a + " is an " + kind + " number");
   }
}

results matching ""

    No results matching ""