OOP Lecture-2

Download as pdf or txt
Download as pdf or txt
You are on page 1of 48

Basics of Java Programming Language

Outline
 Data Type in Java

 Overview of OO principles.

 Overview of Java Programming and types of

Java Program.

 Definition of Java Application, Java Applets

Editing, Compiling and Interpreting.


Data Types
Java defines eight simple types:
1)byte – 8-bit integer type
2)short – 16-bit integer type
3)int – 32-bit integer type
4)long – 64-bit integer type
5)float – 32-bit floating-point type
6)double – 64-bit floating-point type
7)char – symbols in a character set
8)boolean – logical values true and false

1
Byte
 8-bit integer type.
 Range: -128 to 127.
Example: byte b = -15;
 Usage: particularly when working with data
streams.
 short: 16-bit integer type.
 Range: -32768 to 32767.
Example: short c = 1000;
 Usage: probably the least used simple type.

2
int
 int: 32-bit integer type.
 Range: -2147483648 to 2147483647.
Example: int b = -50000;
 Usage:
1. Most common integer type.
2. Typically used to control loops and to index
arrays.
3. Expressions involving the byte, short and int values
are promoted to int before calculation. 32-bit
integer type.
 Range: -2147483648 to 2147483647.
 Example: int b = -50000;
3
Long and float
 long: 64-bit integer type.
 Range: -9223372036854775808 to
9223372036854775807.
Example: long l = 10000000000000000;
Usage: useful when int type is not large enough to hold
the desired value
float: 32-bit floating-point number.
 Range: 1.4e-045 to 3.4e+038.
 Example: float f = 1.5;
 Usage:
 1) fractional part is needed
 2) large degree of precision is not required
4
double
 64-bit floating-point number.
 Range: 4.9e-324 to 1.8e+308.
Example: double pi = 3.1416;
 Usage:
1. accuracy over many iterative calculations
2. manipulation of large-valued numbers

6
char
❑16-bit data type used to store characters.
❑Range: 0 to 65536.
Example: char c = ‘a’;
❑Usage:
1. Represents both ASCII and Unicode
character sets;
▪ Unicode defines a character set with
characters found in (almost) all human
languages.
2. Not the same as in C/C++ where char is 8-bit
and represents ASCII only.
7
Cont’d
❑ boolean: Two-valued type of logical values.
❑ Range: values true and false.
Example: boolean b = (1<2);
❑ Usage:
1. returned by relational operators, such as 1<2
2. required by branching expressions such as if
or for

8
Variables
 declaration – how to assign a type to a variable
 initialization – how to give an initial value to a
variable
 scope – how the variable is visible to other parts
of the program
 lifetime – how the variable is created, used and
destroyed
 type conversion – how Java handles automatic
type conversion
 type casting – how the type of a variable can be
narrowed down
9
Cont’d
 Java uses variables to store data.
 To allocate memory space for a variable JVM
requires:
1. to specify the data type of the variable
2. to associate an identifier with the variable
3. optionally, the variable may be assigned an
initial value
 All done as part of variable declaration.

10
Basic Variable Declaration
 datatype identifier [=value];
 datatype must be:
 A simple datatype
▪ User defined datatype (class type)
▪ Identifier is a recognizable name confirm to
identifier rules
▪ Value is an optional initial value.

11
Cont’d
 We can declare several variables at the same
time:
 type identifier [=value][, identifier [=value] …];
 Examples:
int a, b, c;
int d = 3, e, f = 5;
byte g = 22;
double pi = 3.14159;
char ch = 'x';

12
Variable Scope
 Scope determines the visibility of program elements
with respect to other program elements.
 In Java, scope is defined separately for classes and
methods:
1. variables defined by a class have a global scope
2. variables defined by a method have a local scope
 A scope is defined by a block:
{

}

13
Operators Types
 Java operators are used to build value
expressions.
 Java provides a rich set of operators:
1. assignment
2. arithmetic
3. relational
4. logical
5. bitwise

14
Arithmetic assignments

15
Basic Arithmetic Operators

16
Relational operator

17
Logical operators

18
Bit wise operators

19
Overview of Java
statements

20
If, If..else Statement

 When we need to execute a set of statements


based on a condition then we need to use control
flow statements.
 four types of control statements that you can use
in java programs based on the requirement:
a) if statement
b) nested if statement
c) if-else statement
d) if-else-if statement

3-22
If statement
 If statement consists a condition,
followed by statement or a set of
statements as shown below:
if(condition){
Statement(s);
}
❑ The statements gets executed only
when the given condition is true.
❑ If the condition is false then the
statements inside if statement
body are completely ignored.

