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

UNIT ONE 1.

15

After the file is compiled successfully, byte code(.class file) is generated by the
Compiler. When byte code(.class file) is executed, the following steps are performed
at runtime -

Class loader which is is subsystem of JVM (Java Virtual machine) loads the
java class.

Byte Code verifier checks the code fragments for illegal codes that can violate
access right to the object.
Interpreter reads the byte code stream and then executes the instructions,
step by step.
1.1.5 Data Types
Data types classify the different values to be stored in the variable. In java, there
are two types of data types:

Primitive Data Types


Non-primitive Data Types
Data Type

Primitive Non-Prim itive


String
Array
Boolean NumericC
etc.

Integral
Character

Floating-point
Integer

Int Long Float Double


Boolean Char Byte Short
Default Value Default size
Data Type
false 1 bit
boolean
'AuO000 2 byte
char
0 1 byte
byte 2 byte
0
short
0 4 byte
int
OL 8 byte
long 4 byte
float 0.0f
double 0.0d 8 byte
1.16 UNIT ONE
Data Types Points to Remember
All numeric data types are signed(+/-).
The size of data types remain the same on all platforms (standardized)
char data type in Java is 2 bytes because it uses UNICODE character set.By
virtue of it, Java supports internationalization. UNICODE is a character set
which covers all known scripts and language in the world

1.1.6 Type Conversion


A variable of one type can receive the value of another type. Here there are 2
cases
Case (1) Variable of smaller capacity is be assigned to another variable of bigger
capacity.
double d;
inti = 10;

d i
This process is Automatic and non-explicit, it is known Conversion.
as
The
second case is discussed in next topic.

Program to show usage of Automatic Conversion


public class Test

public static void main(String|] args)

int i = 100;

longl=i; //no explicit type casting


