0% found this document useful (0 votes)
32 views

2-Data Types (E-Next - In)

The document discusses Java naming conventions and data types. 1. Java has specific naming conventions for packages, classes, methods, variables, and constants. Packages and variables are written in lowercase, classes and methods start with uppercase letters, and constants are written in all uppercase. 2. The document describes Java's primary data types - integer, floating point, character, and boolean. Integer types include byte, short, int, and long. Floating point types are float and double. Character type represents a single character. 3. Examples are given to illustrate declaring variables of different data types and assigning values to them. Literals specify the type of data assigned like L for long or F for float.

Uploaded by

Umar Khan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views

2-Data Types (E-Next - In)

The document discusses Java naming conventions and data types. 1. Java has specific naming conventions for packages, classes, methods, variables, and constants. Packages and variables are written in lowercase, classes and methods start with uppercase letters, and constants are written in all uppercase. 2. The document describes Java's primary data types - integer, floating point, character, and boolean. Integer types include byte, short, int, and long. Floating point types are float and double. Character type represents a single character. 3. Examples are given to illustrate declaring variables of different data types and assigning values to them. Literals specify the type of data assigned like L for long or F for float.

Uploaded by

Umar Khan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

AMING CHAPTER

ONVENTIONS
NO DATA
I PES

n the previous chapter, we understood Java by writing a couple of programs. In those programs,
you might have observed that sometimes we have used small letters and sometimes capital
letters. For example, we have written the class System starting with a capital letter. You cannot
·te this class name as system or SYSTEM. Since Java is a case sensitive programmingJanguage, it
=gnizes capital and small letters as different. So the programmer should take care of upper and
er case whilt;. writing a program in Java. But how to know where to use which case-upper or
er? For this purpose, certain conventions (rules) are followed by JavaSoft people while naming
e variables, classes, methods, etc. These naming conventions should be followed by every
;rrograrrimer in his programs for maintaining uniformity and also for clarity of distinction betWeen
.. erent elements of a program. These rules also reduce the possibility of any spelling mistakes
~e writing the nanies of variables, classes, etc. in the programs. For example, a Java program will
::ot compile, if main () method is written as:

e problem in the preceding statement is using capital P for public and capital Mfor main (). Such
=:mrs can be eliminated if we follow the naming conventions.

I ing Conventions in Java


_mning conventions specify the rules'to be followed by a Java programmer while writing the names
packages, classes, methods, etc. Now, let us see some of the major naming conventions to be
- owed in Java.
A package represents a sub directory that contains a group of classes and interfaces. Names of
packages in Java are written in small letters as:

.e
h

A class is a model for creating objects. A class specifies the properties and actions of objects. An
interface is also similar to a class. Each word of class names and interface names start with a
capital letter as:

https://E-next.in
~ChaPter4

o A class and an interface contain methods and variables. The first word of a method name is in
small letters; then from second word onwards, each new word starts with a capital letter as
shown here:

o The naming convention for variables names is same as that for methods as given here:

1!",,---,,-'II'o;_. _
Now, the question that is commonly asked is that if same rule is applied for both variables and
methods, how can we distinguish between them? The answer is that since a method's name ends with·
a pair of simple braces 0, it can be distingUished easily from a variable whose name will not have any
braces.

o Constants represent fixed values that cannot be altered. For example, PI is a constant whose
value is 22/7 or 3 . 14159, which is fixed. Such constants should be written by using all capital
letters as shown here:

Here, BOLD is a constant in Font class. This is the way most of the inbuilt constants in Java are
referenced. <.

o All keywords should be written by using all small letters as follows:.

Data Types in Java


We know we need variables to store the data. Internally, a vanable represents a memory locatiOl
which holds data. When we want to use a variable-in a program, we should first declare it as:

