You are on page 1of 67

The Nuts and Bolts of Java

Data types and simple operators

1
Java
Contents

1 Primitive data types and their range


2 Ranges of Primitive Numbers
3 Unicode Character
4 Variables
5 Keywords/ Reserved words
6 Key Points
7 Constants
8 Literals
9 Integer Literals
10 Decimal literal

2
Java
Contents

11 Octal literal
12 Hexadecimal literal
13 Long literal
14 Floating-Point Literals
15 Character Literals
16 Boolean literals
17 Declarations
18 Local declarations
19 Class declarations
20 Default Values

3
Java
Contents

21 Simple Operators
22 Conditional Statements
23 Loops
24 Labeled break and continue
25 Conversions
26 Automatic or implicit conversion
27 Explicit conversion or casting
28 Integer Bitwise Operators

4
Java
Contents

31 Logical Operators
32 Comparing conditional and logical operators
33 Compound Operators
34 Precedence
35 Extra spaces in the source code
36 Learning resources

5
Java
Know
• Primitive data types and their range
• What unicode characters are
• What variables, constants and literals are
• How to declare variables and classes
• Simple Operators in Java
• Conditional Statements and Loops
• Conversions
• Compound and Bitwise Operators in Java
• The effect of Precedence
6
Java
Be able to
• Write Java programs using primitive data types,
variables, constants and literals
• Use operators, conditional statements and loops

7
Java
Primitive data types and their range
Primitive data types are basic data types.
• Integer type: byte, short, int, long
• Floating point types: float, double
• Character data types : char
• Boolean data type: boolean

Are classes also data


types ? Think about it.

8
Java
Ranges of Primitive Numbers

9
Java
Unicode Character
UNICODE is a 16 bit character stored in hexadecimal
format. \u in beginning of the character is used to
represent hexadecimal character. For example
Character ‘A’ represented in unicode as ‘\u0041’ –
which is the number 65 in base 10.
In fact you can write the entire java program in
unicode characters instead of regular characters.
For example instead of
int a;
You could write
\u0069\u006e\u0074 \u0061;
Even the space and semicolon can be represented
in unicode.
10
Java
Variables
• Variable name must begin with a character after
which it can be sequence of letters/digits.
• Characters like- A-Z, a-z, _,$, or letters of other
languages supported by unicode character set.
• Digits: 0-9 or any unicode that represents digit.
• Length of the variable name is unlimited
• Java reserved words should not be used as
variable names.

11
Java
Keywords/ Reserved words

12
Java
Key Points
• Keywords cannot be used as identifiers (for class
names, variable names, labels etc.).
• goto and const are unused keywords. They are
reserved for future use.
• null, true and false are not keywords. However,
they cannot be used as identifiers.
• enum is a keyword that is introduced in 1.5; assert
is a keyword added in 1.4.
• Java classes are not keywords.

13
Java
Constants
• Value of a constant cannot be changed once assigned.
• final double PI=3.14;

Java naming conventions: variable


name must begin with lower case
and constants must all be in upper
case.

14
Java
Literals
• A literal is the value assigned to a variable. For
example 7 is a literal.
• The literals available in java:
• Integer Literal
• Floating Point Literal
• Character Literal
• Boolean Literal
• String Literal

15
Java
Integer Literals
• Integer literals are integers such as 7 and 10.
• They are stored as int (32 bits).
• There are four ways to represent integer numbers in
the Java language:
1. decimal (base 10)
2. octal (base 8)
3. hexadecimal (base 16).
4. long literals

16
Java
Decimal literal

int a = 10;

17
Java
Octal literal
•Counting from 0 through 7 in octal looks like
this: 0 1 2 3 4 5 6 7 10
int seven = 07; // Equal to
• decimal 7
•int eight = 010; // Equal to decimal 8

What is the decimal


equivalent of 0111?

18
Java
Hexadecimal literal

• Counting from 0 through 15 in hex looks like this: 0 1


23456789abcdef
int x=0X1; // is equal to decimal 1
int x=0xf; // is equal to decimal
15

What is the decimal


equivalent of 0x11?

19
Java
Long literal

•A long literal is a long number (64 bits).


long x = 4000000000L;
long x = 0xFFFFl;

20
Java
Floating-Point Literals
1. Double literals
Examples: 32.4 , 3E1, 3e-1
32.4D , 3E1D, 3e-1D
32.4d , 3E1d, 3e-1d

6. Float Literals
Examples: 32.1F , 32.1f
Guess what happens
if you happen to
attempt to compile :
float f = 32.3;