3-23
Example of if statement
public class IfStatementExample {
public static void main(String args[]){
int num=70;
if( num < 100 ){
/* This println statement will only execute,
* if the above condition is true
*/
System.out.println("number is less than 100");
}
}
}

3-24
Nested if statement in Java
❑ When there is an if statement inside another if
statement then it is called the nested if statement.
❑ The structure of nested if looks like this:
if(condition_1) {
Statement1(s);
if(condition_2) {
Statement2(s);
}
}
❑ Statement1 would execute if the condition_1 is true.
Statement2 would only execute if both the
conditions( condition_1 and condition_2) are true.

3-25
Example of Nested if statement
public class NestedIfExample {
public static void main(String args[]){
int num=70;
if( num < 100 ){
System.out.println("number is less than 100");
if(num > 50){
System.out.println("number is greater
than 50");
}
}
}
}
3-26
If else statement
❑ This is how an if-else statement looks:
if(condition) {
Statement(s);
}
else {
Statement(s);
}
❑ The statements inside “if” would execute if the
condition is true, and the statements inside “else”
would execute if the condition is false.

3-27
Example of if-else statement
public class IfElseExample {
public static void main(String args[]){
int num=120;
if( num < 50 ){
System.out.println("num is less than 50");
}
else {
System.out.println("num is greater than or equal 50");
}
}
}
3-28
if-else-if Statement
 f-else-if statement is Syntax
used when we need to if(condition_1) {
check multiple statement(s);
conditions.
}
 In this statement we
else if(condition_2) {
have only one “if” and
statement(s);
one “else”, however we
can have multiple “else }
if”. else if(condition_3) {
 It is also known as if statement(s);
else if ladder. This is }
how it looks: else {
statement(s);
} 3-29
Cont’d
 The most important Exercise
point to note here is
1. Java Program to find the
that in if-else-if
statement, as soon as largest of three numbers
the condition is met, using if..else..if
the corresponding set 2. Java Program to check if
of statements get number is positive or negative
executed, rest gets 3. Java Program to check if
ignored. number is even or odd
 If none of the
condition is met then
the statements inside
“else” gets executed.

3-30
Switch Case statement
 Switch case statement is switch (variable or an
used when we have integer expression)
number of options (or {
choices) and we may need case constant:
to perform a different
task for each choice. //Java code
 The syntax of Switch
;
case statement looks like case constant:
this //Java code
;
default:
//Java code
;
} 3-31
Cont’d public class SwitchCaseExample1 {
public static void main(String args[]){
 Switch Case
statement is mostly int num=2;
used with break switch(num+2)
statement even {
though it is optional. case 1:
 We will first see an
System.out.println("Case1: Value is: "+num);
example without
case 2:
break statement and
then we will discuss System.out.println("Case2: Value is: "+num);
switch case with case 3:
break. System.out.println("Case3: Value is: "+num);
default:
System.out.println("Default: Value is: "+num);
}
}
}
3-32
Switch Case Flow Diagram
 First the variable, value or expression which is
provided in the switch parenthesis is evaluated and
then based on the result, the corresponding case
block is executed that matches the result.

3-33
Break statement in Switch Case
 Break statement is public class SwitchCaseExample2 {
optional in switch public static void main(String args[]){
case but you would int i=2;
use it almost every switch(i)
time you deal with {
switch case. case 1: System.out.println("Case1 ");
 Before we discuss case 2: System.out.println("Case2 ");
about break case 3:System.out.println("Case3 ");
statement, Let’s have case 4: System.out.println("Case4 ");
a look at the example default:
below where I am not System.out.println("Default ");
using the break }
statement: }
}
3-34
Example with break statement
public class SwitchCaseExample2 { Question:
public static void main(String args[]) { 1. Why didn’t I use
int i=2; break statement
switch(i) { after default?
case 1: System.out.println("Case1 ");
The control would
break;
itself come out of the
case 2:System.out.println("Case2 ");
switch after default
break;
so I didn’t use it,
case 3: System.out.println("Case3 ");
however if you still
break;
want to use the break
case 4: System.out.println("Case4 ");
after default then
break;
you can use it, there
default:System.out.println("Default ");
is no harm in doing
}
that.
}
} 3-35
Few points about Switch Case
public class SwitchCaseExample2 {
1. Case doesn’t always
public static void main(String args[]){
need to have order 1,
char ch='b';
2, 3 and so on. It can
have any integer switch(ch) {
value after case case 'd':System.out.println("Case1 ");
keyword. Also, case break;
doesn’t need to be in case 'b':System.out.println("Case2 ");
an ascending order break;
always, you can case 'x':System.out.println("Case3 ");
specify them in any break;
order based on the case 'y':System.out.println("Case4 ");
requirement. break;
2. You can also use default:System.out.println("Default
characters in switch "); }
case. }
} 3-36
Cont’d
4.Nesting of switch
3. The expression given statements are allowed,
inside switch should which means you can have
result in a constant switch statements inside
value otherwise it would another switch. However
not be valid. nested switch statements
For example: should be avoided as it
Valid expressions for makes program more
switch: complex and less readable.
switch(1+2+23) Exercise
switch(1*2+3%4) 1. Java Program to check whether
a char is vowel or Consonant
Invalid switch expressions: using Switch Case.
switch(ab+cd) 2. Java Program to make a Simple
switch(a+b+c) Calculator using Switch Case.
3-37
For loop
 Loops are used to execute a set of statements
repeatedly until a particular condition is satisfied.
 In Java we have three types of basic loops: for,
while and do-while. In this tutorial we will learn
how to use “for loop” in Java.
Syntax of for loop:
for(initialization; condition ; increment/decrement)
{
statement(s);
}

3-38
Flow of Execution of the for Loop
 As a program executes, the  Second step: Condition in
interpreter always keeps for loop is evaluated on
track of which statement is each iteration, if the
about to be executed. condition is true then the
 We call this the control statements inside for loop
flow, or the flow of body gets executed.
execution of the program.  Once the condition returns
 First step: In for loop, false, the statements in for
initialization happens first loop does not execute and
and only one time, which the control gets
means that the initialization transferred to the next
part of for loop only statement in the program
executes once. after for loop.

3-39
Cont’d
 Third step: After every execution
Infinite for loop
of for loop’s body, the
increment/decrement part of for The importance of Boolean
loop executes that updates the loop expression and
counter. increment/decrement
operation co-ordination:
 Fourth step: After third step, the
control jumps to second step and Example
condition is re-evaluated. class ForLoopExample2 {
Example of Simple For loop public static void
class ForLoopExample { main(String args[]){
public static void main(String for(int i=1; i>=1; i++){
args[]){
for(int i=10; i>1; i--){ System.out.println("The
value of i is: "+i);
System.out.println("The value of i is:
"+i); }} }}
} }
3-40
Cont’d
 This is an infinite loop as the condition would never
return false.
 The initialization step is setting up the value of
variable i to 1, since we are incrementing the value of
i, it would always be greater than 1 (the Boolean
expression: i>1) so it would never return false.
 This would eventually lead to the infinite loop
condition.
 Thus it is important to see the co-ordination between
Boolean expression and increment/decrement
operation to determine whether the loop would
terminate at some point of time or not.

3-41
For loop example to iterate an array
 Here we are iterating and displaying array elements
using the for loop.
class ForLoopExample3 {
public static void main(String args[]){
int arr[]={2,11,45,9};
//i starts with 0 as array index starts with 0 too
for(int i=0; i<arr.length; i++){
System.out.println(arr[i]);
}
}
}

3-42
Enhanced For loop
 Enhanced for loop is useful when you want to iterate
Array/Collections, it is easy to write and
understand.
 Let’s take the same example that we have written
above and rewrite it using enhanced for loop.
class ForLoopExample3 {
public static void main(String args[]){
int arr[]={2,11,45,9};
for (int num : arr) {
System.out.println(num);
}
}
}
3-43
Cont’d
 In the above example, I have declared the num as
int in the enhanced for loop.
 This will change depending on the data type of
array. For example, the enhanced for loop for
string type would look like this:
Example
String arr[]={"hi","hello","bye"};
for (String str : arr)
{
System.out.println(str);
}

3-44
Exercise
1. Java Program to find sum of natural numbers

using for loop

2. Java Program to find factorial of a number using

loops

3. Java Program to print Fibonacci Series using for

loop

3-45
do-while loop
 do-while loop is similar to while loop, however
there is a difference between them:
 In while loop, condition is evaluated before the
execution of loop’s body but in do-while loop
condition is evaluated after the execution of loop’s
body.
Syntax of do-while loop:
do
{
statement(s);
} while(condition);

3-46
How do-while loop works?
 First, the statements inside loop execute and then
the condition gets evaluated, if the condition returns
true then the control gets transferred to the “do”
else it jumps to the next statement after do-while.
do-while loop exampleclass
DoWhileLoopExample {
public static void main(String args[]){
int i=10;
do{
System.out.println(i);
i--;
}while(i>1);
}
} 3-47
Example
Iterating array using do-while loop
❑ Here we have an integer array and we are iterating the
array and displaying each element using do-while loop.
class DoWhileLoopExample2 {
public static void main(String args[]){
int arr[]={2,11,45,9};
//i starts with 0 as array index starts with 0
int i=0;
do{
System.out.println(arr[i]);
i++;
}while(i<4);
}
}
3-48

You might also like