Here, we are declaring that x is a variable, which can store int (integer) type data. This means in
is representing the nature of data to be stored into x. int is also called a data type. For exampl(
x can store an integer number like 125 as:

https://E-next.in
Naming Conventions and Data Types I 2

, x is a variable and = represents that the value 125 is stored into x. This value 125 stored into
also called literal. There are various data types and literals defined in Java, which we will be

I ssing in this chapter.

er Data Types
lin
as data types represent integer numbers, Le. numbers without any fractional parts or decimal
IS. For example, 125, -225678, 0, 1022, etc. come under this category. Integer data types are
sub divided into byte, short, int, and long types. Table 4.1 lists the data types.

I 4.1
type
,
Memory size
. 1 by.t.e
Minimum and Maximum values
:>t.
:!-::e
'" -128 to +127 ><ll m

-- yt 2 bytes -32768 to +32767

-- --
'.
'iii
'R...• 01' 4 byte~ if. ~i;jls .. ."l:. ,~ @ii ':';
-2'14748364~ tq;.Ji~14~48;3M7",~ ".I!ilo'!'
:.::, 9 8 bytes -9223372036854775808 to
+9223372036854775807
us try to understand this through an example given here:

teo~

ose ~ preceding statement, we are declaring byte data type for the variable rno and the value 10,
ital is stored into rno. byte represents any value between -128 to +127.
_:-; x=150L;
-~, _50 is stored into x, which is declared as long type. Notice the L at the end of the statement.
," L is not there, then JVM allots only 2 bytes of memory to x as against the usual 8 bytes
ory that should be allotted to a long type. The reason for this is that 2 bytes are sufficient to
the value 150. But if we attach I or L at the end of the value as shown in the preceding
are Ie, then JVM will consider it as a long value and will allot-8 bytes to it.

Data Types
data types are useful to represent numbers with decimal point. For example, 3.14, 0.0012,
-_::L 11, etc. are called floating point numbers. These are again classified as fl.oat (single
. 'on floating point number) and double (double precision floating point number). The
nce exists essentially in the number of digits, they can represent accurately after the decimal
~ This accuracy is also called precision. Table 4.2 depicts the size of' float and double.

ion

int =:mble 8 bytes -1.8e308 to -4.ge-324 for negative values


:lIe, and 4.ge-324 to 1.8e308 for positive
values

https://E-next.in
. 22.J Chapter 4

What is the difference between float and double?


F loa t can represent up to 7 digits accurately after decimal point, whereas daubl e can represent up
to 15 digits accurately after decimal point.

Let us now look at an example given here:

float i 3.'D12}i';

Here, the variable pi is containing the value 3 .142. I~ F is not written at the end, then JVM ~ould
have allotted 8 bytes assuming the value to be double. The reason for this is that in float and
double data types, the default is taken as double. By attaching F or f, we can ask the JVM to
consider it as a float value and allot only 4 bytes.
double distance=1.98e8;
Here,e or E represents X 10 to the power. Hence, 1. 98e8 means 1. 98X108. This is also called
scientific notation of re~resenting numbers.

Character Data Type


This data type represents a single character like a, P, &, *, etc. Table 4.3 shows char data type
details.
Table 4.3

Data type Memory size Minimum and Maximum values

Char 'II . " 2 bytes ;i't o to 65535 ."F ~ .,"1


Here is an example of character data type:

cfla:f en ~X"

Here, we are storing the single character 'x' into the variable ch. Here, 'X' is also called characte7
literal. WHenever character literals are written, they should be enclosed inside the single quotes.
By observing the minimum and maximum values in the table earlier, we shall get a doubt regarding
why the range is expressed in integer numbers (0 to 65535). We know that all the characters on the
keyboard are translated into integer values called ASCII (American Standard Code for Information
Interchange), which is a standard maintained by every keyboard manufacturer. The processOI
recognizes the character uniquely from its ASCII value. Hence, let us understand the' range
mentioned in the table is nothing but the ASCII value range only.
The ASCII value range, from 0 to 65535, given in the table can uniquely represent a total of 6553E
characters. This means a total of 65536 distinct characters can be recognized by Java. But we nevel
use these many characters since our keyboard contains English alphabets and some othe]
characters whose total does not exceed 256. This means 1 byte is s'Ufficient to represent all th<
available characters of the keyboard. Then why 2" bytes are used to represent the char data type ir
Java?
JavaSoft people wanted to provide a facility to include characters not only from English but alS(
from all other human languages to be used in Java programs. This will enable the programmers t(
write and execute a Java program in any language, which becomes an advantage on Internet. Thi1
system is also called Unicode system. Unicode uses 2 bytes so that any character from any languagl
can be encoded successfully.

https://E-next.in
Naming Conventions and Data Types l1!..
What is a Unicode system?
Unicode system is an encoding standard that provides a unique number for every character, no matter
what the platform, program, or language is. Unicode uses 2 bytes to represent a single character.

llid String Data Types


nd A String represents a group of characters, like New Delhi, AP123, etc. The simplest way to create a
to String is by storing a group of characters into a String type variable as:

ri tr
led
Now, the String type variable str contains "New Delhi". Note that any string written directly in a
program should be enclosed by using double quotes.
There is a class with the name String in Java, where several methods are provided to perform
different operations on strings. Any string is considered as an object of String class. But in
pe CjC++, a string is considered as a character array containing some characters where the last
character would be \0. This is not valid in Java, since in Java, we got strings and character arrays
both separately. .
Now the question arises that if String is a cla~s, why are we taking it as a data type? The answer
is that every class is a data type and is also called user-defined data type.

Boolean Data Types


Boolean data types represent any of the two values-true or false. JVM uses I bit to represent a
boolean value internally, for example:

00 ean\ S onse r
er "
As shown earlier, we should not enclose the boolean value true (or false) in any quotation mal'ks."
in CjC++, 0 represents false and any other number represents true. This is not valid in Java.

"terals
~e
A literal represents a value that is stored into a variable directly in the program. See the following
examples:
6
~r

~r

:e
n
In the preceding statements, the right hand side values are called literals because these values are
being stored into the variables shown at the left hand side. As the data type of the variable changes,
o
the type of the literal also changes. So we have different types of literals. These are as follows:
o
s o Integer literals
e o Float literals
o Character literals
o String literals
o Boolean literals
Read on to get familiar with them.

https://E-next.in
~ Chapter 4

Integer Literals
Integer literaIs represent the fIxed integer values like 100, -55, 123450, etc. All these numbers
belong to decimal system, which uses 10 digits (from 0 to 9) to represent any number. Suppose, we
want to write an integer in octal number system (octal number system uses 8 digits, from 0 to 7),
then· we should prefIx 0 before the number.· To represent hexadecimal number (hexadecimal
number system uses 16 digits from 0 to 9 and from A to F), we should prefIx Ox before the value.

Float Literals
Float literals represent fractional numbers. These are the numbers with decimal points like 2.0, -
0.005, 3.14, 6.1e-22, etc. which should be used with float or double type variables. While
writing these literals, we can use E or e for scientifIc notation, F or f for float literal, and D or d for
double literal (this is the default and generally omitted).

If. same value as dl, but in scientific notation


-~

Character Literals
Character literals indicate the following:
. 0 General characters, like A, b, 9, etc.
o Special characters, like ?, @, etc.
o Unicode characters, like \u0042 (this represents a in ISO Latin 1 character set).
o Escape sequence (backslash codes) like \n, \b, etc.
Character literals should be enclosed in single quotation marks. The preceding unicode characten
and escape sequence can also be represented as strings.

String Literals
String literals repres'ent objects of String class. For example, Hello, Anil Kumar, AP1201, etc. wil
come under string literals, which can be directly stored into a String object.

Boolean Literals
Boolean literals represent only two values-true and false, It means we can store either true or falSI
into a boolean type vanable.

Conclusion
By following naming conventions, a programmer can avoid a lot of mistakes in writing the names 0
packages, classes, methods, variables, etc. This will improve readability as well as understandabili~
of a program. So maintaining naming conventions is a good programming habit.
A program generally acts on data, processes it, and provides the results. So data is very importaI1
element of a program. In this chapter, we also discussed different data types, in terms of type (
data received, stored, or used in a program.

https://E-next.in
~rs

Ne
7), CHAPTER
lal

OPERATORS IN.
JAVA
ile
or

programmer generally wants to do some operations in a program. For example, in a program,

A you want to perform addition of two numbers. How can you do it? Just by using + symbol, we
can add the numbers. This means + is a symbol that performs an operation, i.e. addition.
Such symbols are called operators and programming becomes easy because of them. Let us discuss
about operators in this chapter and how to use them with examples.

Operators
An operator is a symbol that performs an operation. An operator acts on some variables, caped

rs
r
operands toget the desired result, as shown in Figure 5.1.
Operator

a + b
ill

I
Operand
\Operand
;e Figure 5.' Operator and operands
If an operator acts on a single variable, it is called unary operator; if it acts on two variables, it is
called binary operator; and if it acts on three variables, then it is called ternary operator. This is one
)f type of classification. ·Let us now examine various types of operators in detail.
y
Arithmetic Operators
It These operators are used to perform fundamental arithmetic operations like addition, subtraction,
)f etc. There are 5 arithmetic operators in Java. Since these operators act on two operands at a time,
these are called binary operators. Table 5.1 displays the functioning of these operators. Here, we are
assuming the value of a as 13 and b as 5.

https://E-next.in
2!..J Chapter 5
Table 5.1

Operator Meaning Example Result

+ .addition, operator a +h 18
Subtraction a-b 8
operator

Addition operator (+) is also 1,lsed to join two strings, as shown in the following code snippet:
o String 51= "wel";
o String 52= "come";
o String 53= 51+52; Ilhere, '+' ~5 joining 51 and 52.
Now, we get welcome in s3. In this case, + is called String concatenation operator.

Unary Operators
As the name indicates, unary operators act on only one operand. There are 3 kinds of unary
operators:
o - Unary minus operator ( - )
o Increment operator ( ++ )
o Decrement operator ( -- )

Unary Minus Operator (-)


This operator is used to negate a given value. Negation means converting a negative value into
positive and vice versa, for example:

In this code snippet, the unary minus (-) operator is used on variable x to negate its value. The
value of x is 5 in the beginning. It became -5 when unary minus is applied on it.

Increment Operator (+ +)
This operator increases the value of a variable by 1, for example:

https://E-next.in
Operators in Java ~

Here, the value of the variable x is incremented by 1 when ++ operator is used before or after it..
Both are valid expressions in Java. Let us take an dmmple to understand it better:

x= :i{+ •

In this statement, if x is 3, then x+l value will be 4. This value is stored again in the left hand side
variable x. So, the value of x now becomes 4. The same thing is done by ++ operator also.
Writing ++ before a variable is called pre incrementation and writing ++ after a variable is called post
incrementation. In p~e incrementation; incrementation" is done first and any other operation is done
next. In post incrementation, all the other operations are done first and incrementation is done only
at the end. To understand the difference between pre and post incremenations, let us take a couple
of examples.
Example 1: Finding the difference between pre- and post- increment ofx

Output:

Output:

In this example, see the left-hand side and right-hand side statements. The second statement on
the left uses pre-incrementation, while the second statement on the right uses post-incrementai:ion.
At the left hand side:
o System. out. println (x); I I displays the value of x as 1
o System. out .println (++x); I I first increments the value of x and then displays it as 2
o System.out.println (x); I I displays the value of x, which is already incremented, Le. 2
At the right hand side:
o System.out.println(x); II displays the value of x, i.e. 1
o Sys"tem. out. println (x++) ; / / first displays the value of x as 1 and then increments it.
o System. out.println (x); I I displays the incremented value of x, i. e. 2
Example 2: Finding the difference between pre- and post- increment of a and b

https://E-next.in
~ ChapterS

Result:

Result:

At the left hand side, a=++b;


This is called pre-incrementation. So increment the value of b first (it becomes 3) and then store it
into a. Now, the value of a also becomes 3.
At the right hand side, a=b++;
This is called post-incrementation. So incrementation of b will not be done first. Without
incrementing, the value Of b'. i.e. 2 is stored into a (so the value of a becomes 2) and then
incrementation ofb is done (so the value ofb becomes 3).
Example 3: Finding the value of the following expression, given that the value of a is 7
++a*a++;
Here, the value of a is given as 7. So ++a makes the value of a as 8. Then a++ is there. Since, this is
post-incrementation, the value of a will not be incremented in the same statement and hence -the
value of a, i.e. 8 will stay like that only. As a result, we get 8*8= 64.

Decrement Operator (--)


This operator is used to decrement the value of a varIable by 1.

This means, the value of x is decremented every time we use operator on it. This is same as
writing x= x-l.
Writing -- before a variable is called pre-decrementation and writing -- after a variable is called
post-decrementation. Like the incrementation operator, here also the same rules apply. Pre-
decrementation is done immediately then and there itself and
Post-decrementation is done after all the other operations are carried out.

Assignment Operator (-)


This operator is used to store some value into a variable. It is used in 3 ways:
o It is used to store a value into a variable, for example int x = 5;
o It is used to store the value of a variable into another variable, for example:

In't: X ffefe e viflue -0 1S sto e ~n 0 X·

https://E-next.in
Operators in Java l.1z.-.
o It is used to store the value of an expression into a variable, for example:

We cannot use more than one variable at the left hand side of the =operator. For example:

We cannot use a literal or constant value at the left side of the = operator. For example:

Compact Notation
While using assignment operator (=), sometimes we may have to use saine variable at both the
sides of the operator. In such cases, we can eliminate repetition of the variable and use compact
notation or short cut notation, as shown in Table 5.2.
Table 5.2

Experienced programmers use compact notations. However, both the exp~ded and compact
notations are valid in Java.

Relational Cperator
These operators are used for the purpose of comparing. For example, to know which one is bigger or
whether two quantities are equal or not. Relational operators are of 6 types:
o > greater than operator
o >= greater than or equal to
o < less than operator
o <= less than or equal to
o equal to operator
o .! = not equal to operator

https://E-next.in
~ ChapterS

The main use of relational operators is in the construction of conditions in statements, like this:

This statement could be applied in a program as follows:

Observe, that in this example the two statements, a>b and a==lOO, are conditions. If they are true,
then the corresponding statements will be executed. Note that = (assignment operator) is for storing
the value into a variable and == (equal to operator) is for comparing the two quantities. Both are
quite different.

Logical Operators
Logical operators are used to construct compound conditions. A compound condition is a
combination of several simple conditions. Logical operators are of three types:
o && and operator
o I I or operator
o not operator

iT == • J:) == .." C ==; Sl£ste o:t "Yes' .

Here, there are 3 conditions: a==l, b==l,and c==l, which are combined by I I (or operator). In this
case, if either of the aor b or c value becomes equal to 1, Yes will be displayed.

s stem.o\!1;.,J;lrintr" elTOn .
In the preceding statement, there are 2 conditions: x>y and y<z. Since they are combined by using
&& (and operator); if both the conditions are true, then only Hello is displayed. ....

We are assuming that strl and str2 are two string objects, which are being compared. See the
(not operator) and the equals () methods in the earlier condition telling that if strl is not equal to
str2, then only Not equal will be displayed. .

Boolean Operators
These operators act on boolean variables and produce boolean type result. The following 3 arF.
boolean operators:
o & boolean and operator
o I boolean or operator
o ! boolean not operator
Boolean & operator returns true if both the variables are true. Boolean I operator returns true if any
one of the variables is true. Boolean ! operator converts true to false and vice versa.
boolean' a, b; / /declare two boolean type variables
o a= true; / /store boolean value true into a
o b= false; / /store boolean value false into b

https://E-next.in
~ ChapterS
Decimal 10 0000 1 0 1 0

1's complement 11 1 1 0101


(change 0 as 1 and
vice versa)
+1
2'5 complement
(add 1 to 1's 11 1 1 0110 = Decimal -10
complement)
Figure 5.4 Representation of negative numbers

How are positive and negative numbers represented internally;?


Positive numbers are represented in binary·using 1's complement notation and negative numbers are
represented by using 2's complement notation.

There are 7 types of bitwise operators. Read on to understand them. Let us now discuss them one
by one.

Bitwise Complement Operator ( tv )

This operator gives the complement form of a given number. This operator syrpbol is ~, which is
pronounced as tilde. Complement form of a positive number can be obtained by changing O's as 1's
and vice versa.

By changing O's as l's and vice versa, we get 1111 0101. This is nothing but -ll(in decimal). SO,-x
= -11.

Bitwise and Operator ( & )


This operator performs and operation on the individual bits of the numbers. The symbol for this
operator is &, which is called ampersand. To understand the and operation, see the truth table
given in Figure 5.5:

x Y x&y
x = 10 = 0000 1010
= =
Y 11 0000 1011 0 0
1
0
0 0
x&y = 0000 1010. 1 0 0
1 1 1

Truth table

AND gate
Figure 5.5 AND operation
Truth table is a table that gives relationship between the inputs and the output. From the table, we
can conclude that by multiplying the input bits, we can get the output bit. The AND gate circuit
present in the computer chip will perform the and operation.

https://E-next.in
Operators in Java l.!.!...
From the truth table, by multiplying the bits, we can get X&y 0000 1010. This is nothing but 10
(in decimal).

itwise or Operator ( I )
This operator performs or operation on the bits of the numbers. The symbol is I, which is called
pipe symbol. To understand this operation, see the truth table given in Figure 5.6. From the table,
we can conclude that by adding the input bits, we can get the output bit. The OR gate circuit, which
is present in the computer chip will perform the or operation:

x Y xlY
x= 10 = 0000 1010
y= 11 =0000 1011 0 0 0
a 1 1
xlY = 0000 1011 1 a 1
1 1 1

Truth table

.OR gate
Figure 5.6 OR operation

x ="10, Y ~ 11. Of xly." ~


0000 1010.
OPOQ 1011.
From the truth table, by adding the bits, we can get x Iy = 0000 1011. This is nothing but 11 (in
decimal).

Bitwise xor Operator ( A )

This" operator performs exclusive or (xor) operation on the bits of the numbers. The symbol is A,
which is called cap, carat, or circumflex symbol. To understand the xor operation, see the truth table
given in Figure 5.7. From the table, we can conclude that when we have odd number of l's i~the
input bits, we can get the output bit as 1. The XOR gate circuit of the computer chip will perform
this operation.
x y. x'y
x = 10 = 0000 1010
y=11=0000 1011 0 a 0
0 1 1
x'y = 0000 0001 1 0 1
1 1 .0

Truth table

XOR gate
Figure 5.7 XOR operation

If lnt x = 10, y = 11. Find tnevalue of xAy .


. x . 10 0000 1010.
y ~ 11 0000 1011.

https://E-next.in
j
~ ChapterS

From the truth table, when odd number of 1's are there, we can get a 1 in the output. Thus, xl\y =
00000001 is nothing but 1 (in decimal).

Bitwise Left Shift Operator «<)