21
Java
Character Literals
1. Character Literal:
'a‘, or '@’

2. Unicode Character Literal:


'\u0041'; // The letter A

22
Java
Character Literals
3. Escape Sequences Literals:
‘\n’ (enter key), ‘\t’ (tab key)

4. Octal and Hexadecimal character literals:


'\101’ (A), '\u0041‘ (A)

5. ‘\u000a’ inserts a new line character and


‘\u000d’ inserts a carriage return. Therefore,
char c= ‘\u000a’ or char c= ‘\u000d’
gives compilation error.

23
Java
Boolean literals
• true
• false

String literals
“Bill Joy”
“Thank You”
"\u0041“ (A)

24
Java
Declarations

a) Local declarations
b) Class declarations

25
Java
Local declarations
• Declarations made inside a method
• A local variable must always be initialized to a
value before it can be used in calculations or
display

26
Java
Class declarations
• Declarations made outside a method
• A class variable is automatically assigned a
default value if it is not initialised

27
Java
public class Student {
public String name; Class declarations

public int rollno;


public void display(){
Local declarations
String title=“Name:”;
System.out.print(title);
System.out.println(name);
title=“Roll No.:”;
System.out.print(title);
System.out.println(rollno);
}}}
28
Java
Default Values

String null

29
Java
Simple Operators
Arithmetic Unary Operators: + - ++ --

Examples: –5, +5
Pre-increment
y=++x; //(x=x+1; and y=x;)
Post-increment
y=x++; //(y=x; and x=x+1;)

30
Java
Simple Operators
Arithmetic Binary Operator: + - * / %

Example:
int a = 5; int b = 2; int c = a + b;
System.out.println(5%2); // output is 1

31
Java
Simple Operators

Relational Operators: < > >= <= == !=


Example:
int i=10;
int j=20;
System.out.println( i>j );
// output is false
System.out.println(i==10);
// output is true
32
Java
Simple Operators

Conditional Logical Operators: && || ! ?:

33
Java
Simple Operators

Example for || :-
int i=0;
int j=10;
System.out.println( i>j || j>i );
// output is true

&& and || are also called short circuit


operators because they are optimized.

34
Java
//Example for && :-
public class Example{
public static void main(String args[]){
int i=0;
int j=2;
boolean b= (i>j) && (j++>i);
System.out.println(j);
}
} Guess what is the result of
this code ?

35
Java
Simple Operators

Example for ! :-
int i=0;
int j=10;
System.out.println(! (i>j));
// output is true

36
Java
Simple Operators
Syntax of ?:
<variable> = (boolean expression) ?
<value to assign if true> : <value to
assign if false>

Example for ?: :-
int i=0; int j=10;
int k=(i>j)?10:20;
System.out.println(k); // outputs 20

37
Java
Conditional Statements
Should result in boolean value
• if (condition) statement(s)
[else statement(s)] ;
Should result in byte, short,
int or char value
• switch (expression){
[case expression: statement(s)]

[default: statement(s)]
}

38
Java
Loops

for(initialization;condition;iteration)
statement(s);
while(condition) statement(s);
do statement(s) while(condition);
break;
continue;

39
Java
Examples
class Prime{
/*
This program checks if a number is a
prime number. */

public static void main(String str[]){


int num = 5; Initializing variables.
int j=num/2; num is the number
being tested for “prime-
ness”.
boolean flag=true;

40
Java
for (int i=2;i<=j;i++){ Notice the way i is
initialized in the for
if(num%i==0){ loop. i is not
flag=false; available outside
the for loop.
System.out.println("Not prime”);
break; }
else continue; }
if (flag)
System.out.println("Prime number");
}
} 41
Java
public class ReverseNumber{
/*
Reverse a number. */
public static void main(String str[]){
int i=123;
int rem,div=123,rev=0;
do{
rem=div%10;
div=div/10;
rev= rev * 10+rem;
}
42
Java
while(div!=0);
System.out.println(rev);
}
}

Can you
figure out the
logic ?

43
Java
public class Example{
/*
This example counts number of 0s, 1s and
other non-zero or non-one numbers in an
integer.
*/
public static void main(String argv[]) {
int i=102110;
int zeros=0;
int ones=0;
int others =0;

44
Java
int rem;
int div=i;
while(div!=0){
rem=div%10;
div=div/10;
Notice the
switch(rem){ break
case 0: zeros++; statement.
Without it the
break; next statement
case 1: ones++; would get
executed.
break;
default: others++; }}
45
Java
System.out.println(zeros) ;
System.out.println(ones) ;
System.out.println(others) ;
}
}

46
Java
Multiple cases with common
matching statements
Example:
switch(x){
case 10:
case 20: System.out.print(“10 or 20”);
case 30:
case 40: System.out.print(“30 or 40”);
}

47
Java
Predict the output ?

int x = 1;
switch(x) {
case 1: System.out.println("one");
case 2: System.out.println("two");
case 3: System.out.println("three");
}

48
Java
Labeled continue statements

Example:
first: for(int i=0;i<2;i++)
for(int j=1;j>0;j--)
When i=0 and j=1
if(i!=j)
continue first;
else
System.out.println(i+j);
//prints 2
49
Java
Conversions

• Widening Conversions (achieved by automatic or


implicit conversion)

Overall magnitude not lost

• Narrowing Conversions (achieved by casting or


explicit conversion)

50
Java
Automatic or implicit conversion
•The conversion in the direction indicated
happens automatically.
byte->short->int->long->float->double
char
There could be loss of some information during
conversion of the following:
a) int  float b) longfloat
c) long double

