Programming in Java
Sachin Malhotra, Chairperson,
PGDM-IT, IMS Ghaziabad
Saurabh Chaudhary, Dean,
Academics, IMS Ghaziabad
Chapter 3
Java Programming Constructs
Objective
• Understand how Variables are used in Java
• Understand the basic Data types
• Learn Expressions and Conditional Statements
• Understand all the available operation in Java
• Understand the basic of Conversion and Casting
• Understand Loops and Branching statements
Variables
• A symbolic name
• Used to store value which can change
during execution of the program.
• int noOfWatts = 100; // variable declaration
• Declaration involves specifying the
– type (Data Type),
– name (Identifier) and
– value (Literal) according to the type of the
variable.
Primitive Data Types
• byte
• short
• int
• long
• float
• double
• boolean
• char
Identifiers
• Identifiers are names assigned to
variables, constants, methods, classes,
packages and interfaces.
• No limit has been specified for the length
of a variable name.
Rules for Naming
• The first character of an identifier must be
a letter, an underscore (_), or a dollar sign
($).
• Use letter, underscore, dollar sign, or digit
for subsequent characters. Note that white
spaces are not allowed within identifiers.
• Identifiers are case-sensitive. This means
that Total_Price and total_price are
different identifiers.
• Do not use Java’s reserved Keywords.
Valid and invalid identifiers
• Legal Identifiers
– MyClass
– $amount
– _totalPay
– total_Commission
Illegal Identifiers
– My Class
– 23amount
– -totalpay
– total@commission
Naming Conventions
• Class or Interface identifiers begin with a capital letter.
First alphabet of every internal word is capitalized. All
other letters are in lowercase.
• Variable or Method identifiers start with a lowercase
letter. First alphabet of every Internal word is capitalized.
All other letters are in lowercase.
• Constant identifiers All letters are specified in Upper
case. Underscore is used to separate internal words (_).
• Package identifiers consist of all lowercase letters.
Literals
• A value that can be passed to a variable
• Integer literals can be decimal, octal, or
hexadecimal.
– for octal literals, the value must be prefixed with zero
and only digits 0 through 7 are allowed.
– int x = 011; //value in x is 9
– Hexadecimal literals are prefixed with 0x or oX; digits
0 through 9 and a through f (or A through F) are only
allowed.
– int y = 0x0001; //value in y is 1
• All integer literals are of type int, by default.
• To define them as long, we can place a suffix of
L or l after the number for instance:
– long l = 2345678998L;
.
Literals
• String literals consists of zero or more characters within
double quotes.
– String s = “This is a String Literal”;
• Null literal is assigned to object reference variables.
– s =null;
• All floating literals are of type double, by default.
• For float literals, suffix F or f.
• for double literals, D or d are suffixed to the end (optional)
– float f = 23.6F;
– double d = 23.6;
• For char literals, a single character is enclosed in single
quotes.
– char sample = ‘A’
– the prefix \u followed by four hexadecimal digits represents 16-
bit Unicode character:
– char c = ‘\u004E’
Escape Sequence
Keywords
Operators
• Assignment Operators (=)
• Arithmetic Operator (+, -, *, /, %)
• Relational Operators (==, <,>,<=,>=, !=)
• Boolean Logical Operators
– Can be applied to Boolean operands (or
expressions) and return a boolean value.
– conditional OR (||) and conditional AND (&&)
– logical OR (|),
– logical AND (&),
– logical XOR (^)
– unary logical NOT (!)
Boolean logical Operators
boolean a=true,b=false;
System.out.println(“Logical OR: “+ a +” | “+b+”: “+(a|b));
System.out.println(“Logical XOR: “+ a +” ^ “+b+”:
“+(a^b));
System.out.println(“Logical AND: “+ a +” & “+b+”:
“+(a&b));
System.out.println(“Logical NOT: !a : “+(!a));
System.out.println(“Conditional OR: “+ a +” || “+b+”:
“+(a||b));
Syste m.out.println(“Conditional AND: “+ a +” && “+b+”:
“+(a&&b));
// shortcut operator
a |= b;
System.out.println(“shortcut OR: “+ a +” | “+b+” = “+(a));
The Output
Logical OR: true | false: true
Logical XOR: true ^ false: true
Logical AND: true & false: false
Logical NOT: !a : false
Conditional OR: true || false: true
Conditional AND: true && false: false
Bitwise operators
• include and, or, xor, not, right shift, left
shift and unsigned right shift.
• Operate on int and long values. If any of
the operand is shorter than an int, it is
automatically promoted to int before the
operations are performed
Bitwise operators
Bitwise Operators
class BitwiseOperatorDemo {
public static void main(String args[]) {
int x=2,y=3;
System.out.println(“Bitwise AND:
“+x+”&”+y+”=”+(x&y));
System.out.println(“Bitwise OR :
“+x+”|”+y+”=”+(x|y));
System.out.println(“Bitwise XOR:
“+x+”^”+y+”=”+(x^y));
System.out.println(“Bitwise NOT: ~”+x+”=”+(~x));
}}
The Output
• Bitwise AND: 2&3=2
• Bitwise OR : 2|3=3
• Bitwise XOR: 2^3=1
• Bitwise NOT: ~2=-3
Compound Assignment Operators
• +=
• -=
• *=
• /=
• %=
• &=
• |=
• ^=
• <<=
• >>=
• >>>=
• Note: The compound Assignment Operator includes an
implicit cast
Shift Operator
• Left shift
– operator shift the numbers of bits specified, towards left.
– Bits are discarded from the left and added form the right with the
value of bits being zero.
• Right shift
– operator shift the numbers of bits specified, towards right.
– Bits are discarded from the right and added form the left side
with the value of bits being that of the sign bit.
• Unsigned right shift,
– shifts the numbers of bits specified, towards right.
– Bits are discarded from the right and added form the left side
with the value of bits being zero.
Shift Operators
• Assume x=4 and this x is to be shifted by the
shift distance of 1.
• int y = x>>1;
– y has the value 2, value is halved in each successive
right shift
– 00000000 00000000 00000000 00000100>>1
– 00000000 00000000 00000000 00000010 (which is
2).
int y = x<<1;
– y has the value 8, value is doubled in each
successive left shift
• int y = x>>>1;
– same as right shift for +ive numbers.
Increment and Decrement
• Increment and Decrement Operators
– can be applied to all integers and floating-point types.
– can be either in prefix (--x, ++x) or postfix (x--, x++)
mode.
• Prefix Increment/Decrement Operation
– int x = 2;
– int y = ++x; // x = 3, y = 3
– int z= --x; // x = 1, z = 1
• Postfix Increment/Decrement Operation
– int x = 2;
– int y = x++; // x == 3, y == 2
– int z = x--; // x = 1, z = 2
Precedence and Associativity
Your Turn
• What is the role of precedence and
associativity?
• How are hexadecimal integers literals
defined in java?
• What are shift operators?
Conversion and Casting
• Conversions are performed automatically
– For e.g. a smaller box can be placed in a bigger box
and so on.
• Casting also known as narrowing conversion
(reverse of widening conversion).
– A bigger box has to be placed in a small box.
– Casting is not implicit in nature.
– Use casting operator i.e. ()
– int i = (int)(8.0/3.0);
Conversion and Casting
class CastingAndConversionExample
{ public static void main(String args[])
{
int i=(int)(8.0/3.0);
int j=(int)2147483648.0f;
System.out.println(“i = “+i+” j= “+j);
byte b=(byte)257;
short s=(short)65537;
System.out.println(“b= “+b+” s= “+s);
System.out.println(“ Converting int to char “ +(char)75);
double d = i * b * s * 2.0;
System.out.println(“Conversion to double result is :
“+d);
i=b<<2;
System.out.println(“i = “+i);
}}
The output
i = 2 j= 2147483647
b= 1 s= 1
Converting int to char K
Conversion to double result is : 4.0
i=4
Flow of Control
• Conditional Statements
• Loops
• Branching statements
• Exceptions (chap 9)
Conditional Statement
if…else
The syntax of if statement is as follows:
if (x = = 0)
{// Lines of code}
else if(x = =1)
{// Lines of code}
………
else
{// Lines of code}
Switch case
switch (x) {
case 0:
// Lines of code
doSomething0();
break;
case 1:
// Lines of code
doSomething1();
break;
.
.
case n:
// Lines of code
doSomethingN();
break;
default:
doSomethingElse();
}
Switch..case
• x must be one of these: int, byte,
short, char, enum type or wrapper
class.
• Can also be an expression that
returns an int, byte, short or char.
For Loop
class ForDemo
{
public static void main(String args[])
{
for(int i=1;i<=5;i++)
System.out.println(“Square of “+i+” is “+
(i*i));
} }
The Output
The output is as follows:
Square of 1 is 1
Square of 2 is 4
Square of 3 is 9
Square of 4 is 16
Square of 5 is 25
While Loop
class WhileDemo
{
public static void main(String args[])
{
int i=1;
while(i<=5)
{
System.out.println(“Square of “+i+” is “+ (i*i));
i++;
} }
}
The Output
The output is as follows:
Square of 1 is 1
Square of 2 is 4
Square of 3 is 9
Square of 4 is 16
Square of 5 is 25
do…while loop
class DoWhileDemo
{
public static void main(String args[])
{ int i=1;
do
{
System.out.println(“Square of “+i+” is
“+ (i*i));
i++;
}while(i<=5);
}}
The Output
The output is as follows:
Square of 1 is 1
Square of 2 is 4
Square of 3 is 9
Square of 4 is 16
Square of 5 is 25
For..each
for (type var : arr) {
// Statements to repeat
}
• to access each value successively in a collection
of values (like array).
• Like for loops, these loops perform a fixed
number of iterations.
• But Unlike them, for- each loop determine its
number of steps from the size of the collection.
break
class PrimeDemo{
public static void main(String[] args){
int j,k;
System.out.print(“Prime numbers between 1 to 30 : “);
for (j = 1; j < 30; j++ ){
for (k = 2; k < j; k++ ){
if(j % k == 0) break;
}
if(j == k)
{
System.out.print(j+” “);
}
}}}
The Output
Prime numbers between 1 to 30 : 2 3
5 7 11 13 17 19 23 29
Labeled break
class LabeledBreakDemo{
public static void main(String args[])
{
Outer : for(int i=0; i < 4 ; i++){
for(int j = 1; j < 4; j++) {
System.out.println(“i:” + i + “ j:” + j);
if(i == 2) break Outer;
}}}}
The output
i:0 j:1
i:0 j:2
i:0 j:3
i:1 j:1
i:1 j:2
i:1 j:3
i:2 j:1
continue
while ( i < 5){
//doSomething1;
if(i<4) continue;
//doSomething2;
}
Labeled continue
jmp0: while (i < 5){
for (int i=0; i<4; i++){
if( i==2) continue jmp0;
//dosomething;
}
}
Summary
• Variables holds data at memory locations allocated to them.
• There are eight basic data types in java, namely, byte, short, int,
long, float, double, boolean and char.
• Java does not leave the size of data types to the machine and the
compiler.
• All integer (byte, short, int, long) and floating-point types (float,
double) are signed in java.
• operators can be classified as arithmetic, relational, logical,
assignment, increment and decrement, conditional, bit-wise, and
shift operator.
• Expressions are formed with variables and operators.
• Operators in java have certain precedence and associativity rules
that are followed while evaluating expressions.
• Automatic type conversion takes place according to set rules in
expressions with mixed types.
• Explicit type conversion (a.k.a Casting) is also possible in java.