required
float f= ; //no explicit type casting
required
System.out.printin('Int value "+i);
System.out.println('Long value "+);
System.out.println('Float value "+);

Output:
Int value 100
Long value 100
Float value 100.0
UNIT ONE 1.17

1.1.7 Casting
Case (2) Variable of larger capacity is be assigned to another variable of smaller

capacity.
double d =10;
int i;
i (int) d; // Type casting
In such cases, you have to explicitly specify the type cast operator. This process is
known as Type Casting.
In case, you do not specify a type cast operator; the compiler gives an error. Since
this rule is enforced by the compiler, it makes the programmer aware that the
conversion he is about to do may cause some loss in data and prevents accidental
losses.
When you are assigning a larger type value to a variable of smaller type, then
you need to perform explicit type casting

Program to show usage of Explicit Type Casting


public class Test

public static void main(String| args)

double d = 100.04;

long 1 (long)d; //explicit type casting required


=

inti = (int)l; //explicit type casting required

System.out.println("Double value "+d);


System.out.println("Long value "+);
System.out.println(Int value "+i);

Output:
Double value 100.04
Long value 100
Int value 100

1.1.8 Conditional Statements


a
decisions based on
COnditional statements in a computer program support
executed.
if the condition is met, or "true" a certain
piece ofcode is
COndition:
UNIT ON
1.18
user-entered text to lowercase. You
For example, perhaps you want to convert some

want to execute the code only if the user entered some text; if he hasn't, don
execute the code because it will just lead to a runtime error.

There are two main conditional statements used in Java:

if and if-else statements


switch statement.

The if and if-else Statements:


The most basic flow control statement in Java is if statement. This statement is a
statement starts with th
goodchoice for simple decisions.The basic structure of an if
word "if", followed by the statement to test, followed by curly braces that wrap the
action to take if the statement is true.

if (Statement)

/ / do something here.

This statement can also be extended to do something else if the condition is false:

if (statement)

/7 do something here...

else

1/ do sonmething else..

For example, if you are determining whether someone is old enough to drive
you might have a statement that says "if your age is 18 or older, you can drive; else
you cannot drive."

Program to show usage of if statement


public class Ifstatement

public static void main(String[l args)

int age = 18;

if(age >= 18)

System.out.println("You can drive.");


UNIT ON
1.18
some user-entered text to
lowercase. Yo-
For example, perhapsyou want to convert
want to execute the code only if the user
entered some text; if he hasn't, don
runtime error.
execute the code because it will just lead to a

There are two main conditional statements used in Java:

> if and if-else statements

switch statement.

The if and if-else Statements:


This statement is a
The most basic flow control statement in Java is if statement.

choice for simple decisions.The basic structure of


an if statement starts with the
good
word "if", followed by the statement to test, followed by curly braces that wrap the
action to take if the statement is true.

if (Statement)

// do something here...

This statement can also be extended to do something else if the condition is false:

if (statement)

// do something here...

else

1/ do something else.

For example, if you are determining whether someone is old enough to drive
you might have a statement that says "if your age is 18 or older, you can drive; else
you cannot drive."

Program to show usage of if statement


public class Ifstatement

public static void main(Stringl] args)

int age = 18;

if(age= 18)

System.out.println("You can drive.");


1.19
UNITONE

else

System.out.pri
println("You are not old enough to drive ");

Output:
You can drive.

Thereis no limit to the number of else statements you can add.

Conditional Operators:

In the example above, we used a single operator: >=ie. "great than or equal to.

Beloware the standard conditional operators you can use:


Equal to: ==

Not equal to: !=


Less than: <

More than:>
Greater than or equal to: >=

Less than or equal to: >=


In addition to above operators, there are 3 more logical operators used with

conditional statements:
AND:&&
NOT:!
OR: 11
be from 18 to age 85, in which
For example, Let driving age is considered to age
case we could use the AND operator:
else if ( age = 18 && age <= 85)
This will return true only if both conditions are met. The operators NOT and OR
can be used similarly

Program to show usage of AND (&&6) statement


public class Ifstatement

public static void main(Stringl| args)


1.20 UNIT ONE

int age= 18;


if(age > 18 && age c 85)

System.out.println("You can drive.");

else

System.out.printin("You cannot drive.");

Output:
You can drive.

The switch Statement:


The switch statement provides an effective way to deal with a section of
code
that could branch in multiple directions based on a
single variable. It is a preferable
choice when the condition will be met a by single
variable, as it can improve
performance and is easier to maintain.
The switch statement takes a variable and then has a
list of cases or actions to
perform for each value that the variable obtains. It uses the word default to
actions in which the conditions are not met and it perform
uses the word break to stop
performing actions. The default will be executed in case none of the conditions
match the given input.

Program to show usage of switch


statement
public class Switchstatement

public static void main(String[l args)

inti=5;
switch(i)

case 1:
System.out.println (i is 1");
break;
case 2:

System.out.println ('i is 2')


UNIT ONNE
1.21

break;
case 3:

System.out.println ('i is 3");


case 4:

System.out.println("i is 4'");

break;
case 5:

System.out.println(i is 5");

break;
default:
System.out.println("Invalid value");

Output:
i is 5

1.1.9 Looops
of code whern some

is used in programming
to repeat a specific block
Loop
conditions become true. There
are three types of loops in java.

(1) for loop


(2) while loop

(3) do-while loop

The for Loop: number


several times. If the
part of the program
is used to iterate
a
The for loop
recommended to use for loop.
of iteration is fixed, it is

There are three types of


for loops in java.
Simple For LoopP
For-each or Enhanced For Loop

Labeled For Loop


Simple For Loop: condition
initialize variable, check
We can
is s a m e as C/C++.
Ihe simple for loop
and increment/decrement value.
1.22 UNIT O
Syntax:
for(initialization; condition; incr/decr)

//code to be executed

Program to show usage of for loop

public class ForExample

public static void main(String|] args)

forint i=1; ic=5; i++)

System.out.println(i);

Output:

for-each Loop:
The for-each loop is used to traverse array or collection in
java. It is easier to use
than simple for loop because we don't need to increment value and use
notation. It works on elements basis not index. It returns element one
subscript
by one in the
defined variable.
Syntax:
for(lype var:array)

//code to be executed

Program to show usage of for each loop


public class ForEachExample
UNIT ONE 1.23
public static void main(String[] args)

int arll= (10,12,25,30,56);


for(int iarr)

System.out.printlni);

Output:
10
12
25
30
56

Labeled For Loop:


,we ude to
wean hawe name each for loop. Tedoso, we use label before the for loop. It
is useful if we have nested for loop so that we can break/continue specific for loop
Normally, break and continue keywords breaks/continues the inner most for loop

only.
Syntax:
labelname:
for(initialization; condition; incr/decr)

//code to be executed

Program to show usage of labeled for each loop


public class LabeledForExample

public static void main(Stringl] args)

aa:

for(int i-1; i<-3; it+)

bb:
for(int j=1; j<=3; j++)
UNIT ON

if(i-28&c-2)
break aa;

System.out.println(i+""+j);

Output:
11
12
13
21
If you break bb;, it will break inner
use

any loop as shown in below loop only which is the default


program. behavior of
public class LabeledForExample

public static void main(String||


args)
aa

for(int i=1; i<-3; i++)


bb:
for(int j=1;j<=3;j++)

if(i--2&&j=2)
break bb;

System.out.printlni+""+i);
UNIT ONE 1.25

Output:
11
12
13
21
31
32
33

While Loop:
The Java while loop is used to iterate a part of the program several times. If the
number of iteration is not fixed, it is recommended to use while loop.

Syntax:
while(condition)

//code to be executed

Program to show usage of while loop


public class WhileExample

public static void main(String[I args)

int i=1;
while(i<=5)

System.out.println(i)
i++

Output:

4
5
1.26
UNIT ON
do-while Loop:
The Java do-while loop is used to iterate a
part of the program several times
the number of iteration is not fixed and you must have to execute the nes.
loop l
at
once, it is recommended to use do-while loop. The Java do-while loop is
least once because condition is checked after
executecd
loop body.
Syntax:

//code to be executed
whilefcondition);
Program to show usage of do-while loop
public dass DoWhileExample

public static void main(Stringl] args)

int i=1;
do

System.out.printini);
i+t
whileic-5;

Output:

1.1.10 Classes
It is a
template or blueprint from which
that determines objects are
how an object
will behave and what created. A class is an entity
contains fields and methods. A the object will contain. A class
method is like function
object. used to expose behavior of a
UNIT ONNE 1.27

Syntax:

class <class_name>

field;
method;

1.1.11 Objects
An object is nothing but a component which consists of methods
self-contained
and properties to make a particular type of data useful. Object determines the
behavior of the class.

A class is a blueprint or prototype that defines the variables and the methods
(functions) common to all objects of a certain kind.
An object is a instance/specimen of a class. Software objects are often used to

model real-world objects you find in everyday life.

1.1.12 Class Declaration


can think of class
Before you create objects in Java, you need to define a class. We
as a sketch (prototype) of a house. It contains
all the details about the floors, doors,

windows etc. Based on these descriptions we build the


house. Here house is the
be made from the same description, we can create
object. Since, many houses can

many objects froma class.


class Lamp

// instance variable
private boolean isOn

1/ method
public void turnOn()

isOn= true;

1/ method
public void turnOff()

isOn= false;
1.28
UNIT ON
Here, defined a class named Lamp. The class has one instance
we
variak
(variable defined inside class) isOn and two methods turnOn) and turnOff). The iable
variables and methods defined within a class are called members of the class These
The two keywords, private and public in the above program are
modifiers. The private keyword makes instance variables and methods
acce
which can be accessed only from inside the same class. The public
priva
keyword make-
instance variables and methods public which can be accessed from outside
class.
of the
In the above program, isOn variable is
private whereas turnOn0 and turnOff
methods are public. If you try to access
private members from outside of the class
compiler throws error.