51
Java
Example for implicit conversion:
int i=10; byte b=20;

int k=i+b; // ok
byte c=i+b; // error

52
Java
byte b1=20, b2=30;
short s=10;

(b1+b2), (b1+1), (b1+s ) all will result in


a numeric value of int type.

53
Java
byte b=120; // 120 which is int automatically gets
converted to byte.
// The same is true for short also.
Note that int b=10;
byte b1=b; //is erroneous.

54
Java
Explicit conversion or casting

Any conversion between primitives (excluding


boolean) that is not possible implicitly can be done
explicitly.
Conversions like (a) double to long, (b) char to byte
etc.

55
Java
int k=0;
long l=k; //ok, automatic casting
byte b=k; // error- compiler complains of possible
loss of precision
If we are ok with it then we should explicitly cast it.
byte b=(byte)k;

56
Java
Explicit conversion or casting

int k=(int)3.14;
byte b=128; // error
byte b=(byte)128;

Can you figure out


the value of byte b ?

57
Java
byte b = (byte) 128; //Result is –128. Explained below
Step1: Binary : 10000000
Step2: Which is converted to int: 00000000 00000000
00000000 10000000
Step3: Converted to byte : 10000000
Step4: left most is signed bit. So number is negative.
Negative number : Remember, to find out the value of a
negative number using two’s complement notation, you flip
all of the bits and then add 1.
Back to 10000000. Apply sign bit –128.
58
Java
char c=‘A’;
int i=c; // 65(unicode value)
char c=65;// ok 65
int ii=65;
char c=ii; //error
char c=(char)ii;// casting
Though short and char are 16 bits !

short s=c ; // error


short s=(short)c;
59
Java
Integer Bitwise Operators

• ~ & | ^

60
Java
public class AndOrNotEx{
public static void main(String str[]){
byte x=1; // 0000 0001
byte y=3; // 0000 0011
System.out.println(x&y); // prints 1
System.out.println(x|y); // prints 3
System.out.println(x^y); // prints 2
System.out.println(~x); // prints -2
}
Can you arrive at these
} results by manual
calculation ?

61
Java
Logical Operators

• & | ^

62
Java
Comparing conditional and
logical operators
public class Example{
public static void main(String
args[]){
int i=0;
int j=2;
boolean b= (i>j) & (j++>i);
System.out.println(j); //prints 3
}}
63
Java
Compound Operators
• += -= *= /= %= &= |= ^=

Example:
int a = 10;
int b=2;
a+=b; // means a=(int)(a+b);

Similarly
byte b=10;
b+=1; // means b=(byte)(b+1);

64
Java
Precedence
Operators Associativity
-------------------------------------------------------
-
[] . () methodCall() left to right
! ~ ++ -- - + new (cast) right to left
* / % left to right
+ - left to right
>> >>> << left to right
< > <= >= instanceof left to right
== != left to right
& left to right
^ left to right
| left to right
&& left to right
|| left to right
?: left to right
= += -= *= /= >>= <<= >>>= &= ^= |= left to right
Extra spaces in the source code
• Compiler ignores the extra spaces in the source
code in all the cases except when it is involved
with the operators.
• Example:
 a > b;// compiles file
 a > = b; // generates compiler error

66
Java
Learning resources
Self Study (Material)
2. ASCII character set
3. Conversion of octal and hexadecimal
numbers into their decimal and binary
equivalent.
4. IEEE754 standard
Additional Reading
Big and little endian notations
References 67
Java

You might also like