Java Unit 1 Up To Control Statements
Java Unit 1 Up To Control Statements
1
UNIT 1
INTRODUCTION
⚫ Computer is an electronic device that accepts instructions in
a specific language.
⚫ Computer understands machine language only.
⚫ In day today’s life change in technology takes place to fulfil
the end user needs using computer.
⚫ The humans can’t understand machine [Link] is the
reason behind developing the S/W using human
understanding language s such as C, C++, JAVA, and
C#(Latest).
2
⚫ ‘C’ was introduced in 1980s as a structured language by Brain
Kernighan and Dennis Ritchie. As technology grew
complex problems are not efficiently solved using POP.
⚫ To overcome drawback of POP, the OOP’s language were
introduced to reduce complexity.
⚫ OOP facilitate reliability and maintainability
⚫ The OOP, C++ was introduced by Bjarne Stroustrup.
⚫ Java is another pure object oriented language developed by
James Gosling and His colleagues at Sun Micro
Systems.
3
⚫ JAVA was initially called Oak(Oak trees outside Gosling
office)
⚫ JAVA is the most significant language has capability of
moving from one device to another easily.
⚫ JAVA was designed to execute applets( the programs
executed using web browser).
⚫ Gradually JAVA accepted as wide programming language,
replacing C or C++.
4
Java ?
⚫ It is a high level object oriented programming
language. It is designed to be platform
independent due to Java Virtual
Machine(JVM), meaning that java programs can run
on different machines without modification.
OBJECT Data +
1. Object.
2. Class.
3. Data encapsulation.
4. Data abstraction.
5. Inheritance
6. Polymorphism
7. Dynamic binding
8. Message passing
8
1. Object
9
2. Class
10
3. Data encapsulation
12
5. Inheritance
It is the process by which object of one class acquire
the properties of objects of another class.
Inheritance means to link and share some common
properties of one class with the other class from
which it is derived, is also referred as “Reusability”.
Base class- It gets inherited to another class. It is also
known as ‘existing’ class
Derived class(Sub Class)- It is inherited from Base
Class.
13
6. Polymorphism
The word ‘polymorphism’ means ‘many-forms’.
The term ‘polymorphism’ is defined as the process
of using a function/method for more than one
purposes.
An operation exhibit different behaviour in different
instances.
Ex1- 2+3=5, Addition
a+b=ab, Concatenation
note : an operator used with different parameters called
Operator Overloading
14
Ex2- ‘volume’ is a method to calculate different
shapes
I. volume(side)-It is used to find volume of cube.
II. volume(l,b,h)-It is used to find volume of cuboid.
15
7. Dynamic binding
Binding refers to the linking a procedure call to
the code to be executed in response to the call.
It is also known as ‘Late binding’ or ‘Runtime
Polymorphism’.
It improves flexibility.
Supports extensibility to the code without modifying
existing code.
16
8. Message passing
Objects can communicate with each others by
passing messages same as people passing
message with each other.
STEPS
I. Creating classes that define objects and their
behaviour.
II. Creating objects from class definitions.
III. Establishing communication among objects.
17
Benefits of oop or advantages of
oop
i. The reusability of program code is enhanced.
ii. The software quality and performance are improved.
iii. Modularity is achieved.
iv. Data abstraction makes the software easier to handle
v. Software for complex tasks can easily be developed.
vi. It is easy to partition the work in a project based on
objects.
18
Applications of oop’s
19
Difference between pop and oop
OOP
Emphasis on functions rather Emphasis on data rather than
than data. the function.
It allows data flow freely The data is restricted to be used
throughout the program. in a specific program area.
25
Structure of Java compiler and interpreter
Intermediate code
Interpreter
Code
OS/2 UnIX
• Compiler converts the source code into binary form called byte
code.
28
5. Access Modifiers: Control the visibility ( public,
private, etc).
STRUCTURE OF JAVA PROGRAM
Package Statement
Import statements
Interface statements
Class definitions
main method class
{
main method definition
29 }
Documentation Section: It refers to the comments at
the beginning of a java program. This section provides
information about author, program, purpose.
Supports 3 Types of comments and which are not executed
by JVM.
1. Single-Line Comment(//): Used for short descriptions.
30
Package Statement: it is optionally user defined and placed
after documentation [Link] use ‘keyword’ package to
declare the package name.
Ex: import [Link];// import single class
Ex: import [Link].*;//Import the whole package
31
Interface Statements: It is optional section and created by
using keyword i.e ‘interface’. It contains only constants and
method.
Ex: interface car
{
void start();
void stop();
}
Class Definition: We cannot create java program except
‘class’. Every java program must have minimum one class
using the keyword class, which contains ‘main()’ method.
Ex: class Student
{
}
32
main method():
⚫ It is essential for all java programs. Because actual execution of
programs takes place from main().
⚫ It is defined inside the [Link] objects are created and
methods are called in main().
Sample Java Program
public class Simple
{
public static void main(String args[])
{
void display()//method
{
[Link](“Welcome”)
}
}
}
33
Rules to ‘class’ Name.
⚫ Class name must start with ‘UPPERCASE’ . Ex: class Simple
but not class simple.
34
Data types, variables and operators in java
Data types define the kind of values a variable can
[Link] every variable must have a declared type.
Types
1. Primitive data type :These are basic building blocks in
java, directly operated upon machine level instructions.
Ex: int, float, long, char, boolean , byte, double etc are of 8
types.
2. non- Primitive data type: these are complex data types
derived from primitive data type.
Ex: String, Array, Classes, Interfaces, Objects.
35
DATA TYPES,VARIABLES AND OPERATORS IN JAVA
Data type
Primitive non-Primitive
Boolean Numeric
string array etc
boolean Character Integral
36
1. Boolean Data Type:
It is primitive data type used to store only two values either
‘True’ or ‘False’.
It stores one bit of information.
37
3. Short data type:
It is primitive data type used to store small integer values.
Default value is 0
Its is of 16 bits size representation where value ranges from
-32768 to 32767.
Ex : short s=1000;
38
5. Long data type:
It is primitive data type to store larger integer values.
Default value is 0L(used for long Literals)
Its is of 64 bits size representation, where value ranges from -
263 TO 263-1
Used to store factorial of large number.
Ex long a=1000L;
39
7. Double data type
It is primitive data type to store decimal numbers with
higher precision than float.
Default value is 0.0d.
Its is of 64 bits size representation, where value ranges from ±
4.9 * 10-324 to ± 1.8 * 10308
Ex: double num1=10.25;
8. Char data type
It is primitive data type to store single character.
Default value is ‘\u0000’(null character).
Char is 1 byte but java uses 2 byte size representation, where
value ranges from \u0000 to \uffff(65,535)
Ex char letter=‘A’;
Ex char digit=‘7’;
40
JAVA VARIABLES & OPERATORS
A variable is a named memory location, which is used
to store data values such as ‘name’,‘type’, and ‘value’.
It is a reserved space in memory.
It acts as a container for values that can change during the
programs.
Syntax :
<data type><space> <variable name>
Ex : int a;// here ‘a’ is variable.
41
TYPES OF VARIABLES
1. Local Variable
2. Instance Variable
3. Static Variable
Local Variable
A variable declared inside the body of the method,
constructor, or block is called local variable.
Must be initialized before use.
Variable ‘Scope’ is limited to the method/block
and accessible only within that method.
not accessible outside the method/function.
42
Local Variable Example
class Local
{
public static void main(String[] args)
{
int num=10;//Local variable
[Link](“Number :” +num)
}
}
note : ‘String[] args’ Or ‘String args[]’ both type arguments
are valid in main () function.
43
Instance Variable
These variables are declared within class and
outside of any method is said to be instance
variable.
Instance variables are also called as data members.
These variables can easily be accessed in all the
members of the class.
These are allocated as individual copy of each
object(instance) of the class.
44
Instance Variable Example
class Person
{
String name;//instance variable
int age; //instance variable
public void display()
{
[Link](“Name:” + name +”Age:” +age);
}
}
45
Static Variable
A variable is declared as ‘static’ within the
class and also known as class Variable.
46
Static Variable Example
class Sample
{
static String college=“Akash College”;//Static variable
void display()
{
[Link](“college” +college);
}
}
public class StaticExample
{
public static void main(String[] args)
{
Sample ob1=new Sample();// ob1 object created using ‘new’ opeartor
Sample ob2=new Sample();
[Link]();
[Link]();
}
47 }
STEPS TO EXECUTE
C:\Users\Admin>cd C:\Users\Admin\Desktop\BCA CLASSES
college:Akash College
college:Akash College
48
Rules For Naming The Variable
Start with a letter, underscore(_), or $ (but not number).
Cannot be a java keyword i.e int, class, float etc.
Case sensitive, where age and Age are different.
Variable name should be meaningful, which easily depicts
its purpose.
Ex: int age; and int $price; are valid variables.
Ex: int 1number; and int double; are invalid
variables
49
Operators In Java
An Operator is a symbol that is used to perform
operations.
Types
1. Arithmetic Operator
a. Unary operator.
b. Binary operator.
c. Ternary operator.
2. Assignment operator
3. Relational operator
4. Logical operator
5. Bitwise operator
6. Shift operator
50
1. Arithmetic Operator
⚫ Used to perform basic mathematical operations.
⚫ Examples: + (addition), - (subtraction), * (multiplication), /
(division), % (modulus).
⚫ The values which are used in operations known as operands.
Ex: a+b, where a and b are operands.
Arithmetic Operations: a=10,b=5
⚫ Addition: a+b=15
⚫ Subtraction: a-b=5
⚫ Division: a/b=2
⚫ Multiplication: a*b= 50
51
a. Unary operator
Operate on a single operand to perform various operations.
Ex: + , - , ++, - -, ! (logical nOT).
1. ‘+’ : It is unary operator used before the operand, which
results in the same value of the variable.
Ex: if a=5, then +a will result in 5.
if a= -10 , then +a will result as +(-10)= -10.
52
3. ‘++’ : It is unary increment operator increases the
value of an operand by one(1).
TWO TYPES
Prefix
Prefix:When increment operator is used before
the operand is called prefix operator.
Prefix operator means the value of variable changes
before the action takes place.
Ex: M=4;
M=++M;
M will Result as : 5.
53
Postfix
Postfix:When increment operator is used after an
operand is called postfix operator.
Postfix operator means the value of variable changes
after the action takes place.
Ex: M=4;
M=M++;
M will Result as : 4.
note: an incremented value of M will be affected after an
action and included in next appearing variable M.
Ex: M=4;
M=M++ +M; // M=4++ +5; // M will Result as : 9
54
4. ‘- -’ : It is unary decrement operator decreases the value of an
operand by one(1).
TWOTYPES
Prefix
Prefix:When decrement operator is used before
the operand is called prefix operator.
Prefix operator means the value of variable changes
before the action takes place.
Ex: M=4;
M=- -M;
M will Result as : 3
55
Postfix
Postfix:When decrement operator is used after an
operand is called postfix operator.
Postfix operator means the value of variable changes
after the action takes place.
Ex: M=4;
M=M- -;
M will Result as : 4.
note: an decremented value of M will be affected after an
action and included in next appearing variable M.
Ex: M=4;
M=M- - +M; // M=4- - +3; // M will Result as : 7
56
b. Binary Operators
An Operator, operates on Two Operands to
perform various operations.
Ex: + , - , *, / and %.
⚫ Addition: a+b.
⚫ Subtraction: a-b.
⚫ Division: a/b.
⚫ Multiplication: a*b.
⚫ Modules/Remainder: a%b.
57
c. Ternary Operator(Conditional Assignment):
This operators deals with three operands.
Syntax:
variable=(test expression)? expression1:expression2
Ex: a=5; b=3;
Max=(a>b)? a : b
Here, the value 5 is stored in Max, as a>b is true.
Min=(b>a)? a : b
Here, the value 3 is stored in Main, as b>a is false.
Note1: if (condition), becomes true Means ‘a’ is stored else
‘b’ is stored.
Note2:Ternary Operator is equivalent to the ‘if-else’
construct in java language.
58
2. Assignment Operator
⚫ Used to assign values to variables.
⚫ Examples: = (simple assignment),
⚫ Short Hand Assignment operators are, +=
(addition assignment), -= (subtraction assignment),
*= (multiplication assignment), /= (division
assignment), %= (modulus assignment)
⚫ It assigns the value on its right to the operand on its
left.
⚫ Ex: a=b; a+=b; a -=b etc
59
3. Relational Operator
These operators compares the values of two operands
and determine the relationship between them.
It always returns a boolean type value either True or
False.
Symbols are : < , >, <=, >=, = =, ! =.
Examples: a>b; a<b; a>=b; a<=b;
a==b; a!=b;
If a=3; b=5;
If(a>b), returns false.
If(a<=b) , if any one condition is satisfied, which
returns true as ‘less than ’is valid condition.
60
4. Logical operator
These operations are used to perform logical
operations on ‘boolean’ values(true or false).
These operators yield true or false depending
upon the outcome of different conditions.
Logical operators are : AnD(&&), OR(||),
NOT(!).
a=2, b=3;
(a>b) && (b<a) => (F)&&(T) , results as False.
(a>b) || (b<a) => (F)||(T) , results as True.
!(5>3) => !(True) , results as False
61
5. Bitwise Operator
These operators performed on bits representation.
Bitwise AND (&)operation: Returns 1 only if both bits
are 1, otherwise returns 0.
Ex: 0101 & 0011, result is 0001.
Bitwise OR(|) operation : Returns 1 if any one bit is 1,
otherwise returns 0.
Ex: 0101 | 0011, result 0111.
Bitwise NOT (~)operation: Inverts all bits i.e 1->0, 0->
1.
Ex: 0011, result is 1100.
62
6. Shift Operator
Perform operations at the bit level.
Examples: Left Shift(<<), Right Shift(>>).
Left Shift: It shifts bits to the left and adds 0’s to on
the right.
Ex: 0101(5) => 1010=10.
Right Shift: It shifts bits to the right and adds 0’s to
on the left.
Ex: 0101(5) => 0010=2.
63
CONTROL STRUCTURE
⚫ Control structures in java determines the flow of control in
condition based operations.
⚫ Executing statements sequentially unless end of the program
is reached is called flow of control.
CATEGORIES
a. Normal flow of control.
b. Decision making statements.
⚫ Simple if statement
⚫ if- else statement
⚫ if- else-if ladder
⚫ Nested if statement
⚫ Switch case statement(Multiple branching of control)
64
c. Loop Statements
⚫ for loop.
⚫ While loop.
⚫ do – while loop.
d. Jump statement
⚫ break statement
⚫ continue statement
65
NORMAL FLOW OF CONTROL:
⚫ It is the control keeps on executing each and every statement
of the program on the basis of top down approach.
⚫ Ex:
public class Expressions
{
public static void main(String args[] )
{
int a=2, b=3, ans1, ans2;
ans1=a*a+2*a*b+b*b;// (a+b) the whole square
ans2=a*a-2*a*b+b*b;// (a-b) the whole square
[Link](“The first answer =” +ans1);
[Link](“The second answer =” +ans2);
}
}
66
DECISION MAKING STATEMENTS
⚫ Block of statements executed when the given
condition holds true.
67
⚫ If statement
Syntax:
If(condition)
{
statement 1;
}
⚫ If-else
Syntax:
If(condition)
{
statement 1;
}
else
{
statement 2;
}
68
⚫ if-elseif-else ladder
Syntax:
if(condition)
{
statement 1;
}
else if(condition)
{
statement 2;
}
else
{
statement 3;
69 }
⚫ Nested if-statement
Syntax:
if(condition 1)
{
if(condition 1)
{
statement 1;
}
else
{
statement 2;
}
}
70
⚫ Switch case
Syntax:
Switch(expression)
{
case 1:
statement 1;
break;
case 2:
statement 2;
break;
case n:
statement n;
break;
default: statement;
}
71
Loop Statements: A construct is a Set of statements which
are repeatedly executed till the condition is satisfied such a
construct is said to be a loop.
LOOP
Loop Loop
for
If
Terminate
75
2. While loop:
⚫ This loop is used when user is not aware of
iterations.
⚫ Decision is made at the beginning point only.
⚫ Syntax:
While(Test Condition )
{
statements;
}
⚫ It executes block of statements until the condition is
true, if false it will terminate the loop.
⚫ Number of iterations takes place during the process.
76
Example: While Loop
public class SampleWhile {
public static void main(String args[])
{
int r=10,t=1;
double p=100.0, si=0.0;
while(p<=150.0)//executed until ‘p<=150’ and unknown iterations
}
si=(p*r*t)/100.0;
p=p+si;
[Link](p);
}
}
77
}
while loop output
C:\Users\Admin\Desktop\JavaPrograms>java SampleWhile
110.0
121.0
133.1
146.41
161.051
78
3. Do-While loop:
⚫ This loop is used when user is not aware of iterations.
⚫ Decision is made at the end point only(Exit Control)
⚫ Syntax:
do
{
statements;
} While(Test Condition );
⚫ It executes block of statements until the condition is
true, if ‘false’ it will terminate the while loop with
semicolon(;) at end.
⚫ Minimum ‘once executed’ before Number of iterations
takes place during the process.
79
Example: do-while ;
public class SampleDoWhile {
public static void main(String args[]) {
int r=10,t=1;
double p=100.0,
si=0.0; do
}
si=(p*r*t)/100.0;
p=p+si;
[Link](p);
} while(p<=150.0);
}
}
80
Do-while output
C:\Users\Admin\Desktop\JavaPrograms>javac
[Link]
C:\Users\Admin\Desktop\JavaPrograms>java SampleDoWhile
110.0
121.0
133.1
146.41
161.051
82
Example: break
public class SampleBreak
{
public static void main(String args[])
{
int i;
for(i=1; i<=10;
i++) {
if(i==5)
break;
[Link](i);
}
}
}
Output for break
C:\Users\Admin\Desktop\JavaPrograms>javac
[Link]
C:\Users\Admin\Desktop\JavaPrograms>java SampleBreak
1
2
3
4
Note: ‘i<=10’, i values to be printed from 1to 10, but
where the ‘i==5’ condition ‘break’ the other
iterations from printing. After using ‘break’ , no
statement is executed.
84
continue:
⚫ When we use ‘continue’, the control will skip the current
iteration of the loop and will resume back for the next
iteration.
Example: continue
public class SampleContinue
{
public static void main(String args[])
{
int i;
for(i=1; i<=5; i++)
{
if(i==3)
continue; // skips ‘3’ and continue to print from 4
[Link](i);
}
}
}
85
Output for‘continue’
C:\Users\Admin\Desktop\JavaPro
grams>javac
[Link]
C:\Users\Admin\Desktop\Java
Programs>java
SampleContinue
1
2
4
5
Note : Above output is generated
from 1 to 5, where by skipping
number ‘3’ .
86