Java is a Strongly Typed Language: It is important to state that at the beginning that Java is a strongly typed language. Indeed, part of Java’s safety and robustness comes from this fact. First, every variable has a type, every expression has a type and every type is strictly defined. Second, all assignments, whether explicit or via parameter passing in the method calls are checked for type compatibility. There are no automatic coercions or conversions of conflicting types as in some languages. The Java compiler checks all expressions and parameters to ensure that the types are compatible. Any type mismatches are errors that must be corrected before the compiler will finish compiling the class.

The Primitive Types

Java defines eight primitive types of data: byte, short, int, long, char, float, double and boolean. The primitive types are also commonly referred to as simple types, and both terms will be used in this book. These can be put in four groups:

  • Integer: This group includes byte, short, int and long, which are for whole valued signed numbers.
  • Floating point numbers: This group includes float and double, which represent numbers with fractional precision.
  • Characters: This group includes char, which represents symbols in a character set, like letters and numbers.
  • Boolean: This group includes boolean, which is a special type for representing true/false values.

Integers

Java supports four integer types: byte, short, int, and long. All of these are signed, positive and negative. Java does not support unsigned, positive only integer. Java’s designers felt that unsigned integers were unnecessary.

The width of an integer types vary widely as shown in this table:

Name Width Range
long 64 -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
Int 32 -2,147,483,648 to 2,147,483,647
short 16 -32,768 to 3267
byte 8 -128 to 127

byte:

The smallest integer type is byte. This is a signed 8 bit type that has a range from -128 to 127. Variables of type byte are especially useful when we are working with a stream of data from a network or file. They are also useful, when we are working with raw binary data that may not be directly compatible with Java’s other built in types:

byte variables are declared by use of the byte keyword. For example, the following declares two byte variables called b and c

byte b,c;

 

 

short:

 short is a signed 16 bit type. It has a range from -32,768 to 32,767. It is probably the least used Java types, since it is defined as having its high byte first called big endian format. This type is mostly applicable to 16 bit computers, which are becoming increasing scarce.

Here are some examples of short variable declarations:

short s;

short t;

int

The most commonly used integer type is int. It is a signed 32 bit type that has a range from -2,147, 483,648 to 2,147,483,647. The int type is the most versatile and efficient type, and it should be used most of the time when we want to create a number for counting or indexing arrays or doing integer math.

long

long is a signed 64 bit type and is useful for those occasions where an int type is not large enough to hold the declared value. The range of long is quite large. This makes it useful when big, whole numbers are needed. For example, here is a program that computes the number of miles that light will travel in a specified number of days.

public class Light {

    public static void main(String[] args) {

   int lightSpeed;

   long days;

   long seconds;

   long distance;

   lightSpeed = 186000;

   days = 1000;

   seconds = days*24*60*60;

   distance = lightSpeed*seconds;

   System.out.println ("In "+days);

  System.out.println (" days light will travel about "+distance+" miles");

}   

}

 

The output of the above program is:

In 1000 days light will travel about 16070400000000 miles

Floating Point Types:

Floating point numbers, also known as real numbers, are used when evaluating expressions that require fractional precision. For example, calculations such as square root, or transcendental such as sine or cosine, result in a value whose precision requires a floating point type. Java implements the standard (IEEE-754) set of floating point types and operators. There two kinds of floating point types, float and double, which represent single and double precision numbers respectively. Their width and ranges are shown here:

Name Width in Bits Approximate Range
Double 64 4.9 e-324 to 1.8 3+308
Float 32 1.4 e-045 to 3.4 e+038

Floating Point:

They type float specifies a single precision value that uses 32 bits of storage. Single precision is faster on some processors and takes half as much space as double precision, but will become impressive when the values are either very large or very small. Variables of type small are useful when we need a fractional component but do not require a large degree of precision. For example, float can be useful when representing dollars and  cents:

float hightemp, lowtemp;

double :

 Double precision, as denoted by the double keyword, uses 64 bits to store a value. Double precision is actually faster than single precision on some modern processors that have been optimized for high speed mathematical calculations. All transcendental math functions, such as sin(), cos() and sqrt() return double values. When we need to maintain accuracy over many iterative calculations or are manipulating large valued numbers, double is the best.

Here is the small program that uses double variable to compute the area of a circle:

public class Area {

    public static void main(String[] args) {

   double pi,r,a;

   r = 10.8;

   pi = 3.1426;

   a = pi*r*r;

   System.out.println("The area of circle = "+a);

    }

}

 

The out is:

The area of circle = 366.55286400000006.

Characters

In Java, the data type used to store characters is char. Instead, Java uses Unicode to represent characters. Unicode defines a fully international character set that can represent all of the characters found in all human languages

