Java Guide

Java Data Types


Data Type: Data type specifies the size and type of values that can be stored in an identifier. The Java language is rich in its data types. Different data types allow you to select the type appropriate to the needs of the application.

Data types in Java are classified into two types:

•    Primitive which include Integer, Character, Boolean, and Floating Point.
•    Non-primitive which include Classes, Interfaces, and Arrays.
Primitive Data Types:
There are eight primitive data types supported by Java. Primitive data types are predefined by the language and named by a key word. Let us now look into detail about the eight primitive data types.
•    Byte data type is an 8-bit signed two's complement integer.
•    Minimum value is -128 (-2^7).
•    Maximum value is 127 (inclusive)(2^7 -1).
•    Default value is 0.
•    Byte data type is used to save space in large arrays, mainly in place of integers, since a byte is four times smaller than an int.
•    Example: byte a = 100, byte b = -50.
•    Short data type is a 16-bit signed two's complement integer.
•    Minimum value is -32,768 (-2^15)
•    Maximum value is 32,767(inclusive) (2^15 -1)
•    Short data type can also be used to save memory as byte data type. A short is 2 times smaller than an int
•    Default value is 0.
•    Example: short s= 10000 , short r = -20000
•    Int data type is a 32-bit signed two's complement integer.
•    Minimum value is - 2,147,483,648.(-2^31)
•    Maximum value is 2,147,483,647(inclusive).(2^31 -1)
•    Int is generally used as the default data type for integral values unless there is a concern about memory.
•    The default value is 0.
•    Example : int a = 100000, int b = -200000
Long data type is a 64-bit signed two's complement integer.
Minimum value is -9, 223, 372, 036, 854, 775, 808. (-2^63)
Maximum value is 9,223,372,036,854,775,807 (inclusive). (2^63 -1)
This type is used when a wider range than int is needed.
Default value is 0L.
Example: int a = 100000L, int b = -200000L
•    Float data type is a single-precision 32-bit IEEE 754 floating point.
•    Float is mainly used to save memory in large arrays of floating point numbers.
•    Default value is 0.0f.
•    Float data type is never used for precise values such as currency.
•    Example: float f1 = 234.5f
•    Double data type is a double-precision 64-bit IEEE 754 floating point.
•    This data type is generally used as the default data type for decimal values. Generally the default choice.
•    Double data type should never be used for precise values such as currency.
•    Default value is 0.0d.
•    Example: double d1 = 123.4
•    Boolean data type represents one bit of information.
•    There are only two possible values: true and false.
•    This data type is used for simple flags that track true/false conditions.
•    Default value is false.
•    Example: Boolean one = true
•    Char data type is a single 16-bit Unicode character.
•    Minimum value is '\u0000' (or 0).
•    Maximum value is '\uffff' (or 65,535 inclusive).
•    Char data type is used to store any character.
•    Example: char letter A ='A'

