you
before we introduce the Java platform
how about answering a very basic
question what is a PC take your time the
dictionary definition of computer is
that it is an electronic device capable
of performing computations it has many
peripherals like a monitor and keyboard
to accept or display data to users and
memory to store information but the
heart of the computer is its processor
which does all the thinking for the
computer coming back to our definition
of computer you may have noticed the key
word electronic thinking of it if a
computer is an electronic device how can
it understand it display text images
videos and other rich media information
well a computer understands only
electronic signals where a five volt
current represents a binary one and a 0
volt current represents a binary 0 your
PC is continually bombarded with these
electronic pulses which it interprets 8
bits of such signals are grouped
together and text numerical and symbols
are identified by unique patterns of
these 8 electric pulses for example the
pound symbol is represented by the
pattern 1 0 1 0 1 0 1 0 instruction to
add two numbers is represented by
pattern 1 0 0 0 0 0 1 1 this is 8-bit
computing current day processors are
capable of understanding and decoding 64
bits at a time suppose you are asked to
write a program to add two numbers say
add one with two assembly language is
the most elementary form of software
development languages your code to add
two numbers in this language would look
like store number one at memory location
say A
store number two at memory locations say
be add contents of location a and B
store results the way you feed this code
to the processor would depend on the PC
you are using back in the 50s when
computers were huge and consumed a great
deal of power you would convert your
assembly language code into
corresponding machine code of ones and
zeros using mapping sheets and punch the
machine code into punch cards and then
feed those punch cards to the computer
with advancement in technology i/o
devices were embedded you could directly
type the program into the PC using a
program called assembler converted into
corresponding machine code and feed that
to your processor that apart you will
also have to make calls to operating
systems providing functions to display
the output of code with advancement in
software development languages this
entire assembly code could be shrinked
into just one line print f1 plus 2 a
software called compiler is used to
convert your C language code into
assembly code and the assembler converts
it into corresponding machine code
though present-day compilers come
bundled with assembler they can directly
convert your higher language code into
machine codes
now suppose Windows operating system is
running on this Intel processor
combination of operating system plus the
processor is called the platform the
most common platform in the world is the
Windows and Intel called the Wintel
platform the other popular platforms are
AMD and Linux PowerPC and Mac OS X now
with change in processors the assembly
instructions will change for example the
add instruction in Intel may be called
Edition for AMD or mass ad for PowerPC
and obviously with change in operating
system the level and nature OS level
call
we'll also change as a developer I want
my software program to work on all
platforms available to maximize my
revenues so I would have to buy separate
compilers which convert my print F
command into the native machine code but
compilers come expensive and there's a
chance of compatibility issues enter
Java language the code to display
addition of two numbers is system dot
out dot print in one plus two saved as a
dot Java file using the Java compiler
the code is converted into an
intermediate code called the bytecode
the outcome is a dot class file this
code is not understood by any platform
but only a virtual platform called the
Java Virtual Machine this virtual
machine resides in the RAM of your
operating system when the virtual
machine is fed with this bytecode it
identifies the platform it is working on
and converts the bytecode
into the native machine code in fact
while working on your PC or browsing a
web whenever you see either of these
icons be assured the Java Virtual
Machine is loaded in your RAM but what
makes Java lucrative is that code once
compiled can run not only on all PC
platforms but also Mobile's or other
electronic gadgets supporting Java has
Java is a language as well as a platform
to understand the compiling process in
Java let's first take a quick look at
the linking process in C suppose in the
main you have called two functions F 1
and F 2 the main function is stored in a
file a 1 dot C function f 1 is stored in
a file a 2 dot C function f 2 is stored
in a file a 3 dot C all these files are
fed to the compiler whose output is the
corresponding object files which is the
machine code the linker will Club these
three files together and produce an exe
file during program run a loader program
will load an exe into the RAM for
execution let's look at the process for
Java in your main you have two methods F
1 and F 2 main method is stored in file
a one dot Java
F one is stored in file a to Java F 2 is
stored in file a 3 dot Java the compiler
will compile the three files and produce
corresponding dot class files which
consists of the bytecode unlike C no
linking is done the JVM Java Virtual
Machine resides on the RAM during
execution use in class loader the class
files are brought on the RAM the
bytecode is verified for any security
breaches using the bytecode verifies of
the JVM
next the execution engine will convert
the bytecode into native machine code
this is just in time compiling it is one
of the main reasons why Java is
comparatively slow there is more to the
jvm architecture which will be discussed
in later tutorials
open Notepad declare a class with name a
declare the main method public status
void main string a r g s type the system
dot out dot print Ln which displays the
text first Java program
you
save the file as first program dot Java
make sure to select all files while
saving the file in our working folder a
Java file is created in a command prompt
make sure your current directory path is
the same as where your Java file is
stored enter Java C first program dot
java
this will compile the code the code is
showing error the string is not declared
correctly let's correct the error and
save the file compile the code again
after making the changes in the string
the code is compiled successfully if you
look in your working folder you can see
that a file named a dot class has been
created to execute the code enter the
command Java followed by the class name
as expected output first Java program is
displayed now if you copy and paste the
same code in IDE like NetBeans the
compiling and execution is done on the
click of a button using IDE is more
convenient and can improve your
efficiency but since you are learning
Java we will stick to notepad
suppose you want to create banking
software which will perform deposit and
withdraw operations and show the balance
let's examine how the software would be
created using different programming
languages the earliest programming
language were unstructured programming
language a very elementary code of the
banking applications in unstructured
programming language will have two
variables for one account number and
another for account balance suppose a
deposit for $100 is made next you will
obviously show the latest account
balance now the amount of $50 is
withdrawn again you show the latest
account balance in fact for any further
deposit or withdrawal operations you
would program the same steps again and
again here the code for display of
account number and account balance are
exactly the same and it is repeated
throughout the program such repetition
is a waste of programming efforts and
increases coding costs and possibility
of coding errors with the advent of
structured programming common lines of
your code were put in a structure called
functions or methods and wherever
required a simple call to their function
was made now if you can examine closely
throughout the program we are dealing
with data or performing certain actions
on the data in fact having data and
performing operations on the data is the
very basic characteristics of any
software program thought leaders in
software development came up with an
idea to combine data and actions
together hence the birth of
object-oriented programming commonly
called oops
the same code in oops will have some
data and the actions to be performed on
that data
by this combining of data and action we
have several advantages over structured
programming namely abstraction and
capsulation inheritance and polymorphism
we will learn them in detail in
succeeding tutorials
to understand the principle of
abstraction let's do an exercise list
the top ten information like name
address etc of your customer to create a
banking application pause the tutorial
and complete the exercise
I'm sure you did a good job in
identifying the information some of the
information that will be useful would be
full name address contact number tax
information favorite food favorite movie
favorite actor favorite band and I am
sure you're wondering what the heck I'm
talking about well the amount of
information available for you as an
individual is infinite we do not need
all the available information for a
customer to create a banking application
but only the relevant ones in essence we
are selecting data from a larger pool
hence the name abstraction but the same
information once abstracted could be
used in a wide range of applications
like this data set can not only be used
in banks but will also be useful in
employee databases hospitals government
databases the advantages the same set of
data can be reused
coming back to the banking example that
we used earlier suppose a hacker is able
to gain access to the code and tries to
deposit an invalid amount into your
account usually variables in a class are
set as private and they can only be
accessed via corresponding methods so
such access is not allowed next he tries
to use the deposit method to carry out
his operation but the method
implementation has checked for negative
values and throws an error
thus you never expose your data to an
external party which makes your
application secure the entire code can
be thought of as a capsule and you can
only communicate to it via messages
hence the name encapsulation
consider the same banking application
from previous examples we're supposed to
open two different account types one for
saving and another for checking also
known as current let's compare and study
how we can approach coding from a
structured and object-oriented
programming perspective instruct your
programming I will create two functions
one to withdraw and another to deposit
since the working of these functions
remain same across the accounts while
using the object-oriented approach we
will create two classes each having an
implementation of deposits and
withdrawals this is redundant extra work
now there's a change in requirement
specifications for something that is so
common in software industry you're
supposed to add functionality privilege
banking account with overdraft facility
for a background overdraft is that you
can withdraw and amount more than the
available balance in your account using
functional approach I would have to
modify my withdraw function which is
already tested and perhaps code a method
like this one which will take care of
new requirements using oops approach I
just need to write a new class with
unique implementation of withdrawal
functions I never touched the tested
piece of code what if the requirement
changes further like to add credit-card
account with its own unique requirement
of deposits using structural approach
you have to change the tested piece of
deposit code as well but using
object-oriented approach you will just
create a new class with its own unique
implementation of deposit methods so
even though structural programming seems
like an easy approach initially OOP wins
in the long term but one may argue that
across all classes you have repeated
pieces of code to overcome this you
create a parent class say a count and
implement the same function
of deposit and withdrawn and make child
classes inherit account so that they
will have access to withdraw and deposit
functions in account class the functions
are not required individually
this is inheritance but wait there is a
problem with the method of
implementation for withdraw for
privilege and deposit for credit card is
different to overcome this you can
override the method implementation in
your base class such that when withdrawn
method for the savings account is called
this method is executed
but when withdraw method for the
privilege account is called the custom
method is executed
this is polymorphism
suppose you want to build software for a
pet management system especially meant
for dogs obviously you need to store
information about various breeds of dogs
in your system you need to model
real-life entities that is dogs into
software objects and the million-dollar
question is how do you design such a
software first let's do an exercise you
see the picture of three different kinds
of dogs pause the tutorial and list down
the differences between them I hope you
did a good job determining the
differences some of those differences
would be breed size age color etc if you
think for a minute these differences
also in essence are common
characteristics shared by these dogs
they can form data members for your dog
object next identify common behavior
among the dogs here's a hint eat sleep
sit and run so we have identified
actions for our software objects for
dogs
next I will define the class dogs with
the data members such as size age etc
and with methods such as eat fit sleep
etc and for different values of data
members in my class I will get different
dog objects you can design any boot
program using this approach
let's create a class account with
instance variables a and B and a method
set data to set the values for a and B
and the method show data to display the
values for a and B
a main method
wherein we create an object of account
class
and call methods set data and show data
let's compile and run the code
our expected output a and B should be
initialized to the values two and three
respectively but the value is zero
why let's investigate in the methods set
data the arguments are declared with
names a and b while the instance
variables are also named a and B during
execution the compiler is confused
whether a on the left side of the
assigned operator is the instance
variable or the local variable hence it
does not set the value of a when methods
set data is called the problem can be
overcome by this keyword append both a
and B with the this keyword followed by
a dot operator during code execution
when your object calls method set data
the keyword this is replaced by the
object handler o
B J now the compiler knows the a on the
left hand side is the instance variable
whereas a on the right hand side is the
local variable the variables are
initialized correctly an expected output
is shown suppose you are smart enough to
choose different names for your instance
variables and method arguments but this
time around you create two objects of
the class each calling the set data
method how will the compiler determine
whether it is supposed to work on the
instance variable of object 1 or object
2 well the compiler implicitly appends
the instance variables with the this
keyword such that when object 1 is
calling a set data method instance
variables are appended by its reference
variable while object 2 is calling the
set data method instance variables of
object two are modified this process is
taken care of by the compiler itself and
you do not need to append this keyword
explicitly unless there is some
exceptional situation as in our earlier
examples
consider that some line of your code is
calling method m1 in the stack a frame
will be created from method m1 the
variable X in M 1 will also be created
in a frame for m1 in the stack m1 is
calling method m2 in the stack a new
frame will be created for m2 on top of
the frame m1 variable B and C will also
be created in the frame m2 in the stack
say method m2 is calling method m3 again
a frame m3 is created on the top of the
stack m3 is creating an object for a
class account which has two instance
variables P and Q the new operator will
create an object in a heap the reference
variable ref will be created in a stack
the assignment operator will make a
reference variable to point to the
object in the heap once the method has
completed its execution the flow of
control will go back to the calling
method which in this case is m2 the
stack from method m3 will be flushed out
since the reference variable will no
longer be pointing to the object in the
heap it will be eligible for garbage
collection once m2 has completed its
execution it will be popped out of the
stack and all its variables will be
flushed and will no longer be available
for use likewise for method m1
eventually the flow of control will
return to the start point of the program
which usually is the main method
you
consider the following scenario the
class media player
media player has two subclasses CD
player and DVD player each having its
own implementation of play method
another class combo drive is inheriting
both CD and DVD which play method should
it inherit
this can cause a serious design issue
and hence Java does not allow multiple
inheritance but suppose you have
requirements where your class dog is
inheriting class animal and class pet
but you cannot extend to classes in Java
so what would you do
the solution is interface and interface
is 100% abstract class and has only
abstract methods a class can implement
any number of interfaces class dog can
extend to class animal and implement
interface pet
let's create Class C one
with method m1
and a main method
create an object of c1
and call method m1
now let's say I want to put this class
into the package at the first line of
code right the statement package P one
save file as demo dot Java let's compile
the file
compilation is done in a class file
created but we have to create a package
for this use command Java C - D demo
Java
this command forces the compiler to
create a package here dot operator means
the current working directory if you
check out the folder a package p1 is
created which has class c1 if you
compile the same file with double dots
the package will be created in the
parent directory which is the C Drive
let's say you want to create a sub
package modify the statement as p1 dot P
to compile the file
in your p1 folder another folder p2 is
created with class c1 to execute the
code mention the fully qualified name of
the class that is package name and sub
package name followed by the class name
there are two types of errors
compile-time and run-time compile time
errors can be again classified into two
types syntax errors for example instead
of declaring a variable integer int a
you mistakenly declare it as in a for
which the compiler will throw an error
or you can have a semantic error where
you have declared a variable int a and
after some lines of code you again
declare an integer as int a all these
errors are highlighted when you compile
your code a runtime error is called an
exception error and is any event that
interrupts normal flow of program
execution
suppose you have coded a program to
access a server and things work fine
while you are developing the code during
the actual production run the server is
down and when your program tries to
access it an exception is raised
if you observe these are not any syntax
or semantics errors but arise due to
situation out of the developers control
for example the programmer would never
know a server's downtime beforehand but
blaming your code failure on
environmental issues is not a solution
you need robust programming which takes
care of exceptional situations such code
is known as exception handlers in our
example good exception handling would be
when the server is down connect to the
backup server or mirror server to its
LeMat this enter your code to connect to
the server you will check if the server
is down if yes write the code to connect
to the backup server such organization
of code using if and else loops is not
effective when your code has multiple
exceptions to handle hence Java provides
for inbuilt
exception handling where
normal code goes into the try block and
exception handling code goes into the
catch block try block will contain code
to connect to the server and catch block
will contain the code to connect to the
backup server in case the server is up
the code in the catch block will be
ignored in case the server is down an
exception is raised and the code in the
catch block will be executed