1.1.13 Creating Objects


When class is defined, only the specification
for the object is defined; no
memory
or
storageis allocated. To access members defined within the
class, you need to
create objects. Let's create
objects Lamp class.
of
class Lamp

boolean isOn;

void turnOn)

isOn = true;

void turnOff()

isOn= false;

class ClassObjectsExample

public static void main(Stringll args)

Lamp 11 new Lamp0;


=
// create 11
object of Lamp class
Lamp 12 =new Lamp0; //
create 12 object of Lamp class

The above program creates two


objects I1 and 12 of class Lamp.
1.29
UNIT ONE
1.14 Method Declaration and Invocation
access members (call methods and instance variables) by using
You can access

the"."operator.

Example-
1.turnOn0
This statement calls turnOn()
method inside Lamp class for 11 object.
within the
the above statement, all statements
When you call the method using back to
the control of program jumps
bodyof turnOn) method are executed. Then,
the statement following 11.turnOn);
class Lamp

void turnOn() (
ison true;

class ClassobjectsExample
main(String[] args) {
public static void

11.turnon();-

as:
can be accessed
instance variable
Similarly, the
inside
12isOn= false;
members c a n be accessed only from
that, the private (outside of the
It is important to
note
lies within the main) method
12.isOn = false;
code
the class. If the will show
error.

Lamp class), compiler and


invocation
declaration
show m e t h o d
Program to
class Lamp

boolean isOn;
void turnOn)