Java Tokens:
A java Program is made up of Classes and Methods and in the Methods is the Container of the various Statements and a Statement is made up of Variables, Constants, operators etc.
Tokens are the various Java program elements which are identified by the compiler. A token is the smallest element of a program that is meaningful to the compiler. Tokens supported in Java include keywords, variables, constants, special characters, operations etc.
When you compile a program, the compiler scans the text in your source code and extracts individual tokens. While tokenizing the source file, the compiler recognizes and subsequently removes whitespaces (spaces, tabs, newline and form feeds) and the text enclosed within comments. Let us consider a program
//Print Hello
Public class Hello
Public static void main (String args [])
System.out.println (“Hello Java”);
The source code contains tokens such as public, class, Hello, {, public, static, void, main, (, String, [], args, {, System, out, println, (, "Hello Java",},}. The resulting tokens• are compiled into Java byte codes that is capable of being run from within an interpreted java environment. Token are useful for compiler to detect errors. When tokens are not arranged in a particular sequence, the compiler generates an error message.
Tokens are the smallest unit of Program There is Five Types of Tokens
•    Reserve Word or Keywords
•    Identifiers
•    Literals
•    Operators
•    Separators
Identifiers are names given to classes, methods, variables, objects, arrays, packages and interfaces in a program. These are user defined names.
•    Identifiers are formed with alphabets, digits, underscore and dollar sign characters.
•    The first character must be an alphabet.
•    They can be any length.
•    They are case sensitive.
1.    Class names in Java begin with a capital letter. Class names should be descriptive names or noun phrases but not very long. If class name contains multiple words then each subsequent word in the class name begins with a capital letter. For example: Employee, Grade Book, Commission Employee, ProcessExamResult etc.
2.    Names of the fields that are not final and method's name should begin with a lowercase letter. Method names should be verbs or verb phrases. However, if they contain multiple words then each subsequent word in the name begins with a capital letter. For example: firstName, salary, getName, getMaximum etc.
3.    Names of the packages intended only for local use should have a first identifier that begins with a lowercase letters.
4.    Constant represent fixed values that cannot be altered. For example, PI is constant with a fixed value 3.14159. Such constants should be written in uppercase.
5.    These conventions are followed so that programmers can distinguish whether an identifier corresponds to a class name, variable, method, package in a program.
Keywords are words which belong to java language. They have standard predefined meaning. These words should be used only for their intended purpose. The Keywords should be written in lowercase. Some of the keywords are:
For, do, while, goto, if, else, int, char, byte, switch, new, void, try, catch, public, protected, private, static, throw, throws.
New is a Keyword which is used when we are Creating an object of class for storing all the data like variables and member functions of class there is some memory space that is to be needed so that with the help of new Keyword an object is instantiated or simply an object reserves some memory or some new memory is allocated to class object for storing data and member functions of class .So every object must be created with the help of New Keyword so for allocating new memory area.
A constant value in Java is created by using a literal representation of it.
integer literal value: 100
floating-point literal value: 98.6
character literal value: ‘X’
string literal value: “This is a test”
A literal can be used anywhere a value of its type is allowed.
Integer Literals:
Integer literals are the primary literals used in Java programming. They come in a few different formats: decimal, hexadecimal, and octal. These formats correspond to the base of the number system used by the literal.
Decimal (base 10) literals appear as ordinary numbers with no special notation. Hexadecimal numbers (base 16) appear with a leading 0x or 0X. Octal (base 8) numbers appear with a leading 0 in front of the digits.
For example, an integer literal for the decimal number 12 is represented in Java as 12 in decimal, 0xC in hexadecimal, and 014 in octal.
Integer literals default to being stored in the int type, which is a signed 32-bit value. If you are working with very large numbers, you can force an integer literal to be stored in the long type by appending an l or L to the end of the number, as in 79L. The long type is a signed 64-bit value.
Floating-Point Literals:
Floating-point literals represent decimal numbers with fractional parts, such as 3.1415. They can be expressed in either standard or scientific notation, meaning that the number 143.85 also can be expressed as 1.4385e2.
Unlike integer literals, floating-point literals default to the double type, which is a 64-bit value. You have the option of using the smaller 32-bit float type if you know the full 64 bits are not required. You do this by appending an f or F to the end of the number, as in 5.6384e2f.
Examples of double literals:
0.0 0.0D 0d
0.7 7D .7d
9.0 9. 9D
6.3E-2 6.3E-2D 63e-1
Examples of float literals:
0.0f 0f 7F .7f
9.0f 9.F 9f
6.3E-2f 6.3E-2F 63e-1f
Boolean Literals:
Boolean literals are certainly welcome if you are coming from the world of C/C++. In C, there is no Boolean type, and therefore no Boolean literals. The Boolean values true and false are represented by the integer values 1 and 0.
Java fixes this problem by providing a Boolean type with two possible states: true and false. Not surprisingly, these states are represented in the Java language by the keywords true and false.
Boolean literals are used in Java programming about as often as integer literals because they are present in almost every type of control structure. Any time you need to represent a condition or state with two possible values, a Boolean is what you need. The two Boolean literal values: true and false.
Character Literals:
Character literals represent a single Unicode character and appear within a pair of single quotation marks. Special characters (control characters and characters that cannot be printed) are represented by a backslash (\) followed by the character code. A good example of a special character is \n, which forces the output to a new line when printed.
An example of a Unicode character literal is \u0048, which is a hexadecimal representation of the character H. This same character is represented in octal as \110.
String Literals:
String literals represent multiple characters and appear within a pair of double quotation marks. Unlike all the other literals discussed in this chapter, string literals are implemented in Java by the String class. This arrangement is very different from the C/C++ representation of strings as an array of characters.
When Java encounters a string literal, it creates an instance of the String class and sets its state to the characters appearing within the double quotes.
"false or true"
"result = 0.01"
"Java is an artificial language"
String literals are objects of the class String, so all string literals have the type String.
Java Operators:
An operator is a symbol which helps the user to command the computer to do a certain mathematical or logical manipulations. Operators are used in Java language program to operate on data and variables. Java has a rich set of operators which can be classified as
•    Arithmetic Operators
•    Relational Operators
•    Logical Operators
•    Assignment Operators
•    Increments and Decrement Operators
•    Conditional Operators
•    Bitwise Operators
•    Special Operators
Arithmetic Operators: All the basic arithmetic operations can be carried out in Java. All the operators have almost the same meaning as in other languages. Both unary and binary operations are available in Java language. Unary operations operate on a single operand, therefore the number 5 when operated by unary – will have the value –5.  
x + y
x - y
-x + y
a * b + c
-a * b
Here a, b, c, x, y are known as operands. The modulus operator is a special operator in Java language which evaluates the remainder of the operands after division.
Integer Arithmetic: When an arithmetic operation is performed on two whole numbers or integers than such an operation is called as integer arithmetic. It always gives an integer as the result. Let x = 27 and y = 5 be 2 integer numbers.
Then the integer operation leads to the following results:
x + y = 32
x – y = 22
x * y = 115
x % y = 2
x / y = 5
In integer division the fractional part is truncated                      
Floating Point Arithmetic: When an arithmetic operation is preformed on two real numbers or fraction numbers such an operation is called floating point arithmetic. The floating point results can be truncated according to the properties requirement. The remainder operator is not applicable for floating point arithmetic operands.
Let x = 14.0 and y = 4.0 then
x + y = 18.0
x – y = 10.0
x * y = 56.0
x / y = 3.50    
Mixed mode arithmetic: When one of the operand is real and other is an integer and if the arithmetic operation is carried out on these 2 operands then it is called as mixed mode arithmetic. If any one operand is of real type then the result will always be real thus 15/10.0 = 1.5.
Relational Operators: Often it is required to compare the relationship between operands and bring out a decision and program accordingly. This is when the relational operator comes into picture. Java supports the following relational operators.  
Relational Operator    Description
<    Less than
<=    Less than or equal to
>    Greater than
>=    Greater than or equal to
==    Equal to
=!    Not equal to

It is required to compare the marks of 2 students, salary of 2 persons, we can compare them using relational operators. A simple relational expression contains only one relational operator and takes the following form:
exp1 relational operator exp2
Where exp1 and exp2 are expressions, which may be simple constants, variables or combination of them. Given below is a list of examples of relational expressions and evaluated values.
6.5 <= 25 TRUE
-65 > 0 FALSE
10 < 7 + 5 TRUE
Relational expressions are used in decision making statements of Java language such as if, while and for statements to decide the course of action of a running program.
Logical Operators: Java has the following logical operators; they compare or evaluate logical and relational expressions.  
Logical AND (&&): This operator is used to evaluate 2 conditions or expressions with relational operators simultaneously. If both the expressions to the left and to the right of the logical operator is true then the whole compound expression is true.
a > b && x = = 10
The expression to the left is a > b and that on the right is x == 10 the whole expression is true only if both expressions are true i.e., if a is greater than b and x is equal to 10.
Logical OR (||): The logical OR is used to combine 2 expressions or the condition evaluates to true if any one of the 2 expressions is true.
a < m || a < n
The expression evaluates to true if any one of them is true or if both of them are true. It evaluates to true if a is less than either m or n and when a is less than both m and n.
Logical NOT (!) : The logical not operator takes single expression and evaluates to true if the expression is false and evaluates to false if the expression is true. In other words it just reverses the value of the expression.
! (x >= y)
The NOT expression evaluates to true only if the value of x is neither greater than nor equal to y.
Assignment Operators: The Assignment Operator evaluates an expression on the right of the expression and substitutes it to the value or variable on the left of the expression.
x = a + b
Here the value of a+b is evaluated and substituted to the variable x. In addition, Java has a set of shorthand assignment operators of the form.
var oper = exp;
Here var is a variable, exp is an expression and oper is a Java binary arithmetic operator. The operator oper = is known as shorthand assignment operator.
x + = 1 is same as x = x + 1
Bitwise Operators:
Java defines several bitwise operators which can be applied to the integer types, long, int, short, char, and byte.
Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and b = 13; Now in binary format they will be as follows:
a = 0011 1100
b = 0000 1101
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
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:
public class Test {
public static void main (String args []) {
int a, b;
a = 10;
b = (a == 1)? 20: 30;
System.out.println ("Value of b is: " + b);
b = (a == 10)? 20: 30;
System.out.println ("Value of b is: " + b);
This would produce following result:
Value of b is: 30
Value of b is: 20

Separators are used to inform the Java compiler of how things are grouped in the code. For example, items in a list are separated by commas much like lists of items in a sentence. The most commonly used separator in Java is the semicolon. As you have seen, it is used to terminate statements.
Semicolon (;):
Terminates statements.
Comma (,):
Separates consecutive identifiers in a variable declaration. Also used to chain statements together inside a for statement.
Braces { }:
Used to contain the values of automatically initialized arrays. Also used to define a block of code, for classes, methods, and local scopes.
Parentheses ( ):
Used to contain lists of parameters in method definition and invocation. Also used for defining precedence in expressions, containing expressions in control statements. Also used for surrounding cast types.
Brackets [ ]:
Used to declare array types. Also used when dereferencing array values.
Period (.):
Used to separate package names from sub packages and classes. Also used to separate a variable or method from a reference variable.


Post a Comment