Thus, in Java char is a 16 bit type. The range of a char is 0 to 65535. There are no negative chars. The standard set of characters known as ASCII still ranges from 0 to 127 as always.

The following program, demonstrates char variable.

public class CharDemo{

    public static void main(String[] args) {

        char ch1;

        ch1 = 'X';

        System.out.println ("ch1 contains "+ch1);

        ch1++;

        System.out.println ("ch1 now contains "+ch1);       

    }

}

 

This program prints:

ch1 contains X

ch1 now contains Y

Booleans

Java has a primitive type, called boolean, for logical values. It can have only one of two possible values, true or false. This is the type returned by all relational operators, such as a<b. boolean is also the type required by the conditional expressions that govern the control statements as if and for.

Here is a program that demonstrates the boolean type:

public class BoolTest{

    public static void main (String[] args) {

        boolean b;

        b = false;

        System.out.println ("b is "+b);

        b = true;

        System.out.println ("b is now "+b);

        If (b)

        System.out.println ("This is executed ");

        b = false;

        System.out.println ("This is not executed ");

    }

}

 

The output is:

b is false

b is now true

This is executed

This is not executed

A closer look at Literals

In Java, literals refer to fixed values that are represented in human readable form. Literals are also called constants. For example, the number 100 is a literal. Java literals can be of any primitive data types.

Java language specifies five major types of literals.

  • Integer Literal: Integer literals are specified as numbers without fractional components. For example, 10 and -100 are integer literals. By default, integer literals are of type If we want to specify a long literal, we append and I or and L. For example, 12 is an int, but 12L is long.

Hexadecimal, Octal and Binary Literals:  A hexadecimal literal begins with 0x or 0X. An octal literal begins with zero (0). The binary literal begins with 0b or 0B.

Hex = 0xFF

Oct = 0177

Binary 0b1101

  • Floating Literal: Floating point literals require the use of the decimal point followed by the number’s fractional component. For example, 11.123 is a floating point literal. Floating literals are also represented in scientific notations. For example, 1.234E2 represents the value 123.4. By default, floating point literals are of type double. To specify a float literal, append an F or f to the constant. For example, 10.19F is of type

As a point of interest, Java also allows hexadecimal floating point literals, but they are seldom used

  • Character Literal: A literal character is represented inside a pair of single quotes. All of the visible ASCII characters can be directly entered inside the quotes, such as ‘a’,’z’ and’@’. For characters that are impossible to enter directly, there are several escape sequences which allows entering the character we need. For example ‘\n’ for new line character.
  • String Literal: The string literal is a set of characters enclosed by double quotes. For example, “This is a text” is a string literal.
  • Boolean Literal: Boolean literals are simple. There are only two logical values that a boolean value can have, true and The values of true and false do not convert into any numerical representation. The true literal in Java does not equal to 1, nor the false literal equal to 0. In Java, they can only be assigned to variables declared as boolean.

 

Variables

 The variable is the basic unit of storage in a Java program. A variable is defined by the combination of the identifier, a type and an optional initializer. In addition, all variables have a scope, which defines their visibility and a lifetime.

Declaring a Variable:  In Java, all variables must be declared before they can be used. The basic form of variable declaration is as follows:

type identifier [=value];

The type is one of Java’s atomic types, or the name of a class or interface. The identifier is the name of the variable. We can initialize the variable by specifying an equal sign and a value.

Here are several examples of variable declarations of various types.

int a , b, c;

int d = 3; e, f = 5;

double pi = 3.14159;

char ch = ‘x’;

Dynamic Initialization: Java allows variables to be initialized dynamically, using any expression valid at the time the variable is declared. Let us consider the following small program

class DynamicInitialization {

public static void main (String args[]){

double a = 3.0, b = 4.0;

double c = Math.sqrt(a*a+b*b);

System.out.println (“Hypotenuse is “+c);

}                    

}

 

Here, three local variables –a, b, c are declared. The first two, a and b are initialized by constants. However, c is initialized dynamically to the length of the hypotenuse.

The Scope and Lifetime of Variables

Java allows variables to be declared within any block. A block starts with an opening curly brace and ends with a closing curly brace. A block defines a scope. Thus, each time, we are creating a new block; we are creating a new scope. A scope determines what objects are visible to other parts of our program. It also defines the lifetime of those objects.

Many other programming languages define two general categories of scopes: global and local. These scopes do not fit with Java. Java defines two types of scopes: scope defines by class and scope defined by method. The scope defined by class will be discussed in the coming topics.

The scope defined by method begins with its opening curly brace. This includes parameters of method. As a general rule, variable declared inside a scope are not visible (accessible) to code that is defined outside that scope.