isOn= true;
1.30

UNIT
void turnOff)

isOn- false;

void displayLightStatus()

System.out.println("Light on? " + isOn);

class ClassObjectsExample

public static void main(String[] args)

Lamp 11 =
new
Lamp(), 12 =new Lamp();

11.turnOn0;
12.turnOff(0

11.displayLightStatus0
12.displayLightStatus0;

Output:
Light on? true
Light on? false
Let us
analyse step by step the above program. Here in the program -

Lamp class is declared.


The class has an instance variable isOn and three methods turnOn0
turnOff) and display LightStatus().
Two objects 11 and 12 of
Lamp class are created in the main() function.
Here, turnOn) method is called
using 11 object: 11.turnOn);
This method sets isOn instance variable of 11
object to true.
And, turnOff() method is called
using 12 object: 12.turnOff0;
This method sets isOff instance variable of 12
object to false.
1.31
UNIT ONNE

true because
Finally, 11.displayLightStatus();
statement displays Light on?
true for 11 object.
isOn variable holds
because isOn
And, 12.displayLightStatus();
statement displays Light on? false
variable holds false for 12 object
within a class are called instance variable for a reason.

Note, variables detined


contains its
is initialized, it's called an instance. Each instance
When an object
objects 11 and 12
are
For example, isOn variable for
of these variables.
own copy
different.

1.1.15 Method Overloading


if they differ in parameters
have same name
or m o r e methods
can
In Java, two or both). These
number of parameters,
different types of parameters, method
(different this feature is called
overloaded methods and
are called
methods
overloading

Example
void func0 f.

void func(int a) . .
floatfunc(double a)
{...
floatfunc(int a, float b) have same name
but accept
overloaded. These methods
method is
Here, func()
different arguments. Overloaded methods
same.
methods are not
these
Notice that, the return type of must differ in parameters they
different return type, but they
or not have
may may
accept.
Why method overloading? be
numbers but there can

addition of the given


have to perform for simplicity).
Suppose, you either 2 or 3 arguments
arguments (let's say int)
any number of
sum2num(int,
two methods
can create
the task, you respectively.
However,
ln order to accomplish three parameters
int) for two and behavior of both
methods is
and sum3num(int, int, as the
confused
in future may get
other p r o g r a m m e r s

name. methods. And,


same but they differ by overloading
accomplish
this task is by is called.
This
methods
better way to overloaded
The o n e of the
passed,
the argument
aepending upon
the program.
readability of
helpsto increase
1.32
UNIT ON
Method overloading:
Method overloading is achieved by -

1. Changing number of arguments.


2. Changing the datatype of arguments.
Overloading by changing number of arguments -

Program to show method overloading by changing number of argument.


class MethodOverloading

private static void display(int a)

System.out.println("Arguments: " + a);

private static void display(int a, int b)

System.out.println("Arguments: "+a+ "and"+ b);

public static void main (String[] args)

display(1)
display(1, 4);

Output
Arguments: 1
Arguments: 1 and 4
In above overloaded method
program, first method accepts one argume
whereas other method accepts two arguments.
Overloading by changing datatype of
arguments
Program to show method overloading by changing
arguments
datatype of

class MethodOverloading

// this method accepts int


private static void display(int a)
UNIT ONE 1.33

System.out.println(Got Integer data.");

1/this method accepts String object


private static void display(String a)

System.out.println('Got String object.");

public static void main(String[] args)

display(1);
display('Hello");

Output:
Got Integer data.

Got String object.


argument. However,
one
one
both overloaded accept
methods
In above program
other accepts String object.
argument of type int whereas
accepts
1.1.16 Constructors-Parameterized Constructors

that is invoked
a method (but not actually a method)
A constructor is similar to
instantiated.

automatically when
an object is and
and a constructor by its name

between a method doesn't


Java compiler distinguish same name
as that of the class, and
c o n s t r u c t o r has

return type. In Java, a

return any value.

class Test

Test0

// constructor body

class and doesn't


as that of the
same name
constructor; it has
iere, Test() is
a

have a return type.

You might also like