Java Programming | Java Tutorial for Beginners – Step by Step | Java Training | Edureka

Java Programming | Java Tutorial for Beginners – Step by Step | Java Training | Edureka


hello all this is Neel from Edureka
and welcome to this interesting session on Java programming now this session
will help you get started with java from scratch but not only that will also help
you in preparing on some of the key fundamental concepts that are asked in
interviews mostly to do look out for them and hope you have a great learning
experience starting off let’s look at the agenda for the session we will start
off by first discussing about what is variables as well as the various data
types that are present in Java going on from there we’ll be talking about the
various operators as well as conditional statements and loops which are supported
in Java as such in the last half of the session we’ll be talking about functions
as well as classes and objects which are key important concepts with any of the
programming languages and we’ll look at how it works out in Java as such so
without wasting any time let’s move forward to the first topic of the
session which is variables now weibull’s are nothing more basically than a
reserved memory location to store any value that you want to use further as
part of your program as such this in turn means that every time that you wish
to create a variable you need to allocate a specific memory to it as well
now if you look at the statements to the left let’s not look at it in terms of a
syntax what I want to do is that I want to use three values as part of my
program I only use 25 I wanna use three point one four two eight five seven and
I wanna use true as well in this case what I would do is that I would create a
variable that would store each of these values first I’m gonna create X which is
going to store 25 Y which is going to store three point one four two eight
five seven and B which is going to store true these in turn will get memory
allocated to them and in turn this will also be a way for me to reference them
now there’s two ways I can access the values that are present here I can
either go by the memory address or I can go by the rename of the variable as such
so variable name always becomes an alias as before we go in deep with respect to
the different types of variables that are present in Java let’s actually take
a step back and let’s try to understand what is the difference between a process
and a program for that matter now whenever you write a set of codes it
basically is going to be combined together to form a program as such
programs are usually stored on our secondary memory like our hard disk and
executed whenever needed running instance of a program is always
referred to as a process and a process mostly works on your primary memory like
wrap so in short you can say when a process is created the program gets
memory allocated to it as well but what happens in the memory so memory can be
again segmented into two regions which is stack and he these are actually
nothing more than names that are given to the memory segments as such now let’s
say I create a primitive variable now again there are two types of variables
that you need to always look out for primitive variable and reference
variable for that matter now if I’m using a primitive variable let’s say I
am creating int I here okay now don’t go by what is it we’ll be talking about it
little later it basically is a data type for now just
remember it’s how you create a variable for that fact now if I say int I or
let’s take a little more realistic scenario let’s say I am taking someone’s
mobile number let’s say I’m going to declare in phone number then
correspondingly what happens is that memory gets allocated from the stack
regions to this phone number variable as well and this is about four bytes of
memory now we’ll be talking about the standard memory allocations also going
further but just get this idea in your head now anytime that I want to access
the values that are stored here I can either go by the memory address or I can
go by the variable name that I am going to be using which is for number for that
matter now coming to the second type which is a reference type reference type
can be your strings which is basically a collection of various characters or it
can be an object of a class as well now not going into the details as such let’s
take a real-world example let’s say I want to take the address of someone so
what happens is that the address cannot always be fixed to a cost yes I can keep
a maximum limit for it but it idealistically does not seem right for
me to do that as well so let’s say I’m going to create a strings say address
here it becomes a reference variable now what do you mean by that is that it
takes a variable size for that fact now you cannot decide the size of a string
so it means that string address here is a reference of a string type okay which
in turn can actually hold a string of various values for that fact whenever
you’re going to assign a value to the address let’s say I want to write a
Drakkar unit five zero one you’re 66 then what would happen is that
the value that I provide would be stored in heap and there would be a
corresponding reference variable which is my address being stored in the stack
so every time I wish to pull the information I would go to the stack I
would check the string and then I would correspondingly take it up as well now
this is a very important understanding and usually this is something that is
always asked in any to you whether you understand the difference between a
stack and a heap and when do you use a stack when do you use a heap as well
some of the times they do ask you a difference between a primitive variable
and a reference variable as well so I hope you guys are clear with this moving
on with this let’s talk about the different data types that are supported
by Java now what is the data type basically it’s a means through which I
can classify these variables now why do I want to classify them as well because
we will be using these variables for some future operations as such now if I
use a character for addition that does not make any sense there’s no point in
me adding a plus B unless a and we actually store some values in turn okay
now if I just use the alphabet a and I add it to alphabet B then that is not a
valid operation for that fact as per and when I use addition with respect to
characters it’s a totally different sense as well so classification is a
very important part of the variable system in any programming language and
that’s done through the datatypes associated to the variables as well now
if you look at here I am using three variables here and each of them belong
to a different type now 25 which basically is a whole number belongs to
the class of integers which is why I write int X is equal to 25 same I have Y
is equal to 3 point 1 4 2 8 5 7 so there’s a decimal point value so I’m
going to be using a floating point variable or I’m going to just specify
float here finally B is going to store true so I know it’s either going to be
true or false so I can go with a boolean data type as well so let’s actually move
forward and look at some of the most basic data types that are supported by
Java there are mainly four different types of data types which are present in
Java you have integer you have float you have character and you have William
apart from this there are going to be user-defined data types which will be
saying later sessions as well so just make sure
that you understand these four because we’ll be going into them one by one
let’s start with integer as I said integer is used to store whole numbers
now again in integer they can be classified into four different types
I have byte I have shot I have int and I have lock why do I need to you have so
many different types mainly this is where your memory management concept
also comes into picture as such now on a short run definitely does not make a
difference for me to use either of them but when you want to write optimal and
long code for your programs then this does make a difference because memory
management in itself also this essential factor for defining how fast your
program executes because even when you look at a basic level your primitive
data types perform much faster than your reference data type as well so again
memory management is a key factor if an application takes too much memory if
you’re not run if it requires too much storage memory as well then again that
might be another challenge as well so again these are some of the key factors
that you always need to keep in mind when you want to write real optimal
programs as such now talking about each one of them a byte can actually store
any value that is between minus 128 to +1 287 now as the name suggests it can
take one byte of memory as well now when I come down to Shabbat short actually
can store from minus 32,768 to Plus 32767 again this is a standard range
that has been defined and for integer it starts from 2 billion 147 million four
hundred and eighty three thousand six hundred and forty eight to two billion
147 million four hundred and eighty three thousand six hundred and
forty-seven again with respect to long it’s even further as such so the greater
the number is the more memory it would take and the corresponding datatype
would also be assigned by default if you’re using a whole number it is
assigned to the integer type as such now if you want to make a code more optimal
then you can go with short or by depending on the number itself again
byte as I said takes one byte short takes about two bytes in takes four
bytes and long takes eight bytes of memory as such next data type is your
floating date arrived so again these are you
to store numerical values along with the decimal point of fractional point values
as such then there are two types of floating variables present here you have
float and you have tower so again the precision is what makes a difference
here and by default it’s always double and if you look at the data type your
float takes four bytes and double takes eight bytes of memory as such moving
forward you have character datatypes characters are usually stored too
similar to your character values these can be alphabet these can also be
numerical values this can also be symbols for that matter as well okay so
everything that you can see on your keyboard can in turn be represented
using a single character for that matter now again a character data is usually
about a 16-bit Unicode character so as I said a 16-bit again translates to
roughly two bytes of memory as such so the range for a character idealistically
starts from 0 and goes all the way up to 65535 if you want to store a numeric
value as such the only difference that you might see between a character value
and the short data type is that here you cannot store negative values but in
short you can go with the negative values as such now finally you have
boolean data type and boolean as the name suggests would either stick to true
or false and is usually used as a flag to check condition statements and as you
might have assumed a boolean usually takes just one byte of memory for that
matter now enough of theory let’s actually try to understand all these
with an example and I’ll be using eclipse ID for this matter now let me
give you a heads up I’ve already set up Java 9 on my system and I have also
setup eclipse on my machine now eclipse is an IDE that I prefer with respect to
writing codes in Java but you can have different preferences as well there are
a lot of professionals who like to write their codes on the console itself but
again my recommendation is that if you are starting off with a programming
language it’s better that you start off with an ID because there’s a lot of
support and help that comes with respect to it
so we’ll be looking at each one of them I also on a small level so let me go
back to my Eclipse and let me show you how to start by creating a new project
and let’s also start with our codes now this is my Eclipse environment let’s
first begin by creating a new Java project so you see the new option
present here and just click on Java project
now you need to name your project so let me call it Java programming for the
session and once you’ve done with that if you’ve
set up your environment make sure you choose the correct environment now as I
said I have setup Java 9 on my machine so I’m going to be Java SE 9 and once
I’ve done with this I’m just gonna click on finish and automatically my Java
project has been created if you expand this you can already find two entries
present here one is the GRE system libraries and the source folder now
click on the source folder and select new option under which click on class
option now everything that you write in Java is part of a class so he will be
starting by creating a class called hello which is the first program that
you would be writing as part of this apart from this make sure that he click
on public static void main because it automatically creates a main function
for you now in terms of execution always the execution starts from the main
function so this is something that you need to remember while you’re writing
programs now let’s start with the most fundamental program that you would be
writing on any programming language which is hell over now in order to print
anything on Java you need to write the following command which is system dot
out dot println now one shortcut for that on Eclipse is that just write this
out and press ctrl + space this in turn will expand it and you will get the
complete syntax present here now I just specify hello world here which has to be
printed and in order to run it you have the run option present here so just
click on run and it will ask me save and launch option so at once I click on OK
automatically as you can see here the result is also out so you have
successfully executed your first program now let’s leave this aside let me just
remove this now in order to create a variable as we have discussed you need
to start by specifying the data type so I’m going to create an integer variable
let’s say num1 and let’s say if i don’t want to initialize its value at this
point i’ll just put a semicolon here so one thing that’s important with Java is
that you need to make sure your indentation and semicolons are always
right so if you want to keep your indentation right ctrl shift F all to
matically it does that for you now apart from this let’s say if you want to
initialize this value num1 equal to 100 this is just an initialization that I
have done same thing can also be I treated and it can also be done in one
single step where I remove this and while I’m declaring the variable itself
I can signed a value to it so I know that no
man should have hundred so I can do this as well
now let’s say if you want to create a variable of flow time so float FLT 1 :
I’ll create one of double as well dbl let’s say character so it’s up to
you how we want to create I’ll also create a boolean one
I’ve painted five different variables of different data types as well now again
if you want to print any of the variables to identify the value just use
system dot out dot println and specify which value do you want to print now at
this point I have initialized only num1 okay so when I print num1 then
automatically you can see it’s going to give me a value of 100 but to those of
you who are coming from a different programming background like C or C++ you
must be aware that every time a variable is declared that they are given a
garbage value as such so let’s see if that’s the same with Java as such so I’m
going to replace this I’m going to print if the floating variable that have
declared now one good advantage of an IDE like eclipse is that it already
tells you that there’s an error present here it says local variable FLT one may
not have been initialized but still let me try running this when I try running
this this also an error that says there is an existing error with the project do
you want to still continue with the execution and click on proceed and you
can see it has compiled and given me the following error that the variable
effective 1 is not initialized so this is one good advantage so let’s say if
you’re going on a console and writing the same code then what happens is that
you would directly get but you would only get the compile time error that
happens so on an ID it’s slightly easier with respect to that same where when you
write the syntax itself it identifies the errors that are present so small
issues like errors or semicolons can always be avoided for that matter now if
I had initialized value to FLT 1 then it might have printed this but let’s try
that as well so let’s say if I do FLT 1 and equal to let’s give it a value of 13
point 1 4 5 and I just place semicolon here ok I’m still getting an error do
you know why this is this is because of the default data type that has been set
for floating point variables now if you go on top of the error what it’s going
to tell you is that it’s a type mismatch cannot convert from double to float so
as I said any decimal pointed value by default is considered to be of a type
double here so if you wish to make converted to float you can either put in
F here okay which will automatically solve this issue or they are
the way around is to specify the type that you want to convert before it if I
put upper anthesis here and I say float then the issue also gets resolved so
this is a process called typecasting not to understand this let’s go back to our
slides and let me give you an idea with respect to that same now typecasting
basically is an operation done to provide more memory or reduce the memory
usage by the variables as such now this also helps you to keep a standardization
with respect to that same so let’s say if I’m trying to store a large value in
a variable which cannot be stored automatically the Machine identifies
this and promotes this which is known as Blizzard casting or implicit promotion
now if you look at the diagram here you can see how the implicit promotion
happens a byte can be converted to short which can in turn be converted to int
character also can be directly converted to integer values as well because these
occupy more memory thereby enabling you to convert int to long long then again
can be converted to float and finally double because it takes the maximum size
now what I have done here is that I have specified to convert float to double as
well now let’s try something more interesting let’s leave this aside let
me create a variable of type long okay long let’s say num2
equal to 200 for this matter okay now let’s say I want to update the value of
num1 none equal 2 num1 plus num2 now what you need
to understand is that this is not wrong in terms of mathematical expression
because always the expression to the right is first computed and then stored
into the variable on the left okay now if I put a semicolon here there is still
an error you want to guess why this is because the system has automatically
promoted num1 which is used here for addition to type long ok and what are
you trying to do here you’re going to add two numbers of long type and then
store it inside an integer value now if the same thing if I put it inside a
parenthesis and I specify that it has to be converted to integer type before
being stored on the num1 variable they the error gets resolved as you can see
the numbers are getting added and then stored inside the variable number okay
this is something that is quite interesting and it’s also important in
terms of an interview perspective as well till here we’ve talked about
variables the different types of variables we’ve talked about different
types of memories we’ve talked about data types we’ve talked about
typecasting as well so these are the key concepts that you need to remember and
you need to be strong when you’re talking about fundamentals of Java now
let’s try something interesting let’s look at an example of implicit
typecasting itself so let’s say for ch1 I’m going to assign the value of the
character smally okay and now what I’m going to do is that I’m going to give
num1 the same value as see hatch okay if I put a semicolon here you may notice
that there is no error because we had seen the hierarchy earlier we had seen
that characters can be converted to integers but is this a write operation
so let’s actually see this through the example which is so let me print CH here
as well and let me also print num1 here okay and I’ll just save this and let me
just run this now you can see here although it is printing CH as a but when
I’m trying to print num1 which is having the same value as CH it’s giving me the
output of 97 can you guess why this is happening this is mainly because when
you’re converting it from character to integer it is taking the ASCII value of
the character now each character or symbol that we use has a corresponding
ASCII value and that is what is actually being converted and stored in an integer
variable for that matter let’s try another example let’s say I’m going to
declare another variable let’s say I’m going to create another variable CH 1
and I’m going to assign the value while it’s being created I’ll assign it I okay
so I’ve created a variable CH 1 and I’ve assigned it the value of I same let me
go on to create a third variable let’s say car c2 is equal to
try adding these values CH plus CH one okay put a semicolon here and you can
see there’s already an error that showing me what it’s trying to tell me
is that I cannot convert into cap so automatically it has promoted it to a
character again this is something that can be solved by typecasting so if I’ve
converted to character then the issue gets resolved here so as you can see
there is no issue here and if I try to print c2 here then something interesting
would come out from this let me save this and let’s try to run this as you
can see here it’s giving me totally different character here it’s just added
the integer value of a and small I it’s done that by taking the air ASCII values
and then reconverted it back to a character which is what you’re seeing on
the screen at the moment so this is something interesting because this is
sort of an example that you would see with typecasting as well now let’s take
something interesting let’s try something different let me just go on to
clear all this okay I’ll just clear this these
statements as well I’m going to go on to create a variable of type byte which is
the smallest integer type variable that you see right I’ll call it B I’ll assign
it a value of let’s say 100 any issues here no Rach what if I add another zero
here then you can see it’s already giving me an error that says type
mismatch converting from in to bind it’s already identified this value to go
beyond a byte and it’s by default taking it to be an integer variable as well now
let me reduce this I’ll make it just there and I’ll perform a multiplication
operation here B is equal to B star B for a semicolon here and again there’s
an issue now if you notice I’m just multiplying 10 into 10 again this is a
byte value that is being multiplied which is going to give me a result of
100 but it’s also giving me an error that type mismatch has occurred from int
to bad this is mainly because of a concept or a phenomenon known as type
promotion so let me talk about my promotion as well because this is also
another important concept with respect to Java program now there are merely
four rules that are followed in case of pi promotion and this is something that
really makes you admire of how smart the java virtual machine is now by default
characters do get converted to int a byte can be converted to short then into
the long float and double as ba now all byte and short values by default are
going to be promoted to in for that matter and if one operand of the entire
expression is long then the entire expression is considered to be long
if one operand of the entire expression is float then again it’s completely four
and if one of the operands is actually double then the result also is going to
be double for that matter now if you look at our case what is happening is
that byte is getting promoted to integer so integer and integer is going to give
me an integer value which is going to be stored in a byte format so if I just put
byte here and perform typecasting then it’s perfectly tied
if you print be here then you’re getting the answer to be 100 as well so this is
something that’s quite interesting and definitely should be aware of with your
interviews as well so typecasting anti promotions are some of the key
fundamental concepts to look out for now coming back to our presentation let’s
move on and talk about the different operators which are present in Java
before then let’s talk about what is an operator now operator basically are
constructs or symbols which help you manipulate the values stored in a
variable or operands for that matter what is an operand anything that you
wish to operate on okay there are four different types of operators which are
present in Java you have our thematic operators relational operators unary
operators and logical operators let’s look at them one by one first comes
arithmetic operators ultimately competent errors are quite similar to
your standard operations like addition subtraction multiplication and to those
of you are extremely new dual programming language we have a concept
of modelers present here now like in a normal division wherein you
perform a division and you get the quotient as the answer in modulus
division what happens is instead of a quotient you get the reminder as the
output for this matter now when you talk about relational operators you have
equal to not equal to greater than less than greater than equal to and not equal
to EE equal to is always used to compare now relational operators mainly are used
in condition statements which we’ll be discussing further and usually I
something that I used to check the relation present between the two
operands for that matter then you have unary operators now unary operators or
something of my favorite and is something that’s always a tricky
question for that matter now unary operators are basically of two types
here you are just working on a single operand and there can only be two
operations that you can perform either you increase the value or you decrease
the value and the increase and decrease is by a value of 1 now when does the
decrease or decrease happen either I perform an increase before I go on to do
any other operation which is pre increment or I perform the operation I
want and then I increment the value that is needed so let’s take an example to
understand this let me write it down for you here let’s
say I have a variable called I okay now I’m going to define an expression that
says I plus 1 so this is my standard expression okay now if I perform plus
plus I okay and this is an unary operation and then I add 1 to it and if
I perform I plus and what so these two are not going to
give me the same answer but different answers now in this case let’s say I
assume the value of I to be two okay in the first operation the answer is
actually going to be four now what is happening is that first I am going to
increment the value of I which is what pre-increment does I’ll increment it
then I will perform the operation so I’ll increment the value from two to
three then to that I’ll add one in the second case what happens is I take the
present value of two then I’ll perform the operation after the operation is
complete I will increment the value of I so the result of the second one would be
three instead of four saying with case of bickerman
you either decrement before the operation starts or decrement after the
operation is complete let’s try to understand this with an interesting
example let me go back to my Eclipse let me clear all this let’s say int um equal
to five okay so I’m just declaring a variable called num and I’ll also create
in answer which is going to be equal to plus plus num plus num num plus plus
plus num plus plus okay so I’m performing a
pre increment a post increment and a pre increment adding all of them and then
printing the answer okay now I’ll print two things let me first print the value
of num the value of num and I’ll also print the
value of the answer as well okay first let’s try to understand what is the
value of num at any point okay now let me put this in comments so that
you can understand better single line comments can always be used with double
backslashes and this is one of the best practices to use always make sure you
have good readability with your code and you are commenting in your code as well
because although you may be writing the code today tomorrow if anyone wishes to
read the code or get an understanding from the same without comments it might
be quite hard for them to get a complete idea as well now what is going to be the
value of num here okay I’ve defined the value of num at the start okay now what
I’m going to do is that I’m going to update the value because I’m performing
a pre increment so five becomes six then to this I am what I’m going to do is
that I’m going to perform a post increment operation so the value remains
six itself which will get updated after this and then I’m going to perform
another pre increment so what is happening here is that the value is
taken as six and then the value gets updated so here I have seven and finally
there’s also one more update that gets added so six plus six becomes 12 plus
seven which becomes 19 so let me just run this and as you can see the answer
is 19 and after this the value of num finally becomes eight because I have one
last post increment I hope you guys have got a good understanding of pre
increment and post increment as well now let’s go back to our presentation and
let’s talk about the last type of operators which is your logical
operators now again there are three types of logical operator you have
logical and logical not and logical or now logical not our is the easiest of
all to understand that is if a value is true then logical not converts it to
false so it basically just flips the value with respect to that same when you
come down to logical and here what happens is it will return the value of a
if the value of a is assumed to be false otherwise it will return the value of P
now logical or is actually quite opposite of this it will return the
value of B if B is false otherwise it will return the value of a now although
it might seems quite complicated when we talk about conditional statements and
loop statements you might get a better understanding of that C now let’s move
on and talk about conditional statements and we’ll be talking about the first
conditional statement which is an if statement
now if statement is quite straightforward and easy to understand
that is if and certain expression is true then execute a set of statements
which are present inside it now if you look at the flow as well okay you start
off your operation and then you go into the if condition statement if it is
found to be true if the specific expression is true then what will happen
is any cord mentioned inside this branch would get executed if not this code get
skipped but what if I have more than one condition what will you do in such cases
then you have your else if condition so else if actually lets me write multiple
conditions that needs to be evaluated so if my first condition is not true then
it will go and check the next condition again if it is found to be false then it
will not execute now if I have multiple conditions then I can always have a
ladder of if else if situation wherein I am validating all the conditions now
there will also be operations where you would need to perform some set of
operations or some set of statements if none of the statements are true then you
would go on to execute the else step now in order to help you understand this
let’s look at it with an example for that matter now in order to help you
understand I have already written a sample code present here so what I’m
trying to do here is that I am trying to assess what are the number of digits
that are present in a number that I am passing so what happens is that I am
defining a value of a number equal to 25,000 okay then I am writing my nested
condition so this is how you represent an and operation in Java okay so first I
am checking if the number is less than 100 and if it is greater than 10 so only
and only if both of them are true will it enter this condition that’s how your
logical and works now unless and until the both the values are true you would
not get a true value for this expression and you would not execute the following
sequence but whereas in case of your logical odd
what happens is if either one of the conditions are true it will give you an
output of true which will in turn enter the treatments that are present inside
now here I am using logical and because a two digit number falls in this range
okay it starts from 10 and goes on all the
way till 99 so this is the range that I have defined if it is in this range then
it is a two-digit if it is greater than 100 but less than thousand it’s a three
digit if it’s greater than thousand and less than 10000 greater than or equal to
10000 and less than one lakh it’s a five digit number okay so this is the range I
have defined if it is not falling in any of these categories then I’m going to
say that this number is actually not between 1 and 99 thousand that is it’s
beyond the range that you have specified okay
now let me just run this program and if I click on OK as you can see it’s
telling me it’s a four-digit number so I had just reduced one zero so let me add
two zeros and let’s read on this and you can see it does not follow in
this rate so what we’ve understood here is that we’ve seen how an if-else ladder
being executed as well as I hope you’ve got a simple understanding of how the
logical and operator is also being used now let’s come back and let’s talk about
the next type of conditional statements which is a switch case statement a
switch case is quite similar to your if-else statement the only difference
between an if-else statement and our switch case is that here you actually
know the value which based on which you have to evaluate now in my previous
example I did not know if the number fell in between the range of ten to
hundred one hundred two thousand thousand to ten thousand and ten
thousand to one lakh but when you know the exact value which it can take that’s
when you would actually be using a switch case statement now ideally if you
look at the flow of a switch case statement it’s not quite different it’s
just little more structure you start off by switching into the expression and
then you check if it’s the first value second value third value or fourth value
if it’s none of the values then you reach the default State now you default
cases are very much similar to your L statement okay now if a value is matched
then the corresponding statement is written and then you break out from the
sequence of operation now break is something that’s quite important as part
of a switch case statement so let me just give you an example and help you
understand let me go back to my Eclipse and show you the code so again to make
it easy for you to understand I’ve already written a code here and what
I’ve done here is that I have defined the value of day equal to four and then
based on the value that I want I would correspondingly be creating the
different cases now I know that these are start from one and goes all the way
till seven for a week now in this case if it’s any value beyond that I know
it’s an email it day as well now if you can see here my week starts with Sunday
Monday Tuesday Wednesday Thursday Friday and Saturday let’s just run this
now as you can see the value that is getting printed is Wednesday and if you
check here it’s for K is for now what would happen if I remove break statement
from here let me remove break statements from all the consecutive cases that are
present okay now I am renewed break statement from here and let me just read
out this now if you notice what is happening here is that every
corresponding value or every corresponding case which is present
after the required value gets executed if break is not present so this is
something that you need to be careful about while you are working with switch
case statements for that matter so let me come back and let’s move on to the
next interesting topic which I like the most is loops loops are basically those
statements which actually help you execute same set of statements multiple
number of times now if I want to perform one continuous operation of addition
five times then other than writing into five times I would just put it inside
the loop helps me execute a set of statements multiple number of times now
in Java there are mainly three types of loop you have a do-while a vile and a
for loop but before we talk about them let’s just look at a little flow of a
loop statement you always start then you go on to check the condition of the loop
if it is found to be true then what you do is that you execute all the sequence
or the statements that are present inside it from there you go on to check
back the condition and again if it’s found to be true you’re going to keep
repeating for the same unless and until your condition is not found to be false
you do not exit from that loop once you’ve done that then you go on to the
next set of statements which are present now let’s talk about one by one let’s
start with a do-while to a do I loop again is one of the most basic
statements but it’s slightly different from your loops this is called an exit
control loop here instead of checking the expression first and then executing
the statement it’s after you execute the statements that we check the condition
so let’s just look at the flow to get a better understanding you start off with
the operation you enter into the do sequence and then you execute the block
once you execute it you reach the while condition where you check the condition
for that matter if it is false then you exit from that loop but if it is true
go on to repeat it now one thing that you need to understand is that a
do-while loop is used in situations where I need to execute the statements
at least watts so the minimum number of execution of the statements present
inside the loop would be at least once now let’s look at an example to
understand do-while loop for that matter let me create a new class file and let’s
begin with a new value okay so what am i go
so let’s say I want to add all the first 100 numbers which are present so I’m
going to create an int num2 let’s say what okay so from 1 200 and I’m also
going to create another variable called sup okay now I’m going to write a
do-while now inside this let’s say sum is equal to sum
plus numb okay now I don’t want to write this I want to reduce my code length so
in this case what I’m going to do is that I’m going to remove this entire
process and I am going to write plus equal to numb so this is a shorthand
writing okay so this in turn is equal to sum is equal to sum plus now okay so
I’ve just reduced the entire operation has quite fast for that matter while now
I want to write the while statement so let’s say while my num is less than or
equal to hundred okay but I need to again increment the value of nob
so for that what I’m going to do I’m going to go back into the loop and I’m
going to use one of my favorite or interesting operator which is the unary
operator num plus plus so every time this value has to get incremented so
once this is done I’m going to use this out
and I wanna print the value of the sub all right well I’m good now for just
clarification as this initialize it as zero and let’s begin executing this so you can see the some of the first
hundred numbers is 550 okay now this is just one way of doing this now the same
can be danced slightly easier when you look at the next loop statement that
we’re going to be talking about which is the while loop for this matter now a
while you basically it repeats same set of operations but the major difference
between a do-while and a while loop is that here you actually check the
condition before you enter into the sequence or if before you execute the
statements so you start off then you go on to check the condition if it is false
you exit from the loop if it is true you execute the block and then go on to
check the condition till it’s found false let me come here let me reduce
this entire process okay let me remove this let me make it as a while loop
while okay now in this case what I’m going to do is that I am gonna change
the value of num from one to hundred okay and while num is greater than or
equal to 1 in this case perform this operation but not on an increment level
but on a decrement level that is keep decrementing the value till you get the
answer so what is how going to happen is that it will come into the loop first
you will see the value of num is equal to hundred can you go into it it will
add from hundred then it will reduce the value to 99 it’s going to go back and
it’s going to keep checking the same so again this seems a little more apt for
the sequence that I have mentioned so this run this and the answer remains the
same it’s just that I have taken a different approach to solve the same
problem for that matter now the last kind of loop statements that we’ll be
discussing is the fall now for loop is again something that you use in case
where you know that the number of iterations needed is fixed so let’s say
if I know I need to execute a statement hundred times or ten times for that
matter that’s when I will actually be using a fogging this is what makes it
different compared to the while and do-while loop but on a same level a for
loop is also an entry control loop you only check the condition and then go on
to enter the statements that are present inside so it’s similar to the while loop
but it’s used when you do know the number of iterations required so again
the previous treatment can again be made quite easier but before let’s start off
by understanding how the for loop works you start off with an initialization
step now the syntax for for loop is also slightly different you have three
different elements present here apart from just the expression you have an
initialization you have a condition and then you have an actress initialization
is just to keep a track so that you remember how many times you need to
execute the set of statements condition this for checking the condition and
iteration is to increase the initialized value so that the repetition takes place
as per required once initialization is done I’m going to check the condition if
it is false I’ll exit from the loop if it is true I’ll execute the statement
then I will perform an iteration on the initialized value and I’m going to keep
repeating the same so this is going to execute n number of times with respect
to that same now if the same statement has to be converted into a for loop let
me just remove all this let’s say for int I so I’m already declaring a
variable here equal to zero I less than equal to 100 and I’m going to perform
the iteration here itself I plus plus now inside the loop what I’m going to do
is that I am going to write some plus equal to I okay this is my statement now
this in turn helps me eliminate the need for another variable called num so I’m
just going to remove num as well and if I run the same statement I get the same
answer for that matter so again this is how you can use three different ways to
solve just one simple problem the ideal difference is that you need to
have a clear good understanding of when to use a while loop when to use a do
while loop and meant to use a for loop my suggestion would be is that you
remember what is the purpose of each of the loops you use a do-while loop when
you want to execute the statement at least once and then decide whether to
continue or not a while and a for loop are used when you want to first check
the condition and then decide whether to execute the statement or not a while
loop is used in cases where you’re not sure of the number of iterations and a
for loop is used in situations where you exactly know the number of iterations
required as well is that clear please make sure that you have some clarity
with respect to that same now before we go on and get into the details I just
wanted to show you something interesting that I always loved and helped me
understand loops concept quite interesting there was a song called 99
viewers on the wall so Alaura would be us one of the key interesting things
that Loops helped us understand was to write the lyrics using the for loop
statement so here’s a slightly different version of what you would find on the
Internet now I know there are certain things that you have not been interested
to so let me just show you an example with respect to where I’d leave the rule
is X goes 99 bottles of beer on the wall 1 bottle of beer take it down and pass
it around and it keeps getting reduced as it keeps going on
so you need to count down with respect to that same so I first start off by
initializing the number of beers to be 99 ok and then I define the words to be
bottles so this is how you define a string you specify the type string and
then you use the name of the string the following which the value as well then
what I’m going to do is that I’m gonna use of while loop where the number of
beers are greater than 0 I’m going to check if the total number of beers is
equal if it is one then I would replace it
with water now what I’m going to do here is that I’m going to start by printing
my number of portals so it’s 99 bottles okay then what I’m going to do is that
I’m going to use a plus symbol now a plus symbol here is used for an
operation known as concatenation concatenation basically is used when you
want to join two strings or two words for that matter
now again strings is something that will be extensively discussing on in our
upcoming session so I just wanted to introduce and show you how interesting
this would be when you look at it and get an idea of the loop statements as
well so I’m going to tell the number of beers that are present at the moment I’m
going to add a space between that then what I’m going to do is that I’m going
to use the word bottles okay this will in turn tell me how many bottles are
present on the wall then what I’m going to do is that I’m going to say the
number of bottles on the wall and I’m going to specify these are the number of
bottles of beer then I’m going to say take one down and pass it around so this
basically is telling me that I need to reduce the number of peers by one I can
do either this or I can just write beyond a minus minus so this is two ways
that I can write the same okay now finally when it comes down and I find
that the total number of beers at this point is zero then I’m going to say no
more bottles of beer on the wall that means this is my end so this is how I’m
gonna executed so let me just run this and let me help you understand how this
works out now let me just go up let me just show you this now if you see let’s start from the
first 99 bottles of beer on the wall 99 bottles of beer you take one down and
you pass it around so I have 98 bottles of beer on the wall which is 98 bottles
of beer again I take one and I keep passing it up now this goes all the way
down all the way till I realized that I have taken out my last bottle and I have
passed it at art which lets me know no more bottles of beer on the wall and it
automatically exits as well so this is roughly about 500 lines of output it has
been generated from what I would say let me remove these white line spaces as
well so roughly in about 20 lines of code I
have created a program that gives me about 400 lines of output just using
mainly the logic of loop statements so this is just one interesting example
that I had loved with respect to loops and I usually use for explaining the
loops concepts as well so now let’s move on and talk about functions which is
another interesting concept of Java now again functions basically is a block
of reusable code which actually can be used to perform a single and a related
operation any number of times that you want okay now again functions can be of
two types it can be a predefined function or a user-defined functions as
well now when we talk about predefined functions your mean is a predefined
function where your execution starts from your system dot out dot println is
one of the best example of a predefined function as well now what you see here
is just a function that will help you act so let’s just look at it in Java
okay so this is the same function that I had shown you in the representation
there what I’ve done here is that let me explain the code I have declared two
variables num1 and num2 okay then going on I have created a new
variable called AXA okay and let’s just leave this part out for now okay and
then I’m just printing the answer here now before we go on let me explain here
so this is what you would refer to as a function call and this is your function
definition okay so once I call a function then it automatically goes down
and checks where the function has been defined now it finds that the function
sum has been defined here and then it goes the control moves here before it
executes it’s the next set of operation so what happens first is that a variable
num 1 is created and memory is allocated with and the value 10 stored inside that
same is repeated for num2 where the value 35 the stored and then what is
happening is that I have found a function call so I’m going to go to the
function definition now if you see the function definition then what you can
see is that it takes two values as an input so these are the parameters for
the function now you can have parameterised function or non
parameterize function as well now in this case I am saying that it needs to
take two values as the parameter okay once it’s taken two values I am just
going to create a new variable called solution
and I am going to add these two numbers once it’s added then what I’m going to
do is that I’m going to return this value back to the place where it is
being caught now this is to help you understand the
overall flow so this is where the sequence starts it goes down to the
function definition it executes the function definition and then goes back
to where the function was caught now once it returns here what it’s going to
do is that it is going to assign the value that I have got from solution into
answer once that is done then it’s going to print out the same it’s a very basic
program but I hopefully give you an understanding of how functions work now
if you execute this you can see then solution as the sum of the two numbers
is fortified so let me just summarize what has happened I have created two
variables then I’ve called for the function the control has moved to the
function and once the function operation has been completed which is an addition
it goes back here and it works on now again I’ve already defined two numbers
here but let’s say I have to calculate something more interesting so idealistic
Lee functions are used mostly when you are using a user-defined value or when
you want to perform a same set of operations for a different set of values
as well so this is when you use functions remember there is a key
difference between loops and functions loops gets executed either indefinite
number of times or finite definite number of type but you do not need to
call for that loop execution once the loop execution starts it will keep going
on until it’s completed and then it will move on to next lines of code whereas in
a function every time I call the function the control moves on to the
function definition as such okay now let me help you understand how to write
Fibonacci series using functions in Java okay so I have already returned the
Fibonacci code here so let’s just look at it so what I’m first doing is that I
am globally defining the values of variable n1 number 1 number 2 and number
3 so 0 1 0 is what I am going to follow here ok then I have defined a function
called print Freebo which is going to take the count okay if the count is
greater than 0 then what it is going to do is that it is going to add number one
and number two – and store it inside number 3 ok then
number 1 gets replaced by number 2 number 2 gets replaced by number
so this is the sequence that you always follow with Fibonacci series all right
so in this case what I’m going to do is that I’m going to print only the first
ten values so I’m always going to print number three here okay and this is to
keep track with respect to that same now finally what is going to happen is that
it is going to call the function itself so it’s going to be a recursive function
so a function calling itself is always referred to as a recursive function for
that matter so this is something that is quite interesting with Fibonacci series
and this example for that matter okay so let me show you the mean as well so
in mean what I have defined is that I have defined the count to be texts so I
just want the first 10 so let’s say I want the first 25 numbers of the
Fibonacci series so first I have to print number one and two because I’m
always going to start by printing number three okay so one and two are zero and
one that’s how you’re gonna see series starts and I’m going to pass my count –
– that is my present count – two because inside the loop it’s substracting by one
so let me just execute this and let me just rerun this so as you can see it has
given me the first 25 values of the Fibonacci series and I hope this has
given you an insight on how functions work okay so let’s go back to our
presentation and let’s talk about the final and one of the most interesting
concepts of Java which is classes and objects now to those of you who heard of
object-oriented programming the concept of class an object is not something new
classes and objects have been the core foundation of the object-oriented
concepts now according to the oops there are mainly four things that belong
inside a class a state and attribute a behavior and a method so to define a
class you have to define these four things according to the object-oriented
theory now since we are in Java if you want to create state an attribute inside
a class you have to define available and for behavior and the thoughts will be
creating functions or methods for that matter now let’s first begin by creating
a simple class called car and slowly we’ll be talking about the different
concepts of car and I hope you understand how it works now to help you
understand what I’ve done here is I’ve just created a skeleton of two classes
present in the same file I also have a class called you spa
okay inside which my main is defined but there is nothing returnees out there and
what I’m done is that I have saved it by the name of the class which has my main
function now let me just show you what happens when you compile a java code
which contains multiple classes in order to compile a Java code always
use a command Java C followed by the name of the file now I have only one 5
present here so I can execute this but before that let me just show you the
number of files that are present here so dir actually tells me that there is only
one file present in this location ok now what I’m going to do is that I’m going
to use Java C following which I’ll specify the name of the file and I’m
gonna click on enter so now here let’s just try to see what BIA is giving me it
tells me that there are two class files that have been created here one is of
card.not class and other this user Karnad class okay now if we check the
root folder also as you can see there are three files present here car door
class user car door class and user car Java so user car dot Java was the code
that we had written now the bytecode is created according to the classes now
even if we have two classes it will create two byte code files one for the
car and one for the used car as well now let’s see how we can create objects for
the car class so let me go back to my Eclipse and here what I’ll do is let me
start off let me create a new class let me call it use demo and include mean
as well now before I get into used em myself
let me also create another class demo here
and inside this let’s say I’m going to create a new variable called Val okay
I’ll come back inside my use demo and I will remove this now let me create
something known as an object of the class now objects are nothing but an
instance of a class as well like how do you hire a process being an instance of
the program objects are an instance of a class so how are they different let’s
take the example of cars itself whatever I design with respect to a car ok a car
has to have four wheels a car has to have two headlights a car has to have a
windshield a car usually is driven by one person so a single steering wheel
all these are basic parameters that I can define for a car but when it comes
down to an implementation then what happens is it slightly varies
now a car can have a color but as you can see there are various colors that
are available with respect to cars that are out the tree okay coming in terms of
the wheel thickness coming in terms of the brand that is being developing so a
nadie six will be as much as different from a BMW or an Mercedes S 350 okay so
each one has its unique attribute but end of the day we all refer to them as
cars itself so my cars here becomes my class and each of these vehicles
themselves become an object as well now in order to understand how to define an
object of a class all you need to do is first specify the class to which the
object is going to belong to in this case it’s going to belong to the class
demo then what I’m going to do is that I’m going to create an object so specify
the name of the object obj then use the keyword new now new here is used to
allocate memory for that object okay and finally we’re going to use something
called constructor here which we’ll be talking about in our next sessions while
creating an object if you wish to initialize a value then you use
something called as a constructor by default every class has a constructor so
we’re going to call the default constructor
which goes by the name of the class as well which is demo in this case okay so
once I do this the object is going to get created now if I wish to have a
unique value for an object then what I can do is that specify the object dot
I have valve okay and then what I’m going to do is that I’m going to assign
it a unique value which is nineteen thousand because this is just a rough
value for that car okay I have created an object I have assigned a value for
that as well but the question is how do I access it or how do I make use of it
so what you need to understand here is that demo obj or what you’re seeing the
obj in itself actually is a reference to the class now it means that class Ashley
is a referenced user-defined data type and this in turn means that we can
create reference variables of type class demo
now these in turn are also capable to hold references of the class demo
objects as well now let’s try to access this value now same command that I am
going to use but there’s a slight difference with respect to it now let’s
say the value is now again make sure these are in quotes because if not it
would not get printed now following this put a plus as I said
plus here is for concatenation or joining two strings or values now in
order to access it you cannot directly type by now if I type value it would
tell me there is no variable which is going by the name value now if you see
here it tells me value cannot be resolved into a variable but if I say
obj dot value then it says no Hara this is again because obj here becomes a
reference of the type demo okay this is what I have been trying to explain
earlier now in here if I just execute this then you can see the value is
19,000 as I have defined it as well now let’s actually go back to the most
important question here that is what is an object in Java and how is it created
now let’s go back to the syntax that’s present here what we’ve written here is
demo OPG equal to new demo this statement actually creates the object
for the class demo in the heap region so this is how objects are created now what
if I just write this statement I remove demo dot obj and I just write new dep
okay now what happens here is that it creates an object which returns the
object reference and it is captured by the obj which in turn is the object
reference as well so if I do not specify this then it does not have a reference
but now this statement in itself is also known as anonymous object creation okay
a class is used for code organization now what you need to understand this the
more I want to bring structure into my code the more I am going to break it
down the more I’m gonna introduce newer concepts I’m going to use
functionalities and the hosters was the best example for code organization now
if you actually look at the structure inside a class we can create variables
as well as methods inside them now removal methods or functions in
themselves cannot be outside the class because as we know Java is a language
where everything needs to be inside a class but then a class in itself is also
existing inside a container known as package so for variables and functions
we have a container which is class and for classes we have a bigger container
which is a package which in turn is actually stored as a folder in your
system okay now if you look at the example here you can see that I have
various classes created but they are all present inside a specific package called
default package now I’m not named this if I want I can name this as well as for
my requirement assets so a collection of all these classes will in turn be in a
folder called a package now I can also have various packages present inside a
package as well depending on my requirement now ideally this is the
hierarchy that you would be following in a project as well
wherein you would be working with multiple variables which in turn will
work with multiple functions which will be present in multiple classes again
these classes will be inside packages and packages themselves will be working
hand-in-hand with each other as well quite fascinating right that’s the
interesting part of Java now move more forward let’s actually look at how
accesses to these classes can be specified that is what exactly is the
axis for a class and from where is it accessible in Java who can access it and
how can it be accessed as well now when you talk about the access specifier for
a class there are mainly two types of access specifier first is before now as
you can see there is no keyword that is present here you don’t need to write
anything as such it’s understood that is d4
okay let’s look at the example of class demo itself this is a class that is of
the type default but what you need to understand is that this class demo is
actually accessible only inside the package in which it is defined and not
outside this the second and the last type of access that is present with
respect to classes is public access now this axis with respect to class provides
access to the class all within the package as well as outside as far now
although this is very interesting and useful there is only one restriction
with respect to public access now let me go back to my previous example let’s
take the same used car okay let me just open this in a notepad now if you see
here I have class car I have class use car as well now I have not defined
anything with respect to that sink now let’s say if I make this public
then and if I try to compile this will let’s see what happens now as you can see there’s already an
error that tells me that it should be declared as the filename car Java okay
so this is one of the first and most essential mistake that has happening now
as per this rule that whichever class is public in that file you should save the
name of the file with the name of the class which holds public with respect
now one more thing that idly is recommended while you’re going with
respect to programming in multiple classes is that the class which contains
the main function should always be the public class as well this is because
main function is where the execution starts and that is one place that has to
be public as well you might be wondering why is this needed why do I actually
need to name only one class as public as well as I need to have the name of the
file as the public class now what you need to understand is that although on a
small level while you’re working with one or two programs this may not seem as
a problem but when you’re working on an organizational level let’s say you’re
working on a very huge project okay Java in itself follows a rad model now here
what happens is you have to make a lot of classes while you’re working on a big
time project as well now let’s say I’m taking a class which is designed by John
okay now inside if the rule was not present one of the first things that you
would be noticing is that there are multiple classes present let’s say I
have ABCD efg classes present now if I’m searching through the source code now
this becomes a challenge as well and even in the folder it’s being stored as
my dot Java as well so this does not give me any clarity with respect to
which is the main function which can be accessed and it becomes a problem as
well since it has multiple public functions as such so Java in itself has
bought a restriction in JVM that the file name and the class name should be
the same and this in turn is the code organization principle now let’s look at
the access rules for the class members which are present by default there are
four different accesses that are associated with class members those
members which are private can be accessed only within the class and
cannot cross the class boundary as well second you have d4 with
the class these variables can be accessed as well as when you bring in
the concept of inheritance even the child class can actually access these
variables as well second you have default default helps you to access
every variable that is off default type within the class as well as any child
class that is part of the same package as well in which it is defined so let’s
say I have a package called package 1 inside which I am defining index and
this is off a type default I have class c1 and child class c2 as well so X in
turn will be accessible in child class c2 also because it’s been defined in
class c-1 as such ok so again what you need to understand is those variables
which are part of the same package if they belong to default they can be
accessed without a problem by any child class part of the same package as well
now let’s say you want to access the member outside the class then this can
be done by an object reference but it needs to be within the same package in
which it is defined so anything in class let’s go back to the same example I have
a function that is present inside class c1 and if I want to call that function
in my child class c2 then I can do that by using an object reference provided
they both are in the same package as well so third you have protected now
protected is an evolved version of before using protected the members can
actually be accessed by a child class which is also present in a different
package provided it is doing the same using an object reference so let’s say I
have a child class c3 which is present in package 2 which is the child class of
c1 okay now if I have an object reference then I can call any protected
member that is present in class c1 4th and finally you have public again this
gives you complete access for you to access these variables
now by default it’s always recommended that you do not keep any variable public
because it becomes openly accessible as well now in order to help you understand
what I have discussed here better let’s actually go back to my Eclipse and let’s
try to understand now in order to provide protected access to any variable
it’s not very hard all you need to write is protected
okay and automatically the variable becomes protected in nature okay so if
you go over it you can actually find it is of protected nature as well now let’s
try to look at an example where I’m going to comment it this up now what I’m
doing here is that I am NOT giving an initial value to my object reference
okay now if you noticed earlier we had gotten an error okay earlier when we
were using a variable you had to initialize it but let’s test this out
and let’s see what happens as you can see here the value is zero now what JVM
has done is that it has set a rule that whenever a variable is declared in a
class then JVM automatically initializes these variables with a default value
while it’s creating an object now these default values have already been fixed
that is they’re already set in the system for each of the data types now
let’s see in case of other variables let me add double D Val let me add a boolean
B well let me also give a character
see well okay so what I’m just doing is that I’m just declaring these variables
as part of the class now let me just copy this up
okay so I’m going to print the double value the boolean value and the
character value as well so let me just save this and let’s run this now you can
see by default for a double it is zero point zero four boolean it is false and
for character it’s a single white space that has been stored as well now it’s
very important for any interview that you understand how we can create methods
inside a class and the syntax as well with respect to that now first and the
most important is the access specifier and the return type then the name of the
function as well as the parameters same like how we had done in case of a
function now here we had specified the access specifier now I had not come on
this earlier because I didn’t want to confuse you guys so by default my sum
function was public okay then I’m going to specify the return type okay so now
it’s off the return type integer this is also has been specified now let’s go
back and let’s now again in case of your access specifiers what you can do is
these can also be public if you do not specify anything it will be default you
can also keep them protected and even private as well as for your requirement
again as we had explained earlier once function is caught then you will want to
find the definition you execute it and then you go back to the caller once you
successfully executed it as well now here one important factor is that if you
need to understand there is a function call that is maintained and it’s in the
call stack internally let’s say I have 450 a has called BP has called CC has
called e then after you finished B it reaches to C then C gets executed
reaches to B and B gets executed finally comes to it now let’s actually see how
this is done with a dev know if you look at our operation in itself there is
always a first function that gets called that is your main function so this is my
entry point and this is always the first function that gets executed as well now
if I come down here let’s say I am going to create a new class here what I will
do is that I will remove the sum function from here and I’ll put it
inside a new class as well let me just modify this to help you understand so I
have a hope you guys have understood this function I’ll bring my function here I’ll just
remove this I just keep it what that is it’s not going to return anything now I
just remove the values that it is taking as well so it’s not a parametrized
function and what I’m going to do is that I’m going to define num1 coma
I’m to here let’s say I’ll say num 1 equal to 192 is equal to 1 0 9 my answer
my solution is also going to change it is going to be num1 plus num2
now instead of returning this value I just copied this I will remove from here
and I’ll put it inside the sum function itself ok so what I’ve done is that I’ve
just modified my previous function to add two up to class system wherein I am
going to define one more let’s say this is a function that is going to return a
value in some one and I am going to start defining this I just copy these
two lines and I’ll make sure this answer is returned ok and
shift F actually formats it so that’s a very useful code in this case now if you
come down to my main now what I start off is let me remove this entire process
so let me begin by creating an object reference to my function class function
obj again this is an object reference equal to use the new keyword and then
the constructor as I had mentioned so let’s begin by calling the some
functions obj dot some and obj dot someone now this in turn actually is how
you make use of methods in a reusable environment and it should have a better
design as well with respect to that safe now one thing that you might notice here
is that even though of the object is returning a value present in someone
it’s not throwing me an error at this point as well so this is something
that’s quite interesting with respect to memory management as well but when we
talk about memory management the first question that actually comes to your
mind or that should come to your mind is that does a function actually take any
memory so we actually discussed that a class has two members one for member
variables and second for functions so we know if we create the class then we can
also create the class members also so let’s actually see when they are
actually created and they come into memory or when have they actually
allocated memory so that we can use it so let’s see when they are available so
when we create a variable it gets memory when the object for that class has been
created for accessing them we require the object reference so it uses or
fetches it and you get the object reference for every object there is a
separate copy of member variable present in the memory that is if we create ten
objects then ten copies will be created for each and every variable that is
present as part of the class and when we talk about functions they come into
memory when the class is actually initialized in the memory when class is
initialized only then do they get memory allocation now the only difference
between functions and member variables and objects for that matter is that when
they actually come into there is only one copy of the function
that is stored in memory and every variable or object in turn is going to
access this same copy of the function present the memory itself now again if
you wish to access these functions that are present in the memory you need to go
back to your object references as well now let’s take another example to help
you understand how this is so let me come back to this program okay so I have
a class called car inside which I have defined price I’ve also defined a
function called show price which I’m not using at the moment okay I have a public
class called used cars and I have a main function present inside that here what
I’m doing is that I’m creating an object of the class car and I’m setting the
price equal to thousand now I am directly predict this although this is
not wrong for me to do that what you need to understand is that we want this
output to be printed by the function in itself because we’ve already learned the
rule that members having before it access specified can the access within
class anywhere so what I will do is I’ll just modify this code I will change this
print statement from here I’ll cut it out I’ll go inside the member function
and as this print price but instead of the object reference I just directly
print price okay so this is not at all wrong now in order to make sure that
this is going to be printed I need the object reference obj dot show price but
there is one more problem that member variables come in memory when object is
actually created and when we have to use them we require an object reference but
here what I am doing is that I am not using an object reference first so first
let’s actually see whether this code will run or not as you can see it is printing the answer
which is thousand the price is thousand now that this has successfully executed
this in turn actually means whatever you’ve discussed till here is actually
wrong let’s actually analyze this and understand what JVM is doing in turn now
we are executing the program and the definition of the car class is loaded
into memory now in memory a copy of show price also gets created you are creating
an object whose reference is with the obj and you’ve passed obj which had the
value of thousand now this thousand was again given to value as well and then
what you did was you called obj not show price now let’s actually breathe this
time now in this case what has happened is that I have used only one object
let’s say I have multiple object obj1 and obj to obj one has 5000 obj two has
price 2000 now when you call show price it is only referring to price which is
present there now powers the Machine supposed to understand that this is for
which obj okay so here what is happening is that there is only one copy but OB
and obj have different copies as well so how do you actually recognize which
price does it denote it is it obeys price or is it OB once price no the
second problem that you can see here is that it is directly accessing price
without an object reference as well so how will it recognize which object is
calling which one now in order to overcome all these challenges JVM
actually introduces a very interesting concept which is the this keyword the
this keyword holds the current class object reference in the function and
this reference is automatically present inside the JVM and till the point that
you are performing any operation inside the function this automatically is
activated now in order to make our code slightly better let me just modify this
code a bit more ok I’ll update it here let’s say sis out and copy this
statement and change this to this dot price okay
now it is telling me that this is the price for the object
let me also try creating another object and updating the value for price as such
okay I’ll have two objects and let’s see what it happens all right so what I’ve done here is that
I’ve created a new object reference and using that I have given a value for
price now let me just execute this and let’s run this and see how it works
now since I’m calling it with obj1 the price is thousand and it’s for the same
object that is showing thousand let me try for obj one and it’s updating with
respect to that same as well so this is actually a very important keyword that
is being used and helps he keeps tracks of which object is working with respect
to the members now with this we actually come to a
Confucian and we’ve discussed some of the major topics as part of this session
we started off by talking about variables we talked about the different
types of variables we talked about the concept of typecasting as well we talked
about the various data types and then moving on from there we talked about the
various condition statements the loop statements we start about functions and
then we had an in detail walk into classes objects and even the this
keyword asthma so these are something interesting and important concepts with
related to Java programming so with this we come to a conclusion hope you have a
great day thank you and goodbye I hope you have enjoyed listening to
this video please be kind enough to like it and you can comment any of your
doubts and queries and we will reply them at the earliest do look out for
more videos in our playlist and subscribe to any rekha channel to learn
more happy learning

14 thoughts to “Java Programming | Java Tutorial for Beginners – Step by Step | Java Training | Edureka”

  1. Why the division of byte, short,int n long type the memory is divided in 1byte, 2bytes, 4bytes n 8bytes.. I mean how the division of memory is done?? Can u please explain.. I am jus a beginner so maybe i am unable to get it

  2. Got a question on the topic? Please share it in the comment section below and our experts will answer it for you. For Java Training Curriculum, Visit our Website: http://bit.ly/2QtKjnf

  3. I wanted to install JDK8 but oracle website has the newest version of JDK can you please help me?

Leave a Reply

Your email address will not be published. Required fields are marked *