The variables are created when the scope is entered, and destroyed when their scope is left. This means that variable will not hold its value once it has gone out of scope. Thus life time of a variable is confined to its scope.

The scope of the variable can be illustrated by following program.

public class Scope {

public static void main(String[] args) {

   int x =10;//known to all code within main

   if(x==10){

       int y=20; //known only to this block

       System.out.println("x and y: "+x+" "+y);

       x = y+2;

   }

   //y = 20; Error! y is not known here

   // x is still known here;

    System.out.println("x is now "+x);  

}   

}

 

The output of the above program is:

x and y: 10 20

x is now 22

Type Conversion and Casting

There are two types of type conversions in Java. They are:

  • Implicit Conversion
  • Explicit Conversion

Implicit or automatic Type Conversions

When one type of data is assigned to another type of variable, an automatic type conversion will take place if the following two conditions are met:

  • The two types are compatible.
  • The destination type is larger than the source type

When these two conditions are met, a widening conversion takes place. For example, the int type is always large enough to hold all valid byte values, so no explicit cast statement is required. The numeric types are not compatible with char or boolean.

Casting Incompatible Types

To create a conversion between two incompatible types, we must use a cast. A cast is simply an explicit type conversion. It has this general form:

(target-type)value;

Here, target-type specifies the desired type to convert the specified value to. Let us consider the following example:

int a ;

byte b;

b = (byte)a;

The following program illustrates type conversion using cast.

public class Conversion {

    public static void main(String[] args) {

   byte b;

   int i=257;

   double d = 323.123;

        System.out.println("Conversion of int to byte.");

        b = (byte)i;

        System.out.println("i and b "+i+" "+b);

        System.out.println("Conversion of double to int");

        i = (int)d;

        System.out.println("d and i "+d + " "+i);

        System.out.println("Conversion of double to byte");

        b = (byte)d;

        System.out.println("d and b "+d+" "+b);

}   

}

 

The output of the above program is:

Conversion of int to byte.

i and b 257 1

Conversion of double to int

d and i 323.123 323

Conversion of double to byte

d and b 323.123 67

Automatic Type Conversion in Expressions

 

In addition to assignments, there is another place where certain type conversion may occur: expressions. Let us consider the following program.

byte a = 40;

byte b = 50;

byte c  = 100;

int d = a*b/c;

The result of the intermediate term a*b easily exceeds the range of either of its byte operands. To handle this kind of problem, Java automatically promotes each byte or short operand to int while evaluating an expression.

Sometimes expressions can cause confusing compile time errors. For example, this seemingly correct code causes a problem.

byte b = 50;

b = b*2; // Error! Cannot assign an int to a byte!.

The operands are automatically promoted to int when the expression is evaluated; the result has also been promoted to int. Thus, the result of the expression is now of type int, which cannot be assigned to an byte without the use of a cast.

The Type Promotion Rules

Java defines several type promotion rules that apply to expressions. They are as follows: First, all byte and short values are promoted to int. Then, if one of the operand is long, then whole expression is promoted to long. If one operand is float, then the entire expression is promoted to float. If any of the operands is double, the result is double.

 

The following program illustrates this:

 

public class Promote{

public static void main(String[] args) {

byte b = 42;

char c = 'a';

short s = 1024;

int i = 5000;

float f = 5.76f;

double d = 0.1234;

double result = (f*b)+(i/c)-(d*s);

System.out.println("The result = "+result); 

}

}

 

The output of the above program is:

The result = 166.55841342773437

 

Arrays: An array is a group of like-typed variables that are referred to by a common name. Array of any type can be created and may have or more dimensions. A specific element in an array is accessed by its index.

 

One dimensional Array:  In one dimensional array, a list of items can be given one variable name using only one subscript. This type of array is also called single subscripted variable. The declaration for one dimensional array is as follows:

type arr_name[];

Here, type declares the base type of the array. The base type determines the data types of each element that comprises the array. For example, the following declares an array named month_days with the type “array of int”:

int month_days [];

This declaration establishes the fact that month_days is an array variable, no array actually exists. To link month_days with an actual, physical array of integers, we must allocate one using new and assign it to month_days. new is a special operator that allocates memory.

The general form of new as it applies to one dimensional arrays appears as follows:

array_var = new type[size];

Here, the type specifies the type of the data being allocated, size specifies the number of elements in the array, and array_var is the array variable that is linked to the array. The elements in the array allocated by new will automatically be initialized to zero.

month_days = new int[12];

Let us consider the following example:

Let us consider the following program:

 class Array {

    public static void main(String[] args) {

   int months[] = {31,28,31,30,31,30,31,31,30,31,30,31};

        System.out.println("The length of arrays is :"+months.length);

        System.out.println("December has "+months[11]+" days");       

}    

}

 

