Unit 2
Unit 2
2.0 Introduction
2.1 Objectives
2.2 Data Types
2.2.1 Integers and Floating Point Data Type
2.2.2 Character and Boolean Types
2.2.3 Enumerated Types
2.3 Unicode
2.4 Variables
2.4.1 Java Keywords
2.4.2 Variables and Literals
2.5 Operators
2.6 Statements and Expressions
2.7 Example Program Using Scanner Class
2.8 Summary
2.9 Solutions/ Answer to Check Your Progress
2.10 References/Further Readings
2.0 INTRODUCTION
Java is an object-oriented, general-purpose programming language. The popularity of Java
programming language is more because of its features. Basic features of Java include security,
robustness, distributed, multithreading, and a rich library for Graphical User Interface (GUI), but
one of its main characteristic of it is : being Architecture-Neutral and platform- independent,
which we have studied in the previous unit of this Block. To write a program in any
programming language, first of all, we need to know the basic facilities that the programming
language provides. For example, support of different data types, operators, basic programming
constructs for decision making or constructs of looping etc., are the basic facilities Java provides.
In this unit, we will learn to use basic building blocks of Java, such as data types, java keywords,
variables, literals, operators, statements and expressions. To improve your programming
concepts, you can move towards learning of declaration and initiations of different data types
and variables. An operator is a symbol that informs the compiler to perform some operation on
the given data. Java provides several operators. Java expression is built from variables using
different operators. In addition to expression, you will learn statements in Java, which are
equivalent to sentences in natural languages. A statement is a complete unit of execution. At the
end of this unit, you will be able to write java programs using the scanner class.
2.1 OBJECTIVES
1
describe the different data types in Java,
declare and initialize variables in Java,
know reserved words in Java,
define Variables and Literals,
use appropriate Operators in writing programs,
use statements and expressions in program, and
write Java programs using Scanner class.
In programming, we use variables to store values. A variable stores values according to its
declared type. Every programming language provides some primitive data types for storing
values and evaluating expressions. Java provides primitive data types(basic types), which
are statically-typed, which means you need to declare all variables before using them.
There are eight basic data types in Java, which include four types of integer values in ‘int’ data
type, two types of fractional values in ‘float’ data type, character data type in ‘char’ and true or
false values in ‘boolean’ data type. The int, float, char and boolean are keywords that can not be
used as variable names. Java primitive types are given in Table 1.1
Data
Size in Description Example Groups Range
Type
byte
1 byte-length -128 to 127
byte 15, 25
integer
2 -32,768 to 32,767
short short integer 550, 986
4 -2^31 to 2^31-1
int Integer 9, 95, 378, 465 Integer
8 -2^63 to 2^63-1
long long integer 989L, -545L
4 Single-precision -3.4e38 to 3.4e38
float 809.5f, -232.2f, Floating
floating point
point
8 Double-precision 2289.5,-4535.5, numbers
-1.7e308 to 1.7e308
double
floating point 27.6E5
1 true or false
char A single character ‘a’, ‘9’, ‘t’ ‘A’ Characters
1 bit A boolean value '\u0000' to '\uffff'
boolean true or false Boolean
(0 or 1)
2
Following is the Java program to display the size and range of Java primitive data types.
Example Program:
package javadatatyperange;
public class JavaDataTypeRange
{
public static void main(String args[])
{
System.out.println("Size and Range of different Java Data Type ");
System.out.println("Data Type\t Size\t Min. Value\t\t Max. Value\t");
System.out.println("Byte\t\t" + Byte.SIZE + "\t" + Byte.MIN_VALUE
+ "\t\t\t" + Byte.MAX_VALUE);
System.out.println("Short\t\t" + Short.SIZE + "\t" + Short.MIN_VALUE
+ "\t\t\t" + Short.MAX_VALUE);
System.out.println("Integer\t\t" + Integer.SIZE + "\t" + Integer.MIN_VALUE
+ "\t\t" + Integer.MAX_VALUE);
System.out.println("Float\t\t" + Float.SIZE + "\t" + Float.MIN_VALUE
+ "\t\t\t" + Float.MAX_VALUE);
System.out.println("Long\t\t" + Long.SIZE + "\t" + Long.MIN_VALUE + "\t"
+ Long.MAX_VALUE);
System.out.println("Double\t\t" + Double.SIZE + "\t" + Double.MIN_VALUE
+ "\t\t" + Double.MAX_VALUE);
System.out.println("Character\t" + Character.SIZE +"\t" + (int)Character.MIN_VALUE
+ "\t\t\t" + (int)Character.MAX_VALUE);
}
}
If you write and run(execute) the above Java program , it give the following output.
Output:
3
In the above programe you can see that to print the size of a data type (name of datatype).SIZE
is used. To print the minimum value, a data type can store (Name of data type).
MIN_VALUE is used. Similarly, to print the maximum value, a data type can store (Name of
data type). MAX_VALUE is used. You can notice that the first word of the data type is written
in capital. Also Character.MIN_VALUE and Character.MAX_VALUE is converted into an
integer ( here, type casting is done). “/t”(tab) is used for proper alignments of output, the use of
“/t” is similar to pressing the tab on our keyboard.
In most of programming languages, the format and size of primitive data types depend on the
platform on which program code is running. But in Java , the size and format of its primitive data
types is specified, and it frees programmers from the system dependencies while writing program
and using the data types. For example, an int is always 32 bits in Java, regardless of the platform
on which the Java program runs. This allows programs to be written with the guarantee to run
without porting on any machine architecture. All the primitive data types can be divided into four
major groups, as shown in Table-1.1. Now let us learn the use of these primitive data types in
detail.
2.2.1 Integers and Floating Point Data Type
Integers and Floating-point numbers are used to store numeric data values. Java has six numeric
data types, as shown in Table 1.1. They differ in size and precision of the numbers they can hold.
The size of a data type means how many bits are needed to represent that data type. The range of
a data type represents how small/big value can be stored in that data type with the precision of
numbers.
Integers
To store an integer value, you need to declare a variable of integer type, and int keyword is used
for it. The integer variable can be declared as follows:
int age;
The data type of the variable declared above is int, and the name of the variable is age. The
declaration ends with a semicolon. You can store only an integer value in variable age. There are
4
four types available in Java for integer values. These four types are signed variables that can
store either a positive or negative value, as shown in Table 2.2.
As a programmer, you need to choose a variable of any of the four types according to your need
in the application. You may use byte if you are expecting a very small integer value for your
variable. For example, to store student age, you may use a variable of type byte. The int is mostly
used to store an integer value; for a bigger range of integer values, the long integer type is used.
Let us see the four types of integers declared below:
byte age;
short year;
int No_of_Smart_City;
long AccoutNo;
The above declarations of variables of integer types are according to the range of values they can
store.
As an example, the notation of 1035 can also be presented as E35. In table 2.3 , 1038 is presented
as E38 in the table. The declaration of a floating-point variable is as follows:
5
float price = 156. 50F;
This statement declares a variable price by initializing it with a floating point constant 156.50F.
if F is not appended to the constant, then the value is, by default, double type.
The declaration for the double type is the same as that for the float type but will not have the F
towards the end of the constant. Following is a variable earning_ratio declared as double.
The above statement initializes the variable MyChar with a Unicode character representing P.
The character constant assigned to a character variable must be enclosed within single quotes.
“The character enclosed within single quotes is treated as a character constant and that without
single quotes is treated as a variable by the compiler”.
Apart from character variables and constants, Java also provides Escape Sequences character
constants. All the character constants are specified inside a pair of single quotes. Some characters
cannot be entered directly using the pair of quotes. A backslash followed by a character is used
to indicate to the compiler that it has a different meaning. Such sequences of characters are
called Escape Sequences or Escape Characters. The sequence is typed as two characters with no
blank in between the characters. The use of backslash suppresses the meaning of an escape
sequence character. To display double quotes inside a string, \” is used so that it will display
double quotes and not the end of the string. Though the escape sequence is of two characters, it is
treated as a single character. A list of Escape Sequences is shown in Table 2.4.
6
4. \b Backspace
5. \f Form feed
6. \n New line
7. \r Carriage return
8. \t Horizontal Tab
Booleans
In Java, Boolean variables are used as logical variables with either true or false values. The
Boolean variable has only two values: true or false. These two values are Boolean constants.
Different attributes of the boolean data type are given in Table2.5.
Table 2.5: Boolean Data Type
Type Values Default Size
1 bit used in 32
boolean true, false false
bit integer
In the above statement, a boolean variable aTeacher is declared and initialized with the boolean
value true.
The constants are those variables whose values are unchangeable. An enumerated data type is a
special data type in Java . It is a user-defined data type which consists of a set of predefined
values.
Enumerations: An enum is a special "class" used for representing a group of constants, were
added to the Java language in JDK5. In Java, enumeration defines a class type. It is created using
the enum keyword. Each enumeration constant is public, static and final by default. In Java,
final variables are also constant variables. About the final variable, you will learn later in this
course. The enumeration variables can be used and declared in much the same way as a primitive
variable.
An enumeration can be defined simply by creating a list of enum variables. You may create
an enum using the enum keyword, and you have to separate the constants using a comma. The
general format of an enumerated type declaration:
7
Example of creating enumeration :
Another Example:
enum PGDCA_NEW_Courses-I
{ MCS-201, MCS-202, MCS-203, MCS-204, MCSL-205}
8
2.3 UNICODE
In Java to fully understand the char type, you need to know about the Unicode encoding scheme.
Before Unicode, many other coding standards, such as ASCII , ISO 8859-1, KOI-8, GB18030
etc. were used in different regions of the world. Having the use of different coding standards
caused two main problems:
1. A code value corresponds to different letters in the different encoding schemes.
2. The encodings in the case of those languages which have large character sets have variable
lengths.
To solve these problems, Unicode was designed to solve these problems. With the attempt of the
unification effort started in the 1980s, it was decided to have a fixed 2-byte code to encode all
characters used in all languages in the world. The “Unicode 1.0 was released, using slightly less
than half of the available 65,536 code values. Java was designed from the ground up to use 16-
bit Unicode characters, which was a major advance over other programming languages that used
8-bit characters”.
Unicode is a universal character encoding standard. It is “an international encoding standard
for use with different languages and scripts, by which each letter, digit, or symbol is assigned a
unique numeric value that applies across different platforms and programs.” This standard
includes roughly about 100000 characters to represent characters of different languages. While
ASCII uses only 1 byte Unicode uses 4 bytes to represent characters. Hence, it provides a very
wide variety of encoding. “Unicode covers all the characters for all the writing systems of the
world, modern and ancient”. It also includes technical symbols, punctuations, and many other
characters used in writing text. The most widely used forms of Unicode are:
UTF-32, is most appropriate for single-encoding characters. It uses 32-bit code units,
each of which is used for storing a single code point.
UTF-16 uses one or two 16-bit code units for each code point. It is the default encoding
for Unicode.
UTF-8, with one to four 8-bit code units (bytes) for each code point.
2.4 VARIABLES
In Java there are some predefined keywords; they are particular words that act as a key to a code.
These keywords are also known as reserved words by Java, so you can not use them as a variable
or object name or class name. As you know, a variable is a titled portion of the memory used to
store data that is required in any program, perhaps even in other than Java programming
language also. A variable can store only one type of data. In this section, you will learn more
about java keywords, variables, and literals.
break Used to exit a loop before the end of the loop is reached
Used to Specify the class base from which the correct class is
extends
inherited
10
implements Declares that this class implements the given interface
package For defining the package to which this source code file belongs
strictfp For declaring a method or class must be run with exact IEEE 754
semantics
11
volatile Indicates to the compiler that a variable changes asynchronously
Java is case-sensitive, so even though the break is a keyword, Break is not a keyword at all. At
the time of designing Java, its designers decided to make it case-sensitive because, first of all,
this enhances the readability of code; secondly, it reduces the compilation time and increases the
efficiency of the compiler. All the Java technology keywords are in lowercase. The words true,
false, and null are reserved words. Java keeps on adding new keywords as per need. Java 1.4
adds the assert keyword to specify assertions. As we have seen above in table 2.6, each keyword
has a specific and well-defined purpose.
Variables
In programming, we use variables to store data that is used in any program. Like other
languages, Java also expects the variables to be declared and used. A variable is a titled portion
of the memory. You can use a variable to store only one type of data. For example, if a variable
is declared to store an integer, it can store only integer data. Java predefines the type of data
stored in a variable. Java variables are declared by a name and their type. The name given to a
variable is called an identifier. There are a few guiding rules for naming a variable, which is as
follows:
The name of a variable may be of any length.
The name of a variable must start with an alphabet, underscore ( _ ) or a dollar symbol ($).
The remaining characters of the variable name can be alphabetic or numeric.
Special characters such as @,% etc., are not allowed as part of the name of variables.
Underscore ( _ ) can be used to connect two words such as first _ name, student_marks etc.
As Java is case-sensitive hence the variables Age and age are treated as two different
variables.
Blanks or tabs may not be used in variable names.
As a programmer, you are free to give any names to the variables, and only you cannot use the
keywords defined by Java as the name of the variable. Also, it is advisable that naming a variable
should reflect the purpose for which it is declared in a program. The variable names should be
meaningful such as book_tiltle, name, username and password, age, marks etc. This makes your
program more readable. In Java, the naming convention followed is:
the variable name starts with a lowercase alphabet
the remaining words, the first alphabet is an uppercase alphabet
12
Declaring and Initialization Variables
As you are aware, before using any variable, you have to declare it. After it is declared, you can
then assign values to it. Also you can declare and assign a value to a variable at the same time.
Java actually has three kinds of variables:
Instance variables
Class variables
Local Variables.
You will learn more about instance variables and class variables in unit 4 of this Block. Instance
variables are those variables which are used to define the attributes of a particular object. Class
variables are similar to instance variables, except their values is the same for all the objects of a
class rather than having different values for each object of the class. Local variables are declared
for the local consumption of the methods; for example, for index counters in a for loop,
temporary variables to keep some values or to hold values that you need only inside the method
definition itself.
Variable Declarations
In Java, a general variable declaration looks like the following:
datatype identifier [= default value] {, identifier [= defaultvalue] };
Let us consider the following variable declarations:
byte b;
int age;
boolean male;
char c;
Also, it is possible to declare multiple variables of one type in one expression, as given below:
int age, enrollnum, accountno;
Variable declarations can be anywhere in your code as long as they precede the first use of the
variable. However, it is common practice to place the declarations at the top of each block of
code. Variable names in Java can only start with a letter, an underscore ( _), or a dollar sign ($).
They cannot start with a number. After the first character, your variable names can include
letters, numbers, or a combination of both.
As you know, the Java language is case sensitive, implying that the variable x in lowercase is
different from variable X in uppercase. In Java, a variable name cannot start with a digit or
hyphen. The names of the variables should be kept in such a way which may help you
understand what is happening in your program. Therefore you should keep the name of your
variables intelligently or according to their role in the program. Your variable's name cannot
contain any white space. There is no limit to the length of a variable name in Java.
13
Suppose you want to begin a variable name with a digit, prefix underscore, with the name, e.g.
_1Name. You can also use the underscore in the variable name to provide better readability and
meaning, e.g. Student_age.
You will learn more about assignment operators later in this unit.
Literals
The constants or data values used in a program are called literals. Each literal is of a particular
type. For example, the percentage of marks for a student is 78.25, which is a literal and fractional
value, and its type is elaborated on in the subsequent section.
Primitive types in Java are called literals. A literal is the source code representation of a fixed
value in memory. Literals are nothing but pieces of Java code that indicate explicit values. For
example, "Hello IGNOU!" is a String literal. The double quote marks indicate to the compiler
that this is a string literal. The quotes indicate the start and the end of the string, but remember
that the quotation marks themselves are not a part of the string. Similarly, Character Literals are
enclosed in single quotes, and it must have exactly one character. TRUE and FALSE are boolean
literals that mean true and false. Number, double, long and float literals also exist there. See
examples of all types of literals in the following Table 2.7.
Table 2.7: Examples of literals
Constants
Constants are used for fixed values. Their value never changes during the program execution. To
declare constants in Java keyword final is used. The following statement defines an integer
constant x containing a value of 25.
final int x =25;
14
Check Your Progress- 1
1) What is literal in Java?
………………………………………………………………………………………………
…………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
2) Write a program in Java to calculate the Area of a circle. Show the use of the ‘final’
keyword in your program.
………………………………………………………………………………………………
…………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
3) What is boolean data type in Java?
………………………………………………………………………………………………
…………………………………………………………………………
……………………………………………………………………………………
……………………………………………………………………………………
In the next section, we will explore the different types of operators in Java with their meaning
and uses in the programs.
2.5 OPERATORS
An operator is a symbol that informs the compiler to perform some operation on the given data.
Java provides several operators. The operations can be classified into four categories: arithmetic,
relations, logical and bitwise. Each category is explained briefly in the subsequent sections.
Arithmetic operators
You must be friendly with arithmetic expressions in mathematics like ‘A – B’. In this expression
A and B are operands and the subtraction sign ‘ – ‘ is the Operator. The same terminology is also
used here in the programming language. The following table lists the basic arithmetic operators
provided by the Java programming language, along with their descriptions and uses. Descriptions
of arithmetic operators are defined in Table 2.8(a). Operators are divided into two categories
Binary and Unary. Addition, subtraction, multiplication etc. are binary operators and applied
only on two operands. Increment and decrement are unary operators and are applied on a single
operand.
15
Table 2.8(a): Description of arithmetic operators(Binary Operators)
Operator Use Description
+ A+B Adds A and B
- A–B Subtracts B from A
* A*B Multiplies A by B
/ A/B Divides A by B
% A%B Computes the remainder of dividing A by B
package javaarithmeticoperator;
import java.util.Scanner;
public class JavaArithmeticOperator
{
public static void main(String[] args)
{
int A,B,C,D,E;
Scanner s=new Scanner (System.in);
System.out.println ("Enter an Integer Value A : ");
A=s.nextInt ( ) ;
16
B= A/2;
System.out.println ("Value of A/2 is :" + B);
System.out.println ("Enter an Integer Value C : ");
C=s.nextInt ( ) ;
D= B+C;
System.out.println ("Value of D ( i.e. A/2 +C) is :" + D);
}
}
Ouput:
17
Output:
Relational Operators
Relational operators, also called comparison operators, are used to determine the relationship
between two values in an expression. As given in Table 2.9, the return value depends on the
operation.
package javarelationaloperator;
public class JavaRelationalOperator
{
public static void main(String[] args)
{
int A, B, C,D,E;
boolean i,j,k;
A =6;
B=4;
C=5
D=6
i = C>=D;
j = A<B;
k = A !=B;
System.out.println("Result of Comparision C >= D is:"+i);
System.out.println("Result of Comparision A>B is:"+j);
System.out.println("Result of Comparision A !=B is:"+k);
}
}
18
Output:
Boolean Operators
Boolean operators allow you to combine the results of multiple expressions to return a single
value that evaluates to either true or false. Table 2.10 describes the use of each boolean Operator.
Table 2.10: Description of Boolean operators
Bitwise operators
As you know, in computers, data is represented in binary (1’s and 0’s) form. The binary
representation of the number 43 is 0101011. The first bit from right to left in the binary
representation is the least significant, i.e., the value is 1 here. Each Bitwise Operator allows you
19
to manipulate integer variables at bit level. Table 2.11 given below, describes the use of the
bitwise Operator with the help of a suitable example for each.
package javabitwiseoperators;
public class JavaBitwiseOperators
{
public static void main(String[] args)
{
int A, B, C,D,E;
A =6;
B=4;
C= A<<2;
D = ~B;
E = A&B;
System.out.println("Value of A<<2 is:"+ C);
System.out.println("Value of ~B is:"+ D);
System.out.println("Value of A&B is:"+E);
}
}
20
Output:
Assignment Operators
The basic assignment operator ‘=’ is used to assign value to the variables. For example, I = J; in
which we assign the value of J to I. Similarly, let us see how to assign values to different data
types.
Along with basic assignment operators, Java has defined shortcut assignment operators that
allow you to perform arithmetic, shift, or bitwise operation with one Operator. For example, if
you want to add a number to a variable and assign the result back into the same variable, then
you will write something like i = i + 2;
but using shortcut operator ‘+=’ , you can shorten this statement, like
i += 2
Here remember, i = i + 2; and i += 2; both statements are the same for the compiler.
As given in Table 2.12, Java programming language provides different shortcut assignment
operators:
21
One variable named var is initialized as
int var = 50;
to realize the assignment arithmetic operation. Here the variable var has the value of 50
.
When the following statements make use of the assignment arithmetic operators
var = var + 1 (or) var + = 1;
The above notations are equal, and the usage of these notations is left to the discretion of the
programmer. The value of var is 50; it is added with 1, and the results of the above statements
assign 51.
The value of the variable var is 51 is subtracted by 5, and the result 46 is assigned to var.
The value of the variable var is 46 multiplied by 3, and the result 138 is assigned to a.
The value of the variable var is 138 which is divided by 4; the result is 34.5, and the integer part
of the result, that is, 34 is assigned to var . Therefore var will have a value 34.
a % = 5;;
The value of the variable var is 34, and modulus operation with 5 actually divides the 34 by 5
and gives the remainder 4, which is assigned to var.
Multiple Assignments
Example Program
22
package javaassignmentoperator;
public class JavaAssignmentOperator
{
public static void main(String[] args)
{
int i,j,k,l;
float p,q,r;
i= 45;
k=20;
i +=20;
System.out.println("The vale of i is:"+i);
j = ++i +k;
System.out.println("The vale of k is:"+k);
j *=2;
System.out.println("The vale of j is:"+j);
k /=2;
System.out.println("The vale of k is:"+k);
}
}
Output:
23
It accesses a method or field of a class or object.
For example, A.B is used for ‘field access for
"." Class Member Access
object A’, and A.B() is used for ‘method access for
object A’
For example, A(parameters) , Declares or calls the
() Method Invocation
method named A with the specified parameters.
(type) A, in this example () operator Cost (convert)
A to a specific type. An exception will be thrown
(type) Object Cast if the type of A is incompatible with the specified
type. In this type can be an object or any primitive
data type.
24
repeat a group of statements until the certain specified condition(s) are met. You may find more
details on statements in unit 3 of this Block.
2.6.1 Expressions
An expression is a series of variables, operators and method calls that evaluates to a single value.
Also, sometimes you can write compound expressions by combining expressions as long as the
types required by all of the operators involved in the compound expression are compatible/
correct. The Java programming language allows programmers to construct compound
expressions and statements from smaller expressions. In Java, it is allowed as long as the data
types required by one part of the expression match the data types of the other. Let us consider the
following example of a compound expression:
P = A *B / C;
In this example, the order in which the expression is evaluated is unimportant because the results
of multiplication and division are independent of order. However, it is not true for all
expressions. For example, where addition/subtraction and division/multiplication operations are
involved. You will get different results depending on the order of operation ( i.e. whether you
perform the addition or the division operation first). Such expressions are called ambiguous
expression.
For example
R= A + B / 50; //ambiguous expression
As a programmer you can specify exactly how you want an expression to be evaluated by using
balanced parentheses ‘(‘ and ‘)’.
For example, you could write:
R= (A + B)/ 50; //unambiguous and recommended way
Suppose as a programmer; you don’t explicitly indicate the order of the operations in a
compound expression to be performed. In that case, it is determined by the precedence assigned
to the operators and the operators which have higher precedence get evaluated first.
Let us consider the above example again; the division operator has higher precedence than the
addition operator. Thus, the two following statements are equivalent:
R= A + B / 50;
R= A + (B / 50);
Therefore, it is better to write compound expressions, using parentheses to specify which
operators should be evaluated first. This also will make your code easier to read and maintain.
The following table 2.14 shows Operator's precedence
Table 2.14: Operators Precedence
25
multiplicative *, /, %
Additive +, -
Shift <<, >>, >>>
Relational <, >, <=, >=, instance of
Equality = =, !=
bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
logical AND &&
logical OR ||
Conditional ?:
=, += ,-=, *= ,/=, %=, &=, ^=, |=, <<=
Assignment
>>=, >>>=
2.6.2 Statements
In a program a statement is a complete unit of execution. Statements in Java are equivalent to
sentences in natural languages. It is an executable combination of tokens ending with a
semicolon (;) mark. A token of expression can be any variable, constant, Operator or expression.
By terminating the expression with a semicolon (;), the following types of expressions can be
made into a statement:
Assignment expressions
Any use of ++ or --
Object creation expression
Method calls
Let us consider one example of expression statements:
float piValue = 3.141; //assignment statement
counter++; //increment statement
System.out.println(piValue); //method call statement
Integer integerObject = new Integer(4); //object creation statement
In addition to these kinds of expression statements, there are two other kinds of statements.
A declaration statement declares a variable such as:
int counter;
double xValue = 55.24;
A control statement regulates the flow of execution of statements based on the changes to
the state of a program.
The while loop, for loop and if statement is examples of control flow statements. In this
category of statements, you will learn Unit 3 of this Block.
26
Assignment Statement
The assignment statement assigns the values to variables. The equal (=) sign is used as the
assignment operator. The assignment statement has the following format:
Variable = constant (or) variable (or) expression;
The assignment operator has a right-hand side (RHS) and a left-hand side (LHS). The LHS must
be a variable, and the RHS may have a constant or variable or expression.
If the assignment statement has a constant on the LHS the value is assigned to the RHS variable.
If it has a variable on the RHS, the constant is assigned to the LHS variable. Suppose it has a
variable on the RHS; the value of the variable is assigned to the LHS variable. If the RHS has an
expression it is evaluated, and the result is assigned to the LHS variable. The following statement
assigns values to the variables
StudentName = “Mohit”;
AccountBalance = previousBalance;
Area = pi * radius * radius;
The first statement is to assign a string constant to the variable StudentName, the second assigns
the value of previousBalance to the variableAccountBalance, and the last statement calculates
the result by multiplying the values of pi, and radius twice and assigns it to the variable Area.
Also, while writing a program sometimes the same variable may appear on both the RHS and
LHS as follows :
count =20;
count = count + 1 ;
It is an assignment statement where the RHS is evaluated first by taking the present value of the
variable count; for example, it is 20, and it is added with the constant 1, and the result 21 is
assigned to the variable count on the LHS. Now the value of the count is 21.
Example Program:
package javaoperatorprec;
public class JavaOperatorPrec
{
public static void main(String[] args)
{
int a , b, c, d,,e;
a= 50;
b=6;
c=12;
d=15;
e = a+b/c*d-a+b/2;
System.out.println("Calue of a+b/c*d-a+b/2 is:"+e);
e = (a+b)/(c*d)-a+b/2;
System.out.println("Calue of(a+b)/(c*d)-a+b/2 is:"+e);
e = (a+b/c)*d -a+b/2;
27
System.out.println("Calue of(a+b/c)*d -a+b/2 is:"+e);
}
Output:
The following Java Program print whether the given number is odd or even. Using method
nextInt() input number is taken from the user.
28
//Program to print the odd or even numbers using objects
import java.util.Scanner;
class EvenOdd
{
int a;
public void get ( )
{
Scanner s=new Scanner (System.in);
System.out.println ("Enter any Number : ");
a=s.nextInt ( ) ;
System.out.println ("Given Number “a” is :" + a);
}
public void display ( )
{
if (a%2==0)
{
System.out.println ("Even");
}
else
{
System.out.println ("Odd");
}
}
public static void main (String[ ] args)
{
EvenOdd e=new EvenOdd();
e.get ( ) ;
e.display ( );
}
}
When you run the above java program, it will give the output as follows:
29
For a better understanding of the use of scanner class, some more examples are also given in the
next unit of this Block.
package circlearea;
import java.util.Scanner;
public class CircleArea
{
public static void main(String[] args)
{
int radius;
float area, pi;
pi= 3.14F;
Scanner s=new Scanner (System.in);
System.out.println ("Enter the Radius of Circle: ");
radius = s.nextInt ( ) ;
area = pi * radius * radius;
System.out.println ("Area of Circle:" + area);
}
}
………………………………………………………………………………………………
………………………………………………………………………………………………
………………………………………………………………………………………………
………………………………………………………………………………………………
2) Write a Java program that takes the user's name, address and mobile number as input
and displays it?
………………………………………………………………………………………………
………………………………………………………………………………………………
………………………………………………………………………………………………
……………………………………………………………………………………………….
2.8 SUMMARY
This unit has described to you the different basic data types in Java. Basic data types include four
groups Integer, Floating Point Numbers, Characters and Boolean. This unit explained Unicode's
use and different Java keywords that have special meanings for the compiler and cannot be used
as a user-defined identifier. Before using the Java variables in your program, you should declare
them and assign them value. You learnt how to declare variables and use them. You have learnt
different types of operators in Java. You have also learnt about the use of expressions and
30
statements. Expression is a series of variables, operators, and method calls that evaluates to a
single value. Statements in Java are equivalent to sentences in natural languages. A statement is a
complete unit of execution. Toward the end of this unit, you learned to use some Scanner class
methods.
31
3)
In Java, boolean data type is used to define variables for use as logical variables. A
boolean variable can have either true or false values. The boolean variable has only two
values: true or false. These two values are boolean constants.
2)
A combination of assignment operators is a combination of any arithmetic operator( +, -,* etc.)
with the assignment operator(=).
For example, if you have an integer variable a and suppose it has a value of 20, then
a *=2;
It will be similar to a = a*2;
3)
The following program show how to use & and | operators:
package javabitwiseoperators;
public class JavaBitwiseOperators
{
public static void main(String[] args)
{
int A, B, C,D,E;
A =16;
B=4;
C= A&B;
D = A|B;
E = A&D;
System.out.println("Value of A&B is:"+ C);
System.out.println("Value of A|B is:"+ D);
System.out.println("Value of A&D is:"+E);
}
}
32
Output:
2)
Java Program
package useofscanner;
import java.util.Scanner;
public class UseofScanner
{
public static void main(String[] args)
{
String Name,Address;
long Mobile_No;
Scanner s=new Scanner (System.in);
System.out.println ("Enter the Name: ");
Name= s.nextLine ( ) ;
System.out.println ("Enter the Address: ");
Address = s.nextLine ( ) ;
System.out.println ("Enter the Mobile Number: ");
Mobile_No = s.nextLong ( ) ;
33
System.out.println ("The Name is:" + Name +'\n' + "The Address is:"+ Address +'\n'+ "Mobile
Number:"+Mobile_No);
}
}
Output:
34