This operator shifts the bits of the number towards left a specified number of positions. The symbol
for this operator is «, read as double less than. If we write x«n, the meaning is to shift the bits of
x towards left n positions.

o a 1 v ue i we wrl e « .

Shifting the value of x towards left 2 positions will make the leftmost 2 bits to be lost. The value of x
is 10 = 0000 10lD. Now x«2 will be 0010 1000 = 40 (in decimal). The procedure to do this is
explained in Figure 5.8.

x = 10

x «2 =

--- fill O's


Figure 5.8 Shifting bits towards left 2 times

Bitwise Right Shift Operator (»)


This operator shifts the bits of the number towards right a specified number of positions. The
symbol for this operator is », read as double greater than. If we write x»n, the meaning is to shift
the bits ofx towards right n positions.
» shifts the bits towards right and also preserves the sign bit, which is the leftmost bit. Sign bit
represents the sign of the number. Sign bit 0 represents a positive number and 1 represents a
negative number. So, after performing » operation on a positive number, we get a positive value in
the result also. Ifright shifting is done on a negative number, again we get a negative value only.

I 10 t en ca cu ate x»2 va ue.

Shifting the value of x towards right 2 positions will make the rightmost 2 bits to be lost. x value is
10 ~ 0000 1010. Now x»2 will be: 0000 0010 = 2 (in decimal) (Figure 5.9).