The output of above program is:

The length of arrays is : 12

December has 31 days

Let us consider one more example. It finds the average of a set of numbers.

class Average {

   public static void main(String[] args) {

   double nums[] = {10.1,11.2,12.3,8.4,14.8,13.4};

   double result = 0.0;

   int i;

   for(i=0;i<5;i++)

   result = result+nums[i];

   System.out.println("Average is "+result/5);       

} 

}

The output of the above program is:

Average is 11.36

Multidimensional Arrays

In Java, multidimensional arrays are actually arrays of arrays. To declare a multidimensional array variable, specify each additional index using another set of square brackets. For example, the following declares a two dimensional array variable called twoD

Int twoD[][] = new int[4][5];

This allocates a 4 by 5 array and assigns it to twoD. Internally this matrix is implemented as an array of arrays of int.

Let us consider the following example

public class TwoDArray {

   public static void main(String[] args) {

   int twoD[][] = new int[4][5];

   int i,j,k=0;

   for(i=0;i<4;i++)

       for(j=0;j<5;j++)

           twoD[i][j]=k++;




   for(i=0;i<4;i++){

       for(j=0;j<5;j++)

           System.out.print(twoD[i][j]+" ");

       System.out.println();

} 

}

}

 

The output of the above program is:

0 1 2 3 4

5 6 7 8 9

10 11 12 13 14

15 16 17 18 19

 

Important:

The multidimensional array is actually arrays of array; the length of each array is under our control. Let us consider following example:

public class TwoDArr {

   public static void main(String[] args) {

   int twoD[][] = new int[4][];

   twoD[0] = new int[1];

   twoD[1] = new int[2];

   twoD[2] = new int[3];

   twoD[3] = new int[4];

   int i,j,k=0;

   for(i=0;i<4;i++)

   for(j=0;j<i+1;j++)

   twoD[i][j]=k++;

   for(i=0;i<4;i++){

   for(j=0;j<i+1;j++)

   System.out.print(twoD[i][j]+" ");

   System.out.println();

}

} 

}

 

The output of the above program is:

0

1 2

3 4 5

6 7 8 9

Alternative Array Declaration Syntax

There is a second form that may be used to declare an array.

type [] var-name;

Here, the square brackets follow the type specifier, and not the name of the array variable. For example, the following two declarations are equivalent:

int a1[] =  new int[3];

int[] = new int[3];

The following declarations are also equivalent:

char twod1 [][] = new char[3][4];

char twod2[][] = new char[3][4];

This alternative declaration form offers convenience when declaring several arrays at the same time. For example,

int  [] nums1, nums2, nums3;

creates three array variables of type int. It is same as writing

int nums1[] , nums2[], nums3[];

The alternative declaration form is also useful when specifying an array as a return types for a method.

Scanner Class

There are various ways to read input from the keyboard; the java.util.Scanner class is one of them.

The Java Scanner class breaks the input into tokens using a delimiter that is whitespace by default. It provides many methods to read and parse various primitive values.

Java Scanner class is widely used to parse text for string and primitive types using regular expression.

Java Scanner class extends Object class and implements Iterator and Closeable interfaces.

There is a list of commonly used Scanner class methods:

Method Description
public String next() it returns the next token from the scanner.
public String nextLine() it moves the scanner position to the next line and returns the value as a string.
public byte nextByte() it scans the next token as a byte.
public short nextShort() it scans the next token as a short value.
public int nextInt() it scans the next token as an int value.
public long nextLong() it scans the next token as a long value.
public float nextFloat() it scans the next token as a float value.
public double nextDouble() it scans the next token as a double value.

Let’s see the simple example of the Java Scanner class which reads the int, string and double value as an input:

import java.util.Scanner;  

class ScannerTest{  

 public static void main(String args[]){  

   Scanner sc=new Scanner(System.in);       

   System.out.println("Enter your rollno");  

   int rollno=sc.nextInt();  

   System.out.println("Enter your name");  

   String name=sc.next();  

   System.out.println("Enter your fee");  

   double fee=sc.nextDouble();  

   System.out.println("Rollno:"+rollno+" name:"+name+" fee:"+fee);  

   sc.close();  

 }  

}

 

Why does java use Unicode?

Ans: Java was designed for worldwide use. Thus, it needs to use a character set that can represent the world’s language. Unicode is the standard character set designed expressly for this purpose. Of course, the use of Unicode is inefficient for languages such as English, German, and Spanish or French, whose character can be contained within eight digits. But such is the price that must be paid for global portability.

Leave a Reply

Your email address will not be published. Required fields are marked *