x = 10

x »2 =
.........-
fill D's
Figure 5.9 Shifting bits towards right 2 times

Bitwise Zero Fill Right Shift Operator (»»


This operator also shifts the bits of the number towards right a specified number of positions. But,
it stores 0 in the sign bit. The symbol for this operator is »>, read as triple greater than. Since, it
always fills 0 in the sign bit, it is called zero fill right shift operator. If we apply>>> on a positive
number; it gives same output as that of ». But in case of negative numbers, the output will be
positive, since the sign bit is replaced by a O.

https://E-next.in
Operators in Java ~

What is the difference between »and >>> ?


Both bitwise right shift operator (») and bitwise zero fill right shift operator (> > » ar~ used to shift the
bits towards right. The difference is that >> will pmtect the sign bit whereas the >>> opera(or will not
protect the sign bit. It always fills 0 in the sign bit.

Program 1: Let us now write a program to observe the effects of various bitwise 0I?erators.

Ternary Ope~ator or Conditional Operator (1 : )


This operator is called ternary because it acts on 3 variables. The other name for this operator is
conditional operator, since it represents a conditional statement. Two symbols are used for this
operator? and:
Its syntax is variable = expressionl? expression2 expression3;
This means that fIrst of all, expressionl is evaluated. If it is true, then expression2 value is stored
into the variable. If expressionl is false, then expression3 value is stored into the variable. It means:

Now, let us put the following condition

Here, (a>b) is evaluated fIrst. If ij: is true; then the value of a is stored into the variable max, else the
value of b is stored into max. This means:

https://E-next.in
44 IChapter 5

Here, we are using 3 variables:_ a, b,- and max-thus, the name ternary. The preceding statement,
which is called conditional statement, is also represented by this operator. So it is also called
conditional operator. Remember conditional operator is a compact form of conditional statement.
Member Operator ( . )
Member operator is also called dot operator since its s~bol is a. (dot or period). This operator tells
about member of a package or a class. It is used in three ways:
o We know a package contains classes. We can use. operator to refer-to the class of a package.
Syntax:

This could be written as follows:

o We know that each class contains variables or methods. To refer to the variables of a class, we
can use this operator.
Syntax:

, Or

o ectname.varia51ename·

This could be written as:

1S

o We know that a class also contains methods. Using dot operator, we can refer to the methods
of a class.
Syntax:

Or

Let us try to understand this with the help of an example.

https://E-next.in
Operators in Java ~

mstanceof Operator
I This operator is used to test if an object belongs to a class or not. Note that the word instance
means object. This operator can also be used to check if a.11 object belongs to an interface or not.
Syntax:

This could be written as:

Here, we are testing if emp is an object of Employee class or not. If emp is an object of Employee
class, then true will be returned into x, otherwise x will contain false.

ewOperator
new operator is often used to create objects to classes. We know that objects are created on heap
memory by JVM, dynamically (at runtime).
Syntax:

An example of this is as follows:

cast Operator
Cast operator is used to convert one datatype into another datatype. This operator can be used by
writing datatype inside simple braces.

To store x value into y, we have to first convert the datatype of x into the datatype of y. It means
double datatype should be converted into int type by writing int inside the simple braces as: (int).
This is called cast operator.

In the preceding statement, (int) is called the cast operator. Cast operator is generally used before a
variable or before a method.

riority of Operators
When several operators are used in a statement, it is important to know which Qperator will execute
first and which will come next. To determine that, certain rules of operator precedence are followed:
o First, the contents inside the braces: () and [] will be executed.

https://E-next.in
~ ChapterS

D Next, ++ and --.


D Next, *, ;, and % will execute.
D + and - will come next.
D Relational operators are executed next.
D Boolean and bitwise operators
D LogiCal operators will come afterwards.
D Then ternary operator.
D Assignment operators are executed at the last.

Conclusion
In this chapter, you learnt that operators make programming easy by assisting the programmer to
perform any operation by just mentioning a symbol. Just imagine a situation, where we have to add
two numbers without any arithmetic or unary operators available to us. In such a case, a mere
addition will become a very tedius job. Such programming difficulties can be escaped.by_using these
operators.

https://E-next.in ---.- ~ - --- - ---


,

You might also like