Introduction to Java Programming
Java is a widely-used programming language known for its simplicity and versatility. It was introduced by Sun Microsystems in 1995 and has become a standard in the IT industry. The following sections will cover various fundamental concepts in Java programming, including its features, objects, exception handling, and collections framework.
Features of Java
Java possesses several key features that make it a preferred programming language:
- Platform Independent: Java programs can run on any machine with a Java Virtual Machine (JVM).
- Simple and Secure: Java syntax is easy to understand, and it offers built-in security features.
- Object-Oriented: Java uses an object-oriented programming model where everything is treated as an object.
- Robust and Maintainable: Java supports strong memory management with garbage collection to reduce memory leaks.
Basic Concepts of Java
Variables and Data Types
In Java, variables are used to store data, and they come in different data types such as int, float, boolean, char, etc. Each data type consumes a specific amount of memory:
int: 4 bytesfloat: 4 bytesdouble: 8 byteschar: 2 bytes
Operators in Java
Operators are special symbols that perform specific operations on variables and data types. Common types include:
- Arithmetic Operators:
+,-,*,/ - Relational Operators:
==,!=,>,< - Logical Operators:
&&,||,!
Control Statements
Control statements control the flow of the program. They can be categorized as:
- Conditional Statements:
if,else,switch - Looping Statements:
for,while,do-while
Object-Oriented Programming (OOP) Concepts
Java is built around the four main OOP concepts:
1. Abstraction
Abstraction involves hiding complex realities while exposing only the necessary parts. This can be achieved via abstract classes and interfaces.
2. Encapsulation
Encapsulation is the bundling of data with the methods that operate on that data. It restricts direct access to some components and methods.
3. Inheritance
Inheritance allows a new class to inherit properties and behaviors from an existing class. For example:
- Superclass: Vehicle
- Subclass: Car, Bike
4. Polymorphism
Polymorphism allows methods to do different things based on the object it is acting upon. It can be seen in:
- Method Overloading: Same method name with different parameters.
- Method Overriding: A subclass redefines a method from its superclass.
Exception Handling in Java
Exceptions are unexpected events that occur during program execution. Exception handling is a technique used to manage these events to ensure the normal flow of the program is maintained. Common types of exceptions include:
- Checked Exceptions: Must be either handled with a try-catch block or declared with a throws keyword.
- Unchecked Exceptions: Runtime exceptions that do not need to be explicitly handled.
- Errors: Serious problems that cannot be handled by the program.
Examples of Exception Handling
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");
} finally {
System.out.println("This will always execute.");
}
File I/O in Java
Java provides classes in the java.io package for performing input and output operations on files. Common classes include:
- File: Represents a file or directory path.
- FileInputStream: Used to read bytes from a file.
- FileOutputStream: Used to write bytes to a file.
- BufferedReader: Efficiently reads characters, arrays, and lines from a file.
Example of File Writing
File file = new File("example.txt");
try (FileWriter fw = new FileWriter(file)) {
fw.write("Hello, World!");
} catch (IOException e) {
e.printStackTrace();
}
Java Collections Framework
The Java Collections Framework provides a set of classes and interfaces for storing and manipulating groups of data. Key interfaces include:
- List: An ordered collection (elements can be duplicated).
- Set: A collection that does not allow duplicate elements.
- Map: A collection of key-value pairs where keys must be unique.
Using ArrayList
List<String> names = new ArrayList<>();
names.add("John");
names.add("Jane");
Using HashMap
Map<Integer, String> map = new HashMap<>();
map.put(1, "One");
map.put(2, "Two");
Conclusion
Java is a powerful and versatile programming language that enables developers to build robust applications. Mastering its core concepts such as OOP, exception handling, file I/O, and the collections framework is essential for any Java developer. This article serves as a guide through these basic yet important concepts. With continued practice, you can advance your Java skills and develop more complex applications in no time!
Java is one of the most fundamental
programming languages
that anybody can learn
despite being so simple. It is a Marvel what can be achieved
with the use of java?
Hi everyone. I welcome you all to this Java
full court session by Edureka,
but before we begin, let's look
at our agenda for today. So we're going to start out by
talking about Java, what it is, and why do we need it?
Then we're going
to discuss a few basic concepts like variables and data types in Java followed
by which we are going to talk
about operators control
statements and methods. We are also going to discuss
the meat and potatoes of this session classes objects
and object oriented
programming Concepts in Java followed by which
we are going to talk about exception handling
then we're going to discuss
Java collection Frameworks and finally close this Action
by discussing the Dom parser in Java also do click
on the Subscribe button
to never miss an update on the hottest Technologies by
the Edureka YouTube channel. Okay, before we start off
let me introduce myself.
I am vinoth and I have been with this industry
IT industry specifically into Java development
for last 12 years.
Alright, so the first topic is
about introduction to Java. So what are we going to cover
in this particular topic? So it's going to be
introduction to Java
what Java is all about will have
Java installation done as well. So that you guys
can use it in future. You guys can try your hands
on we'll talk about modifiers
and variables in Java. This is pretty much similar to what we have in other
programming languages will talk
about Java data types as well, which is nothing but data type as we have the it's a storage
for different data types,
right or the data that is store whatever
you want to process. Song is first put into memory
and that is what
data type is all about. So you have different storage is like for character you
have something else
and for float you will have
something else for long. We will have something else sort of data type
conversion in Java.
So so you could convert
from one data type to other data type in Java. There are implicit
conversions done.
We're in the programmer
need not take care about it. Java programming by itself would
take care about converting it which is implicit conversion
and there are few conversions,
which programmers have
to take care about they have to explicitly mention that you have to convert
from this data type
to this data type. And if you don't do it you would end up in
compilation errors or something.
We'll talk about operators
operators are nothing but the operators that work upon this data type
and which is nothing
but transformation. So you kind of use
this operators to add up for say for example Of two integers
you want to add it up.
So you would have
this operators used. We'll talk about control
statements in Java as well control statements.
Like you have if else and for loops
and stuff like that, so we'll talk about it.
So Java is pretty much similar to other programming
languages thing is it has some unique features
which makes it really important in the current industry
the IT industry when it comes to Big Data
and stuff like that.
So we'll touch base on all
this important features of java, which would help
you to understand. Why do we really use it?
Alright. So the first
topic is Introduction. So what is Java so Java as we
said the programming language
which has object-oriented
programming model. So when I say object-oriented
programming model everything in Java is taken as an object.
So object is nothing but something that has got State
and behavior say for example, you have chair, right?
Jed has got a particular State and it has got
a particular Behavior. If you do something
if you move it,
it would go this way and that way
and stuff like that. So basically any object
if we think about
in reality realm any object for that matter would have
some kind of state and it would have
some kind of behavior
which incorporates on its own. Right? So basically similar to that
Java is programming language,
which is based on object
oriented programming model. So everything Java
could be thought of as an object or you define a class.
So say for example
you have house right? So house could be thought of as an object or class
rather a house has a class
and it would have
certain attributes right like number of rooms
or stuff like that. So that is nothing
but the state of the house.
So this was actually brought
in by Sun Microsystems in 1995, and basically Java is nothing but we have jvm but jvm
is nothing but you kind
of kind of can say it's
a specification right Sun Microsystems has said
that this is how it should be so that any company tomorrow
I can go and create
my own version of java, but it has to be aligned
to this particular specification that is given
by Sun Microsystems.
So Java is nothing
but reference implementation of java is provided
by Sun Microsystems, but nevertheless
as I said give him
itself is a specification which anyone can Implement
actually but we will talk about Sun Microsystems talk about
the reference implementation
that is nothing but one
created by Sun Microsystems. So everything in Java
would have a state and behavior and
which would be defined by class.
Again, it was started off by
a team led by James Gosling and we know it's open source, which doesn't stop anyone
from putting in whatever code.
I want to still we have lot
of versions coming in Java. So it's not that you
just have one version created by Sun Microsystems
and it's been used
across the industry. You have like find
some issues or if they want to have
some kind of enhancement
in the open a particular
module the keep doing it. So right now we have
like Java is at version 12, which is like we have lot
of enhancements coming in.
It's a evolving thing
it's ever evolving thing. And as I said,
this is open source tomorrow. If you become a good
programmer in Java,
you could go and actually
write something for Java and which would be
moderated by someone and which would be put
as open source.
And anyone can use it
other thing is Java the very important feature
why we use Java or why Java is so widely used is
right once and run everywhere.
So you write a class
or you write program once and you compile it and this particular
compiled version of class.
Be run anywhere on any machine
or you could transport this particular compiled
version of java, which is nothing but classify we
call it as a class file again,
you did not get into
what is class file. But just to say that you compile it you get
a compiled version of it
and this compiled version of class could be transported
anywhere in the network or you could put it
anywhere and just run it
so you could take it
on your pen drive as well and go anywhere and plug your pendrive
get this class path
download this class path or download this class rather and just run it so it right
once and run everywhere
and the magic part is it
could be run on any environment. It could be run on any platform. That's why it's
platform independent.
So I could write a program today
on Windows compile it and tomorrow I can just take it
on my pen drive and run it on Linux as well.
So you don't have
to take care about it. Java by itself has a feature
to make it platform independent. So As you could imagine this
is one of the reasons why
it's been widely used because since we
are getting into a phase of distributed computing,
we cannot have everything run
on same platform. You don't know
where your so you as a programmer write something
but you don't know where this particular program
is going to run. It could be on any platform.
So this is why
it is more important. So unlike dotnet, right? You need to have Microsoft
just to give you
this thing comparison with dotnet so for.net
you need to have Microsoft stack implemented,
but for this you need
not could be run everywhere. So Java can be used
to create complete applications that may run
on a single computer
or can be distributed among servers and clients
in the network. As I said, this is more
about the application
of platform-independent
programming language. So it could be used on any machine you
need not take care
about which machine
your program is going to run on. All right, so let's
talk about Java. Earth so what features
do we have in Java?
First thing is Java is
pretty much simple when it comes to SDK or when it comes
to API application interface.
It's pretty much simple. It's kept as simple as possible. It's pretty much similar
to other programming languages
and it's verbose. So anyone can just read
through it and understand what it is trying to do
so they have kept it
to that level so similar to any high-level languages, right the coach
should be such that
as you read through it. You should understand what it is doing and that's
what they have tried to do.
Its high-performance. One of the things that I
already mentioned about. It's an evolving system.
It's not that it's been
just done once and been used throughout its evolving system. So as and when this continuous
Improvement done, right,
so as then when if I as
the application programmer if I find something not working as expected I can raise a ticket
and they could go
through the ticket or there's a Java development. Which has been driven by Oracle.
Now, they would look
at the priority of this particular stuff. And if there are a lot
of tickets been raised by
other companies as well. And if something could be done on the aspect
on the particular aspect
that you raised they
would surely Incorporated and notify you in a particular release
the enhancement is coming up
and stuff like that. So it's a evolving system
and you know, the performance is always
if there's some drawback or
if there's something not working as expected they would surely Rectify it
in the future releases.
So that way it keep it up
to the mark the keep the high-performance thing
going it is secured. So Java basically runs
in virtual machine sandbox,
and no one can get
into this particular space. So no one can intrude it. I would say
so that keeps it free from virus
and stuff like that or untrusted process. And other thing
that is important is
unlike C. Java doesn't expose pointers so in see There
could be malicious user who could get into the memory
location through pointers
and can manipulate the contents
of a particular memory. Right? Whereas in Java.
It doesn't expose the pointer. It doesn't give you the pointer
to a memory location. So you can't actually go
and change the content
of a memory location
when you are using Java so that keeps it secure. So it's robust.
So Java checks the code during
compilation time and runtime. So basically what happens is as I said when you compile
it you get a class file
and whenever you try
to run this class file on any of the machines, it will ensure
that it's properly done
or if there's some issue
with the class file. It would say that it's
a correctly classify. So basically you have
some kind of checks done
during the compilation as well compilation is nothing but if you have something
tactical error say, for example,
if you miss the semicolon at the
end of a particular statement or an end of any statement, It would prompt you
during the compilation time
that this is not
what is expected or it would ask you to correct it once you have everything as
for the expectation,
it would compile it
and create a class file and when you put this glass file
to any of the machines during the runtime
it checks as well.
And the other thing is about you don't have to take
care about memory allocation and releasing unlike
in other programming languages.
Java by itself does garbage collection
garbage collection is nothing but when a particular memory
is not being utilized
by your program of goes out of scope it
would Java by itself has a thread I don't want
to get into threads
and stuff like that. But Java would enough
the memory contains by itself. You don't have to explicitly
write a code to clean
it and see you have
to write a code to clean. It errors in Java. It's done by itself.
So that makes it robust
other thing is it's portable as we already spoke. You can write
a programming windows.
You can run the same program
or you can write a program in Windows compile
it get a class file or the compiled version
of the class and just put it
on any platform. It could be Windows. It could be you run it
on Unix or Linux or Mac
or anywhere so you don't have
to take care about it. So Java by itself does it and that's where jvm comes
into picture which we'll talk
about in the the further slides. So other thing is it's Dynamic which means that it has
runtime polymorphism.
So all the objects
are evaluated during runtime. It's not just that it's done
during the compile time. There.
Is this something done
during the runtime as well. So basically it's called
as runtime polymorphism. But just to keep in mind
not everything is linked up
during the compile time
is something done during the runtime as well. So it could be
distributed as well.
You don't have to have
all the code put into one machine and run
it from my machine. I could run something written
on your machine as well.
If into net in the same network
or if if they are exposed to a network we could run
programs on different machines. So that's what distributed
is all about.
So you could think of big data. So this is one of the major features why
Java is been widely used
in big data, right? So big data is nothing
but you have chunks of data you have like petabytes
of information coming
in every minute or every hour or every day, right and you want
to process it.
So it cannot be done
in one machine if you want to run
everything on one machine as we had earlier, right?
Everything was monolithic
everything was done on one machine sort of so that's where you would want
to have servers right.
Now. The server thing is it's not being used that much
since there's a lot of English.
Intense stuff like that. So distributed computing
is nothing but we have like pure computers
or normal computers
that we have and programs
are actually done on this machines
rather than rather than having a high-end machines.
So basically this feature is what helps Java
to be used in big data. And as I said,
it's run on commodity Hardware
as against server Hardware which needs a lot
of investment for companies. Java is multi threaded
so multi-threaded is
nothing but so you have
multiple cores on your machine, right? You have like four cores
and stuff like that.
So you could utilize all this
for course say for example, you want to do addition
of two numbers and multiplication of two
numbers right different numbers.
So you don't have to run
everything on One Core. So this could since you have four processors
right for course,
you could have
addition run on one core and you could have
this multiplication going on at the same time
at the same instance, right?
You could have this
multiplication going on as well. You could run them
as a thread right? You don't have to have
one waiting for other.
You don't have to do it
in a sequential manner when you're operating
on different variables, right? So that's what multi-threaded
is all about.
As I said you could have
this operations carried out on different course
in the same instance of time. Object-oriented again
as I spoke earlier,
everything is performed
using objects and Java can be easily extended since it is based
on object model.
Now, let's talk
about which sectors or which industry sectors
actually use Java. So you have Android apps.
So Android apps Cal
could be written on Java. So basically the underneath
is Android API, which is similar
to jdk so jdk is nothing
but Java development kit. It's widely used
in financial services industry. If if you would have
some idea about it.
You could see that mostly all Financial
companies use Java. So the Legacy systems
that we have in financial
companies is mostly developed on Java. So one of the aspects
for this is more
about it's pretty secure. So that's why it's
been written on Java lots of global investment Banks.
Like Citigroup Barclays Standard
Chartered and other Banks use Java for writing front and back office
electronic trading system.
So one of the main features
why it's been used in financial industry
is about security. It provides high
level of security
as we spoke earlier
Java web applications. So basically you have
web servers on which your application would be hosted
and you could request
for a particular JSP or JSP is nothing but
a dynamic HTML page right there in the contents could change
basically you could request
for some particular JSP and you could get it
so say for example, you are trying to log on
to a particular application
you get a login page that is nothing but a JSP. So basically a mini
of the web applications
is developed on Java as well. One of the main features why
web applications are developed because you have a lot
of web servers supporting,
Java you Have
to deploy application on a particular web server and could access it
from anywhere across glue.
You should be
on internet though. Embedded system when it comes
to embedded system. It has to be lightweight, right.
So Java it I remember
Java version 8 had lot of feature making it pretty much
light weight when it comes to embedded systems.
So basically you have
Micro addition j2me. What we are talking here
is j2se and the thing that we so there are
three flavors of java.
So one is j2se, which is nothing
but standard edition and which is standard edition,
which you have like all
the data types and stuff like that all four loops
and stuff like that. Right that is about j2se.
You have G to EE
which is Enterprise Edition, which is nothing but the web application that
we spoke about and we have j2me
which is micro Edition, which is nothing
but for embedded systems as its name suggests,
it is micro Edition,
which is light in weight. And as we can imagine
that in embedded system, it has to be lighter
since it is burnt into a chip,
right and you cannot have
a big application. So that's why
we have lightweight when it comes to j2me.
So again as I touch base
on this it's about web servers and application servers which makes Java compatible
for web applications.
So we have Apache Tomcat which is pretty much widely used
which was a web server earlier. Now, they have Apache Tom e
or which is Tom double e
which is nothing but application
server version of it. So basically when it
comes to web servers or application servers,
what you do is you as a client could send
a request to our web server and web server
or the application server
would just process this particular request and send the response
the way the It's written.
So basically it would serve
the expected result out. So you have
Enterprise applications. Again, this is
Java Enterprise Edition,
which makes it favorable
for web applications. So all these
specifications j2me. J2w.
J2se, this are nothing but
specifications exposed by Java. So if you as a developer
wants to do something or if you want to write your own
version of it you can do it.
So where is Java used
again scientific applications? So I as you could imagine
in scientific applications, you need to have
high level of accuracy
and precision rather. They could be
mathematical equations and mathematical computations
which needs lot of CPU time
because it's very
CPU intensive right? When you do a very
precise calculation with high level of high degree.
It needs lot of CPU time, right? So that's where Java is good at. So basically this is about as
a spoke about multi-threading
utilizing all the course
to the fullest suppose. You have four core processor
using all these four cores is been done by
Java Java has feature
or through threads you
could actually read through or actually utilize this for course to the fullest
Big Data Technologies again,
big data is nothing. But as I said, it's distributed you cannot have
everything run on one machine,
which was the case earlier. You would have one server put up and everything is done
on that particular server.
Now, it cannot be the case. That's where Big Data comes
into picture wherein you have distributed architecture
and you have this data being processed across Network
rather than just on one machine and mind you as I said,
this machines are
commodity hardware and not server level Hardware or the Enterprise level Hardware
which makes Cheaper Internet
of Things So Internet of Things is coming up the booming thing wherein you
could connect things together.
Say, for example,
you have cars, right? So you could
connect cars together so you could have
sensors in your car
which could emit data and you
could connect them together. So basically it's all connecting
things together or say, for example, let me talk
about internet itself.
So earlier if you remember
computers were not connected it were all pure right. It could just be used
for your own purpose.
Now internet has started wherein you have all
these computers connected and if you are connected
to the internet,
you could go onto Google
and search something or whatever you want to sort of So basically this is what
internet of things is all about.
So consider this
instead of computer. It could be any other objects
a car for example, as I said so consider
car has sensor
and it is emitting
this sensor data every minute and we could utilize
this sensor data and do something
with it or one car
can know where the other car is. So that's what internet of thing is about all about
connecting things together.
Let's start off
with the setup setup for Java. So basically you could go
to this particular site and just download the SDK
based on this jdk, right?
So basically based
on whatever platform you are at. If you are using Windows, you have to select Windows
if you are using something else
if you have mac,
you can select Mac. So this is pretty much similar to other softwares you get
an exe file download it
and you just have
to run that exe file. So basically I can show you
what gets downloaded. So I have downloaded
version 12 for Java
as you could see here
and and since its Windows, it is mentioned as Windows. So this is nothing
but an exe file that you get
which you could run and you would have
Java installed on your machine. So it's pretty simple.
It's pretty much similar to other software's you
have say for example, or I could just show
you the location
where it is installed. So if you get into
the program files, you can see javabean
installed here, right?
And it says jdk 12. So once you install Java, once you download
this particular stuff jdk and
once you install this
this executable you should be able to see
this Java folder in your program files.
So it shows here. It's for you can select whatever
you want to see you have as you could see here.
This line X there
is Windows Mac OS and stuff like that. You have to select
the platform you are
on and should be good to go. This is done. You could see you get a exe
which you have to run.
So basically to run Java
what you have to do is yeah. So you go to the system you have
control panel system you go here
and you have to click
on Advanced system settings. Basically, what we are trying
to do is we are going to set an environment variable right
and what we are going to set
is this path variable. So you have if you want to put it specific
to a particular user you
can put it here put it
in the upper space or you want it
across the system. You could basically put
the path variable here
in the system variables. So once you install it
you have to make sure that you have this particular
path being put in
your path environment variable. So basically tells the OS that you have executables within
this particular directory.
So once that is done, once you have
this properly setup, let me open a partial.
So partial is nothing but it's pretty much simpler
to command prompt but it's a Linux flavor of it.
So basically you could run
Linux commands as well. Okay, so I will I
will once this is done. Give me a second.
Okay. So with partial you can do LS which would give you a listing
unlike in command prompt.
You have to give dir. So it's basically
good for programming. So once you have
this properly set
once you have
this path properly set if you write Java here, if you write Java
on your command prompt,
you should be able to see
this help coming up here. So if it's not properly set up, you won't see this it would give
you unrecognized command.
Yeah, open command prompt
and type Java. So once the path is properly set
you should be able to see this. So let's set up Eclipse as well.
So it could be eclipse or IntelliJ whatever
you are comfortable with so you could use
either of them
since IntelliJ has
much more features. You could use IntelliJ as well. So you go to Eclipse download
and whatever flavor you
can take the latest one Whatever flavor you
want to install if you if you want
a simple one you can do it.
If you're trying to do
something on web. You can download
that one as well. So basically for simple purpose
for whatever we are going
to do you can have normal ones. So let me quickly open
up my so this is nothing but the IDE integrated
development environment
that I use with just IntelliJ all the IDS are
pretty much similar. So IntelliJ similar to Eclipse,
so it's coming up.
So basically what you do is you have to select a workspace
first workspace is nothing but all your program
all the class files all
the class and everything that you write would be put
into this particular Works piece and you can create
a new class and start off.
So when we get
to the hello world program, which is the first program
that we are going to talk about it would give
you a clear idea
on what we are talking about. So let's talk
about Java internals how it looks like
and all the features
that we spoke about. So basically so far what we have covered is more
about Java is object
oriented program or it uses
object-oriented programming. Paradigm which is nothing but everything is thought of as
a class with a particular State
and behavior right
is platform independent. That's why it's been widely used
it secured as well. That's why it's been used in
banking applications and stuff.
It's good for
distributed computing since its platform independent. You don't you just
have to write it once
and you can run it everywhere. So basically this platform
independent aspect is what helps it to be widely used
in Big Data applications.
So let's talk
about the internals. So what is jvm jvm is nothing. But again, it's
a specification right?
You could have your own jvm son by itself gives
specification for a jvm. This is what the GBM
should be all about so
I could create my own jvm. But we usually we use
the reference implementation of sun Microsystems Oracle now.
Right, so jvm is
a virtual machine that runs the bytecode. So basically there has to be
some level of compilation done
before give him
can understand it. So that's where you
have Java compiler. And so what this does is nothing
but it takes your source code.
It takes the class files as
or it takes the class that you write as is so Java compiler
would consume it
and kind of compile it
into a DOT class file so dot class file is nothing
but compressed version of it and compiled version
of it as well.
And this dot class file is nothing but it's also known
as bytecode and this is what a jvm could understand.
So once you have
this class file, it could be sent to the jvm and jvm could understand
it and run the applications.
So what makes Java
platform independent is this Java compiler is platform. Pendant you don't have
to take care about it.
You just have
to run the compiler. And whenever you want to run
this particular byte code on any of the machines,
you just have to have jvm
for that particular machine. Right? So basically if you
want to have online X,
right if you want
to run it on Windows, you would have jvm
installed on Windows or you would download
the jvm for Windows.
And if you want to run it
on Ubuntu or the Linux or Mac would just have
to have the jvm downloaded for that particular platform
and it should be able to sense
this particular byte code. So basically this is what makes
it platform-independent. Right?
As I said,
once you have this bytecode once you compile it this
bytecode could be transported or ported into any
of the machines
in operating systems and you should be able to run it that is what it is all about.
It's right ones
and run anywhere. So as I earlier
mentioned you could As get this class file
into your pen drive
and take it anywhere and you could just
plug your pen drive and just run through
that's how simple it is. So, this is Java
runtime environment where in you have set of jvm plus you
have libraries libraries,
it does nothing but you know, although programs put together
all the programs source code
for Java put together. So our T dot jar is
one of the libraries which would have
most of the classes
or you have you till classes
maybe string class string is a class itself, which is exposed by Java.
So this particular jar file or it's a Java archive jar
is nothing but Java archive which is set of java classes
or the class files rather
which would have lot
of class files within so in our T dot jar you would have
something like string class and stuff like that a lot
of other classes,
which is been used by the sea. Some are which has been
used by Java itself? So basically in JRE this is
what you have jvm
plus set of libraries plus other additional files. So as spoke jvm is nothing
but specific to environment,
but all these things
like Artie dot jar and stuff like that
would be independent GRE does not contain tools
and utilities such as compilers or debuggers for developing
applets and application. So GRE by itself
the runtime environment,
so it doesn't have compilers
and stuff like that. So jdk is nothing
but it specifically for development you
could see here.
It's JRE plus development tools
you have compilers and stuff like that as well. So to run a class file,
you just need the JRE but
if you are a developer, you would need jdk so
what we downloaded earlier if you remember
that was jdk right jdk
for Windows or jdk for liners. So basically if you see
this one could see here as jdk. So essentially you need jdk only
if you are a programmer
if you just want to run
the class file GRE would suffice so why is jdk GRE and jvm as we spoke about you
could see jdk is a superset.
It has everything right GDK
would have your jvm. Plus it would have
as we spoke here. It's JRE plus your
development tools as well.
As you could see here details
it has everything here. It would be really
confusing right now. If you directly get
into what all this is all about,
but basically you
could imagine jdk is a superset and Jerry is nothing but
it's your runtime environment which has jvm
and some additional files
or RT dot jar as we said which is nothing but set
of files set of class files
that is exposed by Java which could be used
like string for example, right?
Let's see how it works. So basically you have
your source file. So this is what a developer
would typically right
would create a DOT Java file. So whatever you write
you create a class. You just create a new class
and write something to it.
What you get is dot Java you
get the extension dot Tower. So basically this
is your source code, whatever you write you
as a developer would
write this class. Is would be sent for compilation
or whenever you are good enough done with your coding
you would compile it.
And once the compilation
is done once everything looks good enough. Once the compiler
doesn't Mark anything and
doesn't flag anything rather, which means everything
is syntactically, right? You will get Java bytecode.
Just nothing but dot class 5. Now. This dot class file
could be moved across Network
or you could as I said, you could just put it
in your pen drive and can take it anywhere
and you could run it
on any of the environments. You just have to have jvm. So basically you
could run this class file,
which is compiled on Windows. You could run it on any of the environment
any of the platform's.
So this is something that we
spoke about during runtime. There's a verification as well. So so when classloader would
load this particular class file,
it would ensure that it is up to the Mark
or it's not manipulated sort of so if it all it
sees something wrong,
then it would flag it off as you know corrupted
file or something. So this is nothing
but Java class file libraries
are T dot jar that we spoke about Java archive. So this is what is happening.
When you run a particular
class five, right? So you have this class loaded
and then you have this compilers just-in-time compiler
actually running it for you.
So basically the part of jvm so
jvm is remember jvm is nothing but it's a platform. It is specific to platform.
So basically for Windows you
would have a different jvm. And for line X you
would have a different jvm. So yeah, you get this class
you load this class
using class loader and you run through
the application or run through the class files.
So typically this is how Java operates so just
to give a just on this one. So you have a source code you
have dot Java file written
you compile it you
get our class file and you can put
this class file anywhere. You can run this class file
anywhere on your network
or wherever you want to you just
have to take this class file and on the machine
on which you run. What would happen is
you load this class file
first using class loader and with jvm jvm would
have just-in-time compiler which would run
a particular class for you.
Right? So what we are trying to do
here is you're running the source code
that's written on any
environment you are running it on any other environment. So basically you
could write this on Windows.
You could write
source code on Windows, but you could run it
on say for example line X. So that is what makes
it platform independent.
So here let's create one class and as we created I
will More about it so that you could open
up your eclipse
and could create something
like a new project so it could be a bit different
for you the look and feel might not be
exactly the same as mine,
but you just have to create
a new project select Java. So basically I could
a project name. So whatever you want
to so basic nomenclature is
like it has to start
with uppercase letter, which is camel casing right? So you should follow
camel casing venue.
That's one of the best practices it won't flag you as
some error or something, but that's a normal
industrial practice that
whenever you create
a Java project. It has to use camel casing
created record, Java. So it's creating
a project for me.
And as you can see here, I have this particular project
being created right now. What I do is
I create Java class.
So basically as we said everything could
be seen as a class, right that's what
object-oriented is all about.
So basically what I would do
is I would create a class here. So this is my source folder where enormous Source class
would be there.
So as you can see here
new Java class so say I create calm dot Ed u-- Rica. So this is nothing
but your name space
or the package, right? So you could give whatever
you want to basically this is to avoid collisions, right?
If we don't have a name space
there would be lot of collisions within the class. So there are a lot
of people working
on the same project right so I
could create a class with name. Class A and the other person
might read classy as well. So when this is club together
into one particular application
there would be Collision
So to avoid this basically what you have is you have a namespace.
So I would write as calm
down dear a card dot Class A. The other person
would write something else and that would avoid class name
collisions Applause collisions.
So this is compounded
Eureka is my package or namespace and hello
world is my Java class name. So as you could see here,
there's a package calm
down Ed Eureka, which is again a namespace and there's a class by name
hello world that's been created.
Right? And if you want to see
you could actually go and so you can see
a folder structure
created here in the source. So this is your Source folder
right within your project. There was a source folder
where in we created the class.
So if you go to the source folder you
could see a packet structure or you could see a directory
structure being created
which starts with calm and within calm you
would have at Eureka and here you can see
Hello World dot Java.
So remember we said that your source code
would have all the Java files. So basically this is
what I was referring to.
This is a method that the default method
that's been called. So when you run
this particular class file
jvm would actually look out
for this particular method. So you need to have
the same signature as has so you would have a main
method wherein your program
execution would start, right? So as then when you compile
it and run the class file, so basically when you compile
it you would get a class file,
right and when you run this class file jvm would check
out for this main or a method that has the same
signature as this one.
That's a main method and your program execution
would start running from here. So basically it's a entry point
for your execution, right?
So this would be a simple program wherein we
would just print hello world. So basically you have
like system system is
a class and this is how you print in Java. So I don't want to confuse
right away by saying
what is system
worries out and println, but basically what you
have is a system is a class as I said everything
Could Be Imagined as a class.
So in Java everything
is a class. So basically you
could just click here and you could see
the source code of it, right?
This is the source code
and this is coming from our T dot jar
remember in jvm. We spoke about in GRE.
We had our DDOT jar. We had Jerry we had jvm
plus plus class files. So all this has been written
by Java by the Java community.
So basically you can see here. This system itself is a class. So out is instance variable
and println is nothing
but a method within out so what this statement
particular thing is going as nothing but writing
it on to your console.
So let's print hello world. So basically when you build
a project it's compiling it as you could see here.
It's saying it's building it. So once it has built it you
could see a class file here. Right?
So you could see here
hello world dot class. This is because we built it
when you build it. Your Java file would be
compiled by your compiler
and it would create
a DOT class file. And remember as I said, this class file dot class file
could be run on any machine.
So this is Windows machine that have written
this file Java file and compiled on now.
This dot class file could run
on Linux or any platform that you want to run it on. So, let me talk
about this class.
Right? So you have a public key word, which is nothing
but access modifier
which gives visibility. So basically what we are trying
to say here is hello world is publicly could be publicly seen
so it could be seen anywhere
within the application. So basically for class level
you have public which as the name suggests.
As the name gives out it
could be seen anywhere within your application that the visibility
key access modifier.
All right, so you have
the keyword class here, which is for the class. You need to have
it mentioned as class.
If you write something else, then it would give you
a compilation error. So it has to be
exactly the same.
All right, that's
the syntax of it. Hello is nothing
but the name of your class, then you have this public
static void main,
which is nothing but as I said, this is the entry point
for your application or your class file.
So when you run
this particular class, it would start off from here. You have a static keyword
static keyword is nothing
but it's at the class level. So basically you
need not create instance. We haven't reached
that point yet.
So basically hello is a class and you could create
instance of hello, which is nothing
but object right?
So when you have
a static keyword here You need not create object
of hello to run it if it's not static,
then you need to have
object of hello created. So basically what I'm trying to say is see you have
one more method here,
which is test. Now this doesn't have
a static keyword here. So basically what we
can do is we can print So
yeah, this is a non-static
method right now. We cannot call it directly. If it's a non-static.
You need to have a instance
of Hello World created. So basically how you
create instance is nothing but hello world.
That's your hello world object. So when I say
instance I'm talking about creating object, right
and you could create
new hello world. So object of hello world is
created using new keyword right? When you do this you
would get object of it or now.
What I do is so basically what I was trying to say is
you cannot call test as is if you do it you would get
a compilation error saying
that non static method test
cannot be referenced from a static context, right? You cannot call it
without having your object.
So basically I can call it on Hello World object DOT test
Now I can call it now. It doesn't give
me compilation error.
I'll create one
more static method which would give you some idea. So I will rename this
as non static test
and this would be static test. Right and we are printing
your static method and here we are printing
non static method.
So hello world
dot nonstatictest. Now, whereas the static test
did not be called using object so we could directly
call static test.
Sorry, I haven't
written static here. So this is a static method. Okay, so now you could see here.
It compiles fine. Right? So what I was trying to say is
when you have a static
method you do not have object to call it. Whereas non-static method
you need to have object.
That's what the static
is all about. Then you have void is nothing
but the return type it's not returning
anything from here.
So that's why it's void. You have main method. That's the key word
that the entry point
for your application. You have this arguments. You can see string
array of strings
which are arguments provided
to a particular program. So you could pass
on as many arguments as you want or
if your program is say,
for example, you want to pass your name as
an argument you can do that. So this is arguments then we
have main which represents
the Above the program which I already mentioned then we have system dot out
dot println is nothing
but the print statement so as I mentioned system is nothing everything
could be thought of
as a class system is a class
out is instance variable and println is
a method within out. So basically you don't have
to think much about it just
to understand the structure
of it just to understand how a particular class
is been written. This is what we have.
This is how we write
a class right again, just to brief on this
you have access modifier which denotes the visibility
of a particular class.
You have the class name you have
the main method which is nothing but the entry point for your class you
have a static method,
which says whether you need an object to call
a particular method or could be called
directly from a class.
You have a return type here. So this is how typically
any method would be written and you can write
whatever statements you want to
within this particular method. This case we have printed
out hello world. So basically you
could follow this
when you do it on Eclipse, so it might be a bit different
based on the eclipse version that you would have
but it should be
pretty much similar. All right, so you create
a new Java project. So I showed this
already on IntelliJ,
which is also widely used IDE. But yeah, you could use
Eclipse as well. So basically you
could see the project name
being written as hello world, right and here it mentions
the JRE to be used. So here you can see class class
being created and let's see
how we can run this. So we compiled it and we saw
that dot class file was created. Now we can run this.
So as I said main
is the entry point so it would start
running from here. So your program control
would come here.
And the first thing that it would see is you
have printed hello world, so it should print this one
then I would keep it simple.
I don't want to let's see
what's been printed here, right? So you could see here. Hello world being
printed first, right?
This is where the program
execution started from. So it came to mean so
hello world it printed out hello world.
Then you give a call to
this non static method. So it printed non-static method which is been printed
in this particular method
and then it gave
a call to static method and you could see static method
being printed here. So one thing to remember is
the program execution starts
from Maine and it just you
know executes this main method. So whatever content
you want to write you would basically write it
in the main method
so you could see here hello
world being printed out. Let's see how easy it is
to coat the same in the J shell. So J shell is nothing
but shell prompt
that was created in Java version 9 since nine
you would have gesture. So since I have
Java version 12,
I should have J shell as well. So yeah, J shell is
nothing but a prompt so it's nothing but
instead of writing
into integrated workspace. You could have J shell and you could pry
out something here.
It's not something
for production use as such it's basically to test something right
you as a developer could
if you want to see what it does instead of writing
everything into the main. So if you write a class you
would have to write
things into the main and then run it and stuff
like that with J. Shell. It's just a kind of interpreter
wherein we could write something
some command and see
what the output is. So basically you could say for
example we printed hello world, right so system dot
out Dot println.
Hello world, right
if you remember this is what we typed into
our main method plate. So if you want to run
this you have to have
all this artifacts created as is right to have a class
you need to have main method and then build the class
and then run it basically
initial you could run it just to see what's output. As I said,
this is not application
as such this is just for the developer to test what the output for
a particular command would be
and what a modifiers in Java. So one thing that we saw in the program
was access modifier.
We already saw about actually
this one right public and these are public
here as well. So these are nothing
but modifiers right public
as I said this public means
the access modifier which shows that hello world could be accessed anywhere
throughout your application.
So here we can see as a board
or the fries changes. Meaning of other phase
in some so basically it just trying to say that one
of the aspects are one thing
that access modifier
could be used is to control the visibility
of a particular class or a method as well.
We have access modifier
for your methods as well. So this is just one of the things right we
would see other modifiers
as well modifies in general has
some other things as well. But when it comes to access
modifiers it basically controls the visibility
of a class visibility of a class
or a method or so. Yeah modifiers here as you could see there is access
and on access modifiers,
let's see access modifiers. So we use public already. So this one is nothing
but a access modifier
which is public which says that it could be used
throughout the application so visible to the world
as it says public is nothing
but visible to the world. If we talked about
in a logical order if we talk about the visibility
so default is visible
to the package. So default is nothing but within the package
it would be visible.
So basically you could default is without any keyword
without any access multi-faith. That's a default scope So
within the package it
would be accessible only within the package. So you have like
calm down Eureka.
That's your package. Right? So this hello world
would be accessible
if it has a default scope. It would be accessible only
within calm down Ed Eureka. If you try to access it
from some other package
you would get an error. So that's the default
visibility:visible to the package private is nothing
but it is visible to the class.
It is only visible to the class. So this is the lowest visibility
only visible to the class. If you try to access it
from outside class even
within the same package
you would get an error because You won't be able
to access it is accessible only within the class public
is accessible to the world.
It could be accessed from
anywhere within your application or anywhere within your wherever
your class file. So basically if you
if you have a jar file,
but what I'm trying to say
is public is accessible anywhere right protected is
again visible to the package and all the sub classes.
So we will talk
about sub classes. So subclasses is nothing
but in C we have inheritance, right say for example
integer integer is a class as I said in object-oriented
Paradigm or in Java everything could be visualized as a class.
So integer itself is
a class, right? So there's a number
there is a super class which is number which has all
the common state and behavior
that a particular number
would have right so number is a super class and you have subclasses
like Teacher float
would be a subclass of number long would be
a subclass of number. Basically.
This is inheritance, right you are inheriting integer
float long double and everything from number class.
So number is a super class
and all this integer float and everything is
a subclass of number. So when it comes to protect it,
it says that it is visible
to the package and of the sub classes, so just to keep
in mind as of now,
you can think of access
modifier as visibility of a particular component or could be visibility
of a class or visibility
of a method or instance
variable as well. This is what drives
the encapsulation factor of object-oriented Paradigm.
So basically we control the
access or all this components or we control the access of class variables
methods and everything
which makes it encapsulated
cannot be breached. Sort of as you could see this is like I could make this one
as default as well.
All right, so this
is default scope. It would still run
because it's within the class. Right now suppose I make
this one as private, right?
Just to show you what
this encapsulation is all about or what this access modifier
is all about suppose. I make this one private right
still this one runs
because it within the class
you are trying to access it within the class now. I create a new class
say for example,
we say axis modified test. So I create a main class
here again main method. Now suppose if I try
to run this, right?
So basically I create
the same stuff here. See I create
a hello world object. Okay.
Now this one is
private right now. If I try to access it from here, what I was trying
to say is if I SEC
as you could see here it says that nonstatictest has
a private axis to hello world. So you cannot use
it from outside.
That's what I was trying to say. So basically since it
has got a private scope you cannot access it
from other class.
And if I remove this private now
with gives it default scope and as we said default is nothing but it has got access
within package you could see
this error going off here now it is accessible, right? So that's what is it is all
about when you have
a private scope. It's within a class. There is default is
within a package public
is accessible anywhere and protected is visible
to the package and just the subclasses.
So let's talk about
non access modifiers. This is not controlling the axis
of class method or variable when it static you did
not create object of a class.
So basically for static
test you could see that we didn't create
object of a class. We didn't call static test
on a particular object of class.
It could be called directly. That's what static is all
about the static modifier for calling methods
and variables without an object
to which it belongs as we saw we
didn't create object of our fellow world we directly
cause the static method final is
nothing but you
can't change it final as the name suggests. You can't change it
once it is created.
So finalizing
the implementations of classes methods and so this is nothing
but instance variable
which we would be talking about the slides to come just to tell you this is
an instance variable
which we have assigned
the value 10 now suppose within this particular method I
try to change the value to 11. You would get an error saying
that cannot assign a value
to final variable. So final is like its final
can't change it once you have created it.
You can't change it. But if I remove this final you could see
this error would go off.
You don't see
this error anymore. Whereas by putting final
you would see this error. So that's what
final is all about.
So basically this is good enough
for constants, right? So if you have constants within your class you
would make it final
so that no one can change
it abstract is nothing but you could mention it as abstract when it doesn't
have implementation
of all the methods. So what I am trying to say
is abstract modifier is again a non access modifier
and what it tries to say is say,
for example, you have a shape class
cheap class is abstract class because shape doesn't say
you want to calculate
area of shapes. So basically shape class by itself wouldn't know what
the area of the ship would be.
Is a class where in the generic
class it doesn't know what the implementation
of area would be 4 Square. It would be Side Square
for rectangle its length
into breadth or Circle. It's pie R square. So basically shaped by
itself wouldn't know
what it's area would be but now shape is a super class
and say you have subclasses of it like Square you
would have Circle and so on.
So now basically
you want to ensure that when you create a subclass of the shape class
you want to ensure
that that particular class
implements the area that's when you create it as abstract. So the shape method would have
of the shape class would have
area method as abstract which would be implemented
by the subclasses which has to be ensured
its kind of ensuring
or if the subclasses
don't actually implement it you would get a error. So basically Circle would have
its own implementation of areas
in pie R square square. Would have its
own implementation saying Side Square.
So basically what I'm trying to
say is area is abstract method for shape class. And when you have
abstract method the class
itself is abstract. So you have like shape calm
down Eddie record dot shape. I'm creating a class now.
I'm creating a abstract method
So when you say abstract, you don't have
to provide implementation. It's just a chain break
this thing you don't have
implementation of it. You just have
the signature of it. So basically as I said,
when you have an abstract
method the class itself should be abstract. So we'll have to make
this abstract as well.
So you created a shape class which would have a area and
which would give you this thing. So basically we want to have
subclass and want to show
how the sub classes
are created at this point. But basically this is
what abstract is all about. You don't have
the implementation of it,
but you are ensuring
that subclass is implemented. So here you can see
Just a signature. You don't have implementation
unlike this implementation
is nothing but if you write something
within this braces, this is an implementation
for this particular method,
whereas in shape class. You just provided
the method signature, but we don't have
limitation of it.
So that's what abstract
is all about synchronized and volatile is much about using threads
synchronized is we are saying
that only one thread could get
a control at one point. So as we said threads are
nothing but parallel execution you could have
thread say for example,
you could have read
one calling a method. So we have as non
static method test right say this is a method.
So what we are trying
to say here is if it's synchronized we can make this a synchronized
private synchronized.
So this is what id is all about. So when you have this integrated
development environment, you don't have
to type everything
when you type S why you could
see synchronized coming up here. Put selected. So when you put
a synchronized here,
what we are trying to say is
only one thread could access it at a given point only
one thread at one point. So if multiple threads
are trying to access it
one thread has to wait for it. So only one thread
would get entry to this and the other thread
should wait for it.
So that's what synchronized is
all about and volatile. It's basically for
memory visibility or what we are trying to say is
so basically every processor
has got its own cache. So what we are trying to say is when you use a volatile access
specifier don't store it
in Cash Store it directly
into the main memory so that all the threats would get the most
recent value being assigned
to a variable also
volatile is not needed when you have using synchronized as such so it's
mutually exclusive.
So let's talk about variable. So variables are nothing
but it's a holder, right? Holds value and variables are
nothing but it's reference
to that particular meal or it's a dress or something that is pointing to a memory
location a memory location
where the squirrel use
are being stored and you could access it using
this particular variable name or you could access
the memory location
where the value is stored
using a variable name what I'm trying to say here is so this is a variable
and you could access
so this 10 is stored
somewhere in the memory and you could access this part
of memory location where this 10 is stored
using this variable
or you can manipulate it
as well can change the vat. So basically there are
three types of variables in Java this local instance class
or static local is nothing
but local to your method
whenever you have a method or you kind of create
a variable within a method that is nothing
but local scope which is
like it has the axis
its visibility only within that. Particular method once control
goes out of this method you can no longer access
is particular variable
that is local. So if I Define something
here say, for example, I Define something here.
So this is a local variable since its defined
within a method. So once the control you
would have this only
within this particular method, once the control goes
out of this method. This is no longer accessible.
Basically, this is where garbage collection
for Java is useful. Once you control goes
out of this particular method
garbage collector would kick in and were dean of this variable or clean of this particular
memory location or would make
it available for use. So that's the local scope. The next one is
instance instance is
nothing but something that is defined
at the instance level. So this is instance variable.
So since it's
at the class level, right this is you could see
it at the mid-level. This is at the class level.
This is nothing but
an instance variable now there is static variable as well. So this is how you define
a static variable.
So instance variable is
nothing but it's per instance so you could go and change
this instance variable to something else suppose.
I assign a value for T here now. I could have one more object
created suppose I call this object one
and I have Hello World object. So I create
one more object here. So what we are trying
to do is we are trying
to change the instance
variable through objects. So basically this is
what it is when you have an instance variable
normal instance variable,
which is non static
you could access it through objects, right? So throughout object one you
assign for object one you
assign instance variable value to 44 object to rinse
you change the instance variable value to 50.
I won't say Changed it. But you assigned it. This is how you deal
with instance variable.
It's at the instance level. It's at the object level. Whereas for static.
It's at the class level. It's one per class. It's not one per instance.
It's one per class. So basically what you can do
is you could do something of this sort where in its
at the class level.
It's not at the object level. You are assigning value hundred
to a static variable. So as you could see here,
it's not a particular instance that you're operating
on its the class directly just to give you a just
we have local variable
which is within a particular
method and scope remains within a method. Once the program control moves
out of this particular method
Java would or jvm would come in and kick in garbage collector to
clean this off Sony accessible within this menu you
have instance variable,
which is at the class level, but it's non-static
and which means that it has copy.
Per object when you
have multiple objects, you could change
the values the way you want per object static is nothing
but 1 per class and
as you could see here, we change the value of
the static variable 202 class. So that's about variables.
We have an instance. So instance variables
are declared in a class when the space is allocated.
I will just read
through this one. So when a space is allocated
for an object in the Heap slot for each instance variable
is values created.
We had a your instance variable and whenever you create
but basically an instance of a class is created
in a part of a memory,
which is called Heap. So whenever hello
world object is created a slot for this instance variable
would be treated as well
instance variables are created when an object is created with the use of keyword
new and destroyed
when the object is destroyed. So unlike local variables, which is within
the method scope.
Variable is within
the class scope. So basically whenever
you create an instance of a particular class,
your memory would be allocated for that particular
instance variable. And whenever it's done
whenever it's destroyed
by the garbage collector, it would go off access modifiers can be given
two instance variables.
You could have like
private public protected default all the access modifiers. We assign to students variable.
So basically you could have it as private private is just
within this class. You cannot access it
outside this class you
could have public as well, which is like would be accessed
anywhere within this application you could have protected
which is like within the package or the subclass and you can have
the default one which is nothing but package axis,
which would be accessible just
within this package that is calm dotted Eureka. So instance variable
have default values
for numbers the default value
zero for Boolean it is false for all. Big references it is null
so values can be assigned
during the Declaration or within the Constructor you
could assign values directly while declaring it something
like this instead of 0 is
the default one for integer as they have mentioned. But yeah, you could assign
if you put it as 10 here it would be taken
as a default value zero zero Constructor
is nothing but a method
which constricts an object of a class values can be
assigned during the Declaration or within the Constructor
instance variables
can be accessed directly
by calling the variable name inside the class. However, with static methods
when instance variables
are given access ability. They should be using
fully qualified name. So what we are trying to say
here is this is a static method
from which we are trying
to access instance variable in this particular
static method you need to have object reference.
This is Object
that we created so object reference dot instance
variable you need to have as we have mentioned here.
So here as we can
see object reference to a variable name. You need to have
fully qualified name.
When you try to access it
within the static method. You need to have
fully qualified name. Whereas here within a method
which is non static.
This is non-static here. I can access instance variable
without object reference. So here as we can see it
could be accessed without but
if I do it here it
would throw me an error. It's not accessible here at all. Non-static Fields instance
variable cannot be referenced
from static context
instance variables are not accessible directly here. It has to have fully
qualified this thing,
which is object reference
dot instance variable. Whereas when it's called within non static method you
could use the direct so static
as we spoke about
it's one per class, so it's declared. Using static keyword.
So static variables
are stored in static memory. It is rare to use
static variables other than declared final
and used as either public
or private constants as we said, it's mostly used for constants
and static variables are created when program starts
and destroyed when
the program stops. So one thing to remember
is it's one per class. It's not one per object
instance is one per object.
We have a copy of that
particular instance variable one per object case of instance, whereas case of static
it is one per class.
So the scope remains are
the life cycle remains right when the class is loaded
in the program is stopped in the class is unloaded static
variables are declared public
since they must be available
for users of the class. It's not mandatory though, but usually if it's
a constant it is declared
as public static variables
can be accessed by A calling with the class name. So we saw here last name
dot static variable.
So how do we decide what amount
of memory is to be allocated? So these are the data types
that we have. So each variable in Java
has a specific type
which determines the size
of memory the range of values that can be stored
and the set of operations that can be applied
to the variable data types
can be categorized into two major types
primitive and non primitive. So basically primitive
is not object primitive
is supported by language itself, which is kind of it
has got 8 primitive or its pre defined
by the language
and named as keywords and it
has 8 primitive data types that is byte short integer. Then you have long float
double character and Boolean.
This is pretty much similar
to other programming languages that you have by it
consumes one one bite. These are 8 primitive data type
set of predefined non-primitive.
It's nothing but string string
is object itself. So that's something that is non pyramid
or if we Define
your own class C student
for that matter here, right? We have defined student class
that's non primitive. So this student class has non
primitive you have strings
for storing string, which is again kind
of non primitive. We have arrays
or basically it's all
as reference variables since referencing
a particular memory location through variable name.
This is where we have table
showing white consumes one bite and it's range is from - 128127 short is like two bites
and you could imagine
that it would be
from - 32768232767. So it's pretty much similar
to other programming languages that you have like in C as well
we have similar to this thing.
One thing is characteristics
to bite in C takes one bite. I believe though. It doesn't use all
the two bites every time it.
On encoding type. So Boolean is one
which is true of all since it has to store 1 or 0.
So it's pretty much similar. So just to talk on the bytes
required by test 1 byte short is 2 bytes integer is 4 bytes long
is 8 bytes float is nothing
but it has decimal values
stored signed decimal values. So it again concerns for bites double is sign
again float values
or sign decimal values which consumes 8 bytes
character is 2 bytes and bullion is one bit.
So basically so decide whether to use float
or double depends on the nature of the application.
So if you want to have
more Precision or if you want to have more range
you could go with double so non primitive or reference
data type is a variable
that holds a particular
object or holds bit that represents a way
to access an object the pointer to a memory location baisakhi.
So as we spoke Java doesn't
expose the pointer directly. It doesn't give you directly
pointed to the memory location, but it gives you
the reference variable.
So you cannot manipulate
memory location directly. You cannot add some values to the memory location
through pointers or something
but through reference variable
you can access it and assign someone so yeah, it does not hold
the object itself,
but it holds a reference address to the object reference type
does not have size or bit range. So here we can see string Str
is equal to Ed Eureka.
So the one shown in red is actually the memory
we're dead Eureka is stored. You have a reference
and Str is the reference to it.
So here we can see
variables and data types. So we have a main method again
and we have bite. We declare a bite
here by D is equal
to 10 short s is equal to 20, so, I think it's
pretty straightforward. You kind of have this data types
created you just have
to assign values to it. These are all Primitives
as you could see till here. It's primitive so you could see
that values are being assigned
and it's been printed out here. So I think it's
pretty straightforward. You can assign a value
to a variable n just print.
So again, we use system
dot out dot println for printing it you
could try it out on your own. You could try it out
this data type program.
You could just assign something
and just try to print it out. We are talking about
data type conversions. So we have implicit
and explicit conversion in some case programmers
don't have to actually write explicit conversions
from one data type to other
but in many
cases programmers need so the arrow in the diagram shows the possible
implicit type casting
that a permissible bit
primitive data types. It's just with primitive data
types right as the diagrams. Those int can be converted
implicitly to Long float double
since int X likes less space. It could be applied to any
of the numbers for vice versa. They have to be
converted explicitly.
Whereas if you want
to convert long to integer, you have to
mention it explicitly. So basically we are talking
about when you're trying
to store integer into long
integer takes less space and long takes more space. So it should can
be easily accommodated
since long takes more space. If it is more than the range
of the integer. It wouldn't know
how to assign it to an integer.
So that's why it has
to be explicitly convert implicit conversions. We can on the J shell
you could type this.
So here what we are trying is we
have a character C is equal to a and you could see see is assigned a now
integer K is equal
to C. Which could be done
you could assign character to an integer. So basically it's
a ASCII code for it.
So 97 is the ASCII code for see
which would be assigned to K. So now when you
assign see to float, which works as well,
so you get ninety seven point
zero you could assign character to long as well, which is in bytes integer,
you could assign
double as well, which is 8 bytes float
and you could see but it cannot be done
the other way around
as we spoke. So you cannot have integer or you cannot have double
assigned to character.
So it would
give you incompatible our possible lossy conversion
from double to character. It has to be explicitly done.
If you want to do that need
of type conversions. So here we have integer
a full 200 initiated a variable with type Teacher then
you have a string B,
which is assigned value. Hello. So basically here you
can see string being used
which is a reference variable
and you have string s is equal to a plus b as equal to a plus
b then it adds up like hundred plus since hello is a string
it would concatenated
so you could see hundred and hello being concatenated
and you could see hundred. Hello the data type of both
the variables are different
but to perform any operation we
need both the variables to be of same type here integer value
is converted into string and gets concatenated
with other string.
So basically had we
been an integer you would have got edition of it say for example integer B is equal
to 200 and if you hundred
plus 200 you would get 300 but since it's a string in this case
hundred is converted into string and it is concatenated.
Hello explicit type conversions. We saw the previous case where an double was being
assigned to character
which prompted us
with lossy conversion. So this is similar to that. So basically here
what we are trying to do
is we are trying to assign double to integer. So you have double D
is equal to 45 B,
which is 45 right again
double is 8 bytes decimal signed decimal number so you assign 45 to it.
And now we are trying to assign
this double value to integer. So it's possible
lossy conversion, but you have a provision
to type Custer.
So basically what we're trying
to do here is you're trying to assign again double
to integer which is possible if you type casted so
when I say typecasting it's
nothing but opening parenthesis, then the destination data type
then your data. To a table.
So basically to the right
side you could see that through explicit
type casting we can assign double to integer.
So costing may lose information. For example, floating
Point values are truncated when they are cast two integers
example the value of D.
That is 45.5 when converted
to integer gives 45 so we could see here
the bottom like the double we assigned the value
of 45.5 to double
but when we convert
it into integer, we got 45.5 Force truncated
since double since integer since the destination data type
that's integer dozens
to decimal values. Now, this is like
type conversion methods which is there
any wrapper classes?
What we are trying to do here
is we are trying to convert 23, which is string into integer. So you have a string.
As is equal to 23 you
assign the value 23 so mind you this is this
is string right now. We have integer dot parse int
and we pass the string
which would be
converted into integer. So this integer class that you see here
right here is nothing
but butter wrapper class you
have string into an integer, which is nothing
but integer dot value of string which converts it
into digital data type itself.
So the you could see
the destination is is integer. Now integer to string
you have integer. We have a tostring method
which with converts
integer into string. So basically you have integer I
which is been assigned 23. Now you have
integer dot tostring I
which would convert
this integer into string. We have one more method which is string dot value
of which would also convert.
Integer into string. Let's talk about
operators operators are nothing but it operate
on this data types.
So you have unary which is kind of pretty
much similar to what you have C C++ you have post fix
and you have prefix post fixes.
I plus plus or expression plus plus and the operator is
after the variable which means that it would be assigned value
and then it would be added
prefix is before the operator which would be added first and then assign or the operation
would be done first
and then assign that's
prefix arithmetic is pretty much similar
like multiplicative you have like multiplication division and
mod you have additive which is
plus and minus you
have shifting operation, which is bits shifting
to the left and bit shifting to the right you have
relational operators less
than greater than less
than equal to greater than equal to. Instance of Quality
quality of two data types
or two variables which check whether they are equal
and not equal. We have a bitwise
and bitwise xor bit
wise inclusive or which is happening
at the bit level. We have logical
and logical or so.
Basically, this is
for conditions, right? If you want to have
like two conditions, like if int I is greater than 0
and int J is greater
than zero sort of you add or you have logical anding between two conditions
logical conditions
or illogical or
pretty much similar to other programming languages. Like it's or
between two conditions.
We say that either this or
that we have a ternary operator, which says that if the condition matches we
would have a condition followed
by a question mark
followed by colon, and we would have some value Followed by colon followed
by some other value.
So what we are trying
to say here is if the condition is
true assign value 1 if the condition is false
then assign value to so
instead of having it written in if else you try to put it
within turn your printer. So basically this is when you
have simple assignment operator,
if you have a logic if you have some particular
logic been written it would be a better practice to have
if else so that
it's readable right because ternary operator it would be very
difficult to actually
through we have
assignment operator which is equal to which is
plus equal to is nothing but adds the value
on the right hand side
to the left hand side
and assigns it to the left hand side table - equal to does the same thing.
It kind of subtracts value to the the left hand side from
the value to the right hand side and assigns it
to the left hand side.
So I believe this is pretty much
similar to other programming. Languages there's nothing different in this we
might have used it somewhere
or the else should be pretty
much simpler for you guys. So let's see
unary operator example when X is equal to 10,
so you could see X
been assigned value 10, you have X plus plus as we said it assigns first
and then increments it
so you could see
value 10 here again. So now if you after this
if you print the value of x, you should see
the incremented value.
That's 11. So that's post-increment. So, let's see pre-decrement.
So you have a been assigned
the value of 10. All right. Now, you do - -
A which is pre-decrement you
would see the value 9 directly. And now if you print the value
of a it would be nine again. So basically this is
like decrement and then assign
this is like a sign and then operate this is
like operate and then assign Let's see the negation operation
like a has a value of true now,
we negate it and assign it to the variable D
and you could see that it's changed to false.
Now. Let's see the
arithmetic operator. You have B
which has value of 20.
We have D which has value of 30. So when you add
it gives you value of 50 when you multiply it gives
you the value of 613 220
which is 600 when you divide it 30
by 20 you get value 1 and when you have mod,
which is like remainder, which gives you
value 30 by 20, which is equal
to 10 shift operators are
so it shifts to the left
so shift left shift, right? So basically you have
integer value of 20 and if you convert this into binary
if you convert the 22 binary which comes out
five digits, right? So when you convert this binary
and when you shift,
To the left you would get
the value of 80. So you have value 20, which is nothing but if you
convert this 20 into binary,
which would give you
one zero one zero zero right. Now, what we're doing here
is kind of Shifting it to the left by 2.
This is what you do and this is
what it shows up as value of DT. So this is nothing
but 64 plus 16. So that's what this
left shift does.
Basically it shifting
to the left by 2. Again, you could have shifting
to the right by 2 by 3, which would give the value
of to just shifting
to the right by 3 would be
something like this. Right? So you're basically it shifts it
and you could see that.
Yeah, basically it
would end up to 2. So now we have
like relational operators, which is pretty much simple
like a less than b.
It gives false a greater
than b equals equals P. Since you have a is equal to B. In this case.
We have a equal to B. That's why we have a
less than b as false and a greater than b as false.
But whereas a equal to equal
to B is equal to 2, we have arithmetic operators
pretty much similar. Basically you have ad you have
multiplication you have
division you have mod. So here we have
a is equal to 20. So what we are trying to do
is assignment so a is equal
to 20 now B is equal
to 40 a plus equal to B, which is nothing but as I said,
your left hand side would be
added up to the right hand side and would be assigned
to the left hand side, which is nothing but 20 plus 40
would be assigned to a so
when you print a it would print
60 ternary operator, which is nothing but if a is
less than b here we can see that if a is less
than b then the value
of Should be assigned to tr
or the value 200 in this case. The value 200 is been
assigned is greater than b logical operators
is nothing but anding
and o-ring of conditions. Yeah, here we are saying that a is less than B
and D is less than b
then return false and it's like kind of
ending logical conditions. Now, let's talk about
the control statement in Java.
Now again, this one
is pretty much similar to other programming languages nothing different nothing
different in Java.
So you have control statements
you have I treat if statements you
have jump statements. So one is selection
or decision making statements,
which is like if else
if else ladder you have if if this particular condition
satisfies do some things do some execute group of statements
and if it doesn't then execute
other group of statements that is about if else Which is nothing but
based on the value of a variable
like you to execute
different step of statements like say for example, you have you write a switch
on Integer value
integer variable X. Now when X is 1 you do
something or if x is 0 you do something or you can have
a default statement as well
when X is either 0
or 1 do something else that supports which I tradition is you repeat the same set
of statements again,
and again till the condition till a particular condition
is met that's a titration. So you have four Loops,
which is like after every
iteration the value of variable or the iterating variables
would be changed and would be checked
against a condition and
if it meets it would come out or if it made it
would execute it again, and if it doesn't mean
then it would come out.
So yeah, this is pretty
much similar to other. Other programming languages. So for for INT I is equal
to Z 0 is less than 10.
I plus plus and you write
something within it. So this Loop would go on
for 10 times from 029.
It would break it would come out when eyes greater than 9
which is 10 when it goes to 10. It would come out
while is again pretty
much similar to that. You have do while construct which is guaranteed
to be executed once
because the condition is checked after the execution is done once so basically no matter
what the condition is.
It has to be executed
once for sure. That's when if that's
the behavior you want to put into your program you would use
to Y is equal to once for sure jump statements
you have like break which come out of for
Loop Komodo for Loop
or any attractive statements
you have continued which would again continue
and return is again coming out. Of a method or are mostly
from the methods
you written something so the control leaves
the method now just to give you what if Wells is
if if the condition is true,
then then execute
the conditional code. If the condition is false come out of the execution or come
out of the conditional code.
Skip the conditional code. That's what if else is
so here you have int I is equal to 10 and
int b equal to 20
if I is less than b so it's pretty much similar to
the ternary operator that we had so you could see here
TR is equal to a plus b
so basically the value if a is less than b
which is in this case a is equal to 10 and B is equal
to 20 in that case.
You would have PR as
30 since it is true. So basically it checks
the condition and if the condition is true it
executes the code with now
let's talk about If else if it if else construct is nothing but you have a is a set
of statements to be executed
when the condition is
in satisfy succeed. So in this case if a is less than b TR is equal
to a plus b else TR is equal
to B minus a so in this case
it was less than a is less than b so you
got the value of 30 whereas if a is greater
than b we have again changed it.
So if a is greater
than b then TR is equal to a plus b else TR
is equal to B minus a so in this case a is less than b so
which means CR
should be B minus a which goes into the
else condition statement and here you have
20 be as 20 and a as 10
which is 20 minus 10. So you should have PR as 10. So here it's pretty much same.
It does the same thing
nested if-else now, we are talking about
the switch statement. So you have switch expression
and you would have case written
against it whatever case
you want to execute. So basically you
would have for Value 1. So yeah,
what we are trying to say here
is we have a switch expression and we have a value for Value 1 as its value then
execute this piece of code
and then break out and if it has value to then
execute this piece of code and then break it doesn't match
with value 1 and value to then
executes the default cases. So one thing to note here is
it's mutually exclusive only one of it would be executed
out of the cases.
Make sure you break out of all the the conditions so
to the right hand side you could see integer
CH has a value of 40 now.
We have a switch for 40 now. Is when the value of CH
is 20 it would print case 20 executor
when its value is 30 then we
would have case 30 executed when its value is 40 then we would have
case 40 executed
and then break out and if it's neither 20 30 or 40
we would have a default case is executed with says
that 20 30 40 not executed. So in this case since it has a value
of 40 you would see
that case 40 executed as
output I'd frisson is nothing but it is basically
I treating code if a condition is met
the the code would be executed
until the condition is true. The code would be executed
and once once it is false, it would come out of the loop.
So basically it's
a looping statement. So after every Loop
the condition would be checked and if the condition
is true it would loop again.
And if not,
then it would come out. There are three types
of for Loop in Java simple for Loop similar.
See like for INT I is equal to 0 I is less than 10. I plus plus would be
a simple for Loop for each
or an enhanced for Loop
and labeled for Loop for each is basically I treating on array list suppose
you have some collection
or suppose you have a re right? You don't have to
manipulate the indexes since the typical scenario
with arraylist is I treating
through all the elements within the list. So we have an enhanced
for Loop wherein we don't have
to actually deal with indexes. Java has come up
with a enhanced for Loop where and what each iteration
it would assign the value
of each element
within the array to a variable which could be used
within the loop. So we don't have
to deal with indexes
like we don't have
to Loop through till the sizes met in the loop through in the size
of an array is Matt,
basically it Done
by Java itself. We have an example
which would clarify it. So simple for Loop is
as I mentioned you have
for INT I is equal to 10 is greater than 1 I minus minus so it
would print from 10 to 2.
That's a simple for Loop. Now. What's the Syntax for it is
for then open up round brackets.
Then you have initialization. Then you have a condition
and you have increment or decrement whatever
you want to do
or you could even add up like I plus equal to 2 even
that is good enough. It's like for each even number
not even I would say it's
like incrementing by 2. Now. This is what I
was talking about.
So this is for each Loop
or enhanced for loop. We're in a typical
scenario with array. You kind of eye to it
through each element
within the array and then do something
within the loop, right? So this is what Java
has made it easier for us.
So basically you don't have
to deal with indexes here if we wouldn't have had
for each Loop. What you would do is
you would tell the size
of the array is Matthew
would I trade through and read from each indexes right? But in this case
as you could see
there's an array and for each Loop the value within the array would be
assigned to this variable
and you could use this variable within makes it pretty
much simpler for us. And as I said,
this is typical thing that we do with arrays now labeled for loop it's not
recommended to use this often
but still we have
this construct here. So basically it's like go
to we can have a label of each for Loop.
It is useful we
have nested for Loop so that we can break
or continue a specific for Loop normally break
and continue keywords continues
the innermost Loop innermost for the loop only to give
Behind why I mentioned that this should
be used often is
because it becomes
very difficult to debug right? If you dry run it
if you use this labels, it becomes very difficult
to actually understand
what's happening within so
so we should avoid it and all this could be done
by writing a proper construct. Sorry using simple
for loop as well.
So we should avoid it
somehow so basically as per my experience is
not a good practice to use them. So type of while loop we
have SIMPLE while loop
we have do-while Loop. All right. So simple wire Loop is first
the condition is checked
if it meets then the looping
statements are executed whereas do-while Loop is kind of
the statement is executed once for sure and then
the condition is checked
if it is met then
it is looped again. If not, then comes out. So this is a simple while loop
so you have conditioned
as you could see here while a is greater than 1 you print the value
of a and you increase
decremented Within Here
it's a do while loop so no matter what you
would have this to printer and it would be incremented.
So it's 2 to 9. So no matter what some value
would be printed for sure when you use do I now
we have jump statements,
which is breaking slyke
coming out of a loop. So as we mentioned
it's the innermost Loop that it comes out of
so that's what Brave does
if a particular thing is met
or you could write a condition for a particular Loop
to be broken rather than continuing it.
So basically you could have
like this would be more or less like you could have infinite Loop say for example
running through and
if a particular condition
is met you could break out of it a typical scenario where it would be used.
So here you could see
that you have a loop from 10, which I traits from where I is equal to 10 and
where I is greater than V i- -
which we are
decrementing each Loop. Whereas you're saying that if I is equal to equal
to 7 we should break out.
So here you can see though eyes greater than 5 you can see the
loop has broken out after 8:00 since the value
has reached seven.
It's not printing
the other indexes because it broke
out of the loop. So basically this is like
if a particular condition is met and you don't want the loop
to go ahead you can break out of the loop
continue is similar
when you write continue, it goes to start
of the loop again, it starts the loop again
and it skips the messages
or it skips the code that you have after continue. So in this case you could see
that we have I equal to in case
when I is equal to equal to 5 We are continuing the loop which means the print statement
for I when I is equal
to Phi wouldn't get executed since you're continuing it. So basically as you could see
the News being printed here.
You can see the 01234 and there's no 5 here
then we have 6789. So basically what we
are saying here is
when I is equal to 5 don't execute
the statement within the loop. Just continue.
Just keep it. Okay. So what a methods
in Java So method is
if you would have written function or if you would have
used any programming languages if you want to
perform some operation
if you want to do something or if you want to do something
on some particular data, you would write a method.
So basically in Java methods
are defines the behavior of a class. So remember I told
you a class is all
about State and behavior. So methods are nothing but it
defines the behavior of a class. So what are methods or method
has a group of statements?
Of course, as I said, since it defines the behavior
of a class you need to have some operations done, right?
So you define the operations
through group of statements. It is much more used to have
reusability of a block of code that minimize redundancy.
So imagine if you
didn't have methods then you have written the same piece
of code again and again, Say for example,
you have a method
which adds to number right? And if we write the piece of code to add two numbers
directly into the main method
if you want to write it again, or if you want to again
add two numbers, you will have to write
the same piece of code again
in the main method. Whereas if you have a method what you would do is
you would refactor
and take this add
method or functionality which adds two numbers into a method and this method
could be invoked from anywhere
within the application which is nothing
but re usability right rather than writing
the same piece of code.
Now, what you are doing is you
are defining this add method into some other method which could be called
anywhere within the code.
So that's about redundancy that minimizes redundancy
and increases the reusability of a code a class
can have multiple methods
as you could imagine. You could have
multiple behaviors introduced into a class which means
that you would potentially have
multiple methods within a class. A method returns a null or a value using
the written statement.
So basically the intent of the method is to perform
some operation, right? So what method would take
is it would take parameters
and do some operations
on these parameters and it may or may not return something back
to the calling program.
So if you don't want
written anything you have to return null or if you want to return some value
you could have say for example,
you want to return string
you would return a string of a method you
could have void as well, which means that the method
is not returning anything back
to the calling program. It is doing something
within itself and just the control would be back
to the calling program,
but it won't return anything
out of the method that's about method. So let's talk about so
what the syntax
of method So the first one that you see so this is a method which is public int
at Eureka integer a GB
and it is just concatenating
the two strings or two numbers that we have sent a cross. So basically let's
an itemized it
so what is public
so public is nothing but again access modifier so public means
this particular method
could be accessed from anywhere
within the application. So that's what public
means similarly you could have private.
You could have default scope or
you could have protected scope. So public is accessible anywhere
within the program private is within the class default is
within the package
and the protected is
within the subclass and the package. Okay.
What is this int it is nothing
but the return type so this particular method
is going to take two. Arguments and do something
and written integer,
right name of the method
is you can see ID Rekha. That's the name of the method. Okay.
So what do you see
within the parentheses after the method name is
nothing but the arguments that this method takes so
what this particular method is doing is it
is taking two arguments which it is acting upon right?
So it takes integer
a and integer B, that's the parameter list. So whenever you want to invoke
this particular method you have
to pass arguments in this order. Now, what do you see within
this curly braces is nothing but the behavior or this is
how you introduce a behavior
to the class or this is how you add functionality
to a method. So what you are doing
here is kind of adding
these two numbers. So what is
the written statement? What does it do?
So written statement is nothing but you do something
you take the arguments whenever controlled comes
into a particular method.
It does something and you return it back
to the calling program. So the written statement
is a control flow statement
that terminates the execution of method and written
control to its caller. So when return type
of any method is void,
then the method does not return
anything if it is void, you won't return anything out. But if it is written in string
or something you
would return string or null if you land
not to return anything, it could be null as well.
So here we can see
a method by the name work which is returning void. So you can see
that it is not taking
any arguments as
such or parameters, but it is just
printing out saying that I do recall welcomes you
in the second case you
can see it is written integer. So it's taking int A
and B. Okay, and then it is printing out
and it's returning
integer as well. So let's write a program sample
program to add two numbers and we would be writing all
this logic within a method.
So let's start off
by defining a class. All right. So we define a class
say calm dot edu,
Rica Dot and a typical name for
all arithmetic operation glass with all arithmetic operation
would be calculator, right? So I would write
it as calculator.
For example. Alright, so here you can see
the naming convention again. There's a package
which is calm down
at Eureka and you have
a class has calculator and it follows camel casing so it starts with upper case
followed by lower case.
So you can see the class
is being created here. Okay. Now what we are trying to do is
you are going to have a method
which takes to number. Okay. So say I Define
let's keep it public.
All right. So this is access modifier. We want to keep it public.
So you want to access this particular method from
anywhere within the application. So I'm keeping this public.
So typically addition
would return results, right? You would add two numbers and return results
of two numbers.
So that's your written type
which is integer. So you could either write
the return type as primitive or you could write it
as a wrapper class.
So basically wrapper class
is nothing but integer has its own everything
in Java could has to be realized in terms of classes.
So integer has its own class int
is a primitive data type and integer that you see here. Is a class corresponding int
so let's put the return type
as integer and add is
a method name. Okay. Now this takes two arguments
integer arguments,
which is arg1 and let's put
the second one as arg2. All right, so we start
and ended by curly brace. Okay.
Now we have to write
logic within here. So what you see here, it's throwing an error
saying that you
are not returning integer out. There is a missing
written statement because in the signature this
is known as method signature
this particular thing that we have defined
here is Method signature. So in the method signature
you have mentioned
that this particular add method
is intended to return integer out of the body, but still you
haven't written integer.
So basically to get rid
of this I could put written null which means it's doing
nothing now you can see that Got rid of the error.
So let's do one thing just
to make it more verbose. I will write integer result
is equal to ARG 1 plus ARG 2. So this is a method body
that you are defining here.
So you are adding
a behavior, right? You're giving Behavior
to the calculator class. So by defining add method
this certain behavior
that you are introducing now, you could have
a multiplier method as well which would take two numbers
and would multiply it
which is again giving some sort
of behavior to calculator. So that's the reason we say that methods add
Behavior to the plus.
Okay. So here it is taken two
arguments arg1 arg2 adding it and we will return
the result from here.
All right. So this is a method
that you have defined. But so far we are not invoking
this method right?
We are not calling
this method you want to call and check whether
it's running as expected. So that's where we
would have main method right?
When you type mean it should
give you suggestions saying that are you trying
to write main method? So if once you click
on it it would this is done by
IDE by the IntelliJ
similarly in Eclipse. You would get an option, you know, it would give
you suggestions saying
that we want to
introduce main method. All right, so we have
a main method here. So again, it's
public static void Main
and it's taking arguments here. All right. So remember I said
static and non-static
Method you can see
here add is non static method when it's a non static method
you have to create instance of this class to invoke it.
So basically first thing that I do is I create
instance of Later, so how do you create
instance of calculator?
It's with new keyword. All right, you create new and it would create
an instance of calculator.
Now I give a call to add method and suppose I want
to add like 10 and 30. Okay.
So these are the arguments and it has to be
in order in this case since both are integer.
It doesn't matter but had
it been some other data type. You have to ensure
that say for example, I write string here
what this would return
is typically a result right addition of two numbers. Now, let's print it out
system dot out dot println.
This is for printing result of addition is flits
print out the result that we get here.
All right, and let's end
it by semicolon. So basically you have
a package defined here within the package
you have calculator
and actually it's my bad. I should have defined
it right here. So it gives my it gives
the right package name here.
So earlier I had defined calculator with income
dot Ed u-- Rica again. I defined a package computed
Eureka which is not required.
So yeah, you can see here
packages calm down said Eureka which is nothing
but the namespace we have public class calculator.
So public is nothing
but the access specifier for this class plus is the keyword used
for defining class
and calculator is
the name of your class. Also one thing
to note is the name of the Java file should be same
as the name of the class.
So that is something that IDE or IntelliJ
would do it for you. You just have to create class
and it would create class.
So basically if you go
to the source folder you would have something
like calculator dot Java right? Then you have public method
which is again,
here's the method that we have defined public
is the access modifier for this method integer
is the return type add is
the name of the method. It's taken two arguments
arg1 arg2 within the body you are adding two numbers
and you are returning result
which is integer which aligns to the signature
that you have put here. All right in the main
method just to check
whether this add method
is functioning properly. What you do is you create
the instance of calculator. You add two numbers you
pass two numbers to it then
and 30 and we are going
to print the results and see if it returns as expected. So here basically it
should print the result as 40
since adding 10 and 30. So remember while it
builds it it would compile into a class file.
Okay, the dot Java file
would be compiled if it's properly written
if it's in tactically, correct, it would read dot class file.
All right, let's wait
for it to run. Okay, so it's
prompting me errors that we have an other methods.
So let me do one thing. Let me delete other classes
that we defined yesterday. So I get go to the
source folder Comdata.
Directa. I So I am just
deleting this classes that we defend yesterday.
So that we don't spend time in
actually correcting it, right? So put it into a backup folder. All right, so
Okay, so we have only
this calculator class now I run this. So yeah, you can see here.
It has been tested result
of addition is 40. So basically what it
has done is adding these two numbers 10 and 30.
All right, so that's
what we have here. So we are adding two numbers. So let's talk about the sequence
of how all this is being carried
out by Java right when you run
a particular program how things work out
when you run a class.
The first thing that's been called
is the main method. Okay jvm is nothing
but Java virtual machine
which runs the program for you which is part of JRE
Java runtime environment. When you run a particular class,
it would search for a main method and
if it doesn't have a main method then it
would give you an error saying
that a class can't be run. So it's pretty much similar
to executable file, right? So if you're trying
to run a class it has
to have a main method or you won't be able
to run the class directly. So that's where
the execution starts from.
That's the entry point
for your program. Okay. So once it encounters Main
and everything is good
your jvm would start executing the statement. That are there
within your main method.
Okay. So in the edition case that we saw within the main
method we invoked we created
the instance of calculator
and we invoked add method right? So when we ran that particular
class you could see that the addition was done.
So basically what's happening
behind the scenes is, you know jvm would execute
the sequence of statements that you have with a name.
So again coming back
to the example add example So within the main you
invoke the add method right when you invoke add
method the control would go
to the add numbers method and it would again
execute whatever functionality you have put within
that particular method this case
it was addition of two numbers. So it would execute
once the execution is done. It would return whatever
is been written out.
So in this case, I was was addition
of two numbers, so it would return addition of
two numbers back to the calling.
Program so you're calling method was the main method wherein you
called this add numbers from? Okay, so it would come back
to the main method and that's
how it prints it out. So following the invocation
of add numbers you could see that we have printed
out the visual
that comes out of
this add numbers and that's how it gets printed
onto your console so that the sequence of execution
that happens behind the scenes.
Now what are the ways in which
you could call a method? There's call-by-value call by value is nothing but instead
of passing the memory location,
it passes the value
of a particular variable. Okay. So this is similar
to call-by-value and
call-by-name reference that we have in see okay, instead of passing
the memory reference or instead
of passing the reference. It's just a value
that's been passed. So if you change something
within the method or
if we change the value that's been passed within the method only
the local copy would change
whereas the main copy
would remain as is but basically call by value
is just passing the value but not the actual reference.
All right, so to understand
call-by-value you could so this would give you some idea.
So say for example, I have integer ARG
1 which is equal to 10 integer ARG 2
which is equal to 30.
Okay. Now I pass ARG 1 comma arg2. So what's happening here
is it's passed by value.
So suppose you change. What I'm trying to say is here if you change arg1
to something else 300.
Okay. So what we are trying
to do here is we are trying to pass this to arguments
arg1 arg2 to add method
and within the add method we
are changing this arg1 200. Basically we would check whether this hundred
is been reflected in arg1 here.
Okay. Arg1 here would
change 200 as well. Let's see what happens here.
Okay, so I print it. Okay before passing it by value. So I print arg1 here.
Okay, and after I give a call I would again printed
printing arg1 after busting it a value to a method
add Method All right,
so let's run this so basically since its passed by
value arg1 would remain as 10. Okay, so that's what pass
by value is all over.
So here you can see arg1
before passing was 10 and arg1 after passing was again 10. Alright, so the change
that you made here
doesn't reflect here. So that's pass by value. All right.
So this one more concept of
method overloading with in Java. You could have same methods with different number
of parameters same method
when I say same method
it has The same method name which would take variable
number of parameters. Okay, the overloading happens
at the compile time itself.
So during compile-time jvm
understands to which method you are actually giving a call based on the actual parameters you
pass on so just to give you
a fair idea about this I
Define one more method. C ad which takes
say integer arg1, let's keep this adders.
So I defend
three parameters here. So instead of two I Define
three parameters here. This is nothing
but method overloading.
All right. So here I Define ARG
1 plus ARG 2 plus arg3. All right, so we sum it up here
and we return it back
to the calling program. So one thing to note here
is it's not giving you compile time error, right?
So you can see that it has accepted
this add method as well. So you can see here.
The signature is
pretty much same only thing is we have
one more extra parameter, which is a RG3.
So it is treating this true
methods as a different method. That's what method
overloading is all about suppose I Define
one more ARG pee I say 40.
Alright, so we have
three parameters here. I am giving a call
to add arg1 arg2. If I put arg1 arg2 the first
add method would be called
if I have one more ARG 3 now
the second add parameter or the second add method
would be called. So let's define result
from new add method, right?
So here we say. Okay. So as I said,
we have overloaded the add method overloading is
nothing but same method name but different arguments
or different number
of arguments or it could be
different types as well. You could have only
two arguments but one is integer and one is something else
if for example string that also works so basically
different data types A number of arguments
but different data types or
different number of arguments. Alright, so here we are adding three numbers
and let's run this.
So it's going
to add 10 30 and 40, which is nothing but a tea. So this is done
at the compile time.
As I said this linking is done
by GBM at the compile time. So here you can see results from new add methods
80 during runtime.
You can see that it invoked
this particular method and not this one. Alright now, let's start off
with arrays, right?
What is the concept of arrays? So again, this is similar
to other programming languages arrays are nothing
but grouping data
or grouping values
of same data-type. Okay. So arrays are used
to solve the problem
of storing multiple elements
of the same data type. Okay, an array is group
of like typed variables that are referred
to by a common name.
So you define a name
for the array and in the future you can use
this name to access it. Okay specific element in an
array is accessed by its index
as you could imagine since we are grouping you
would have multiple elements, right you could add
something to it
or you could delete something or you could add it to the end insert it
in the between of the array
or just so something or just search by index rate
you would give some specific index and get element
from that particular index.
So we would be looking
at the Which would give you a clear idea about this but basically array
is nothing but group
of or its multiple elements of the same data type
array type is fixed and cannot be changed.
So in Java when you define an array you either give
the number of elements that you can store in the array,
which is nothing
but the array size or you have to give the values that a particular array
would contain right
when you define it. Okay, but all in all
you have to make sure that when you define an array
you give the size as well
which cannot be changed
the feature the size of the array has to be mentioned
during the Declaration itself. So here's an example
of array this array has around
for which has four subjects
with stores marks of four subjects for a student. Okay?
Here you could see indexes
in the white box, which says 0123 it's
always in sequence. It starts with 0
and it ends with n minus 1.
So basically this array is
of size for which starts from index ranges from 0 to 3. All right the value
that is stored is nothing
but the that's a marks
in a particular subject which is like 87 60 70 and 80. That's the value
that when stored
into this array. Okay, we can access any of this indexes suppose
you want to access
at index 1 you could do it. Do you need to define a front
you need to Define on the size of the array of front?
This is how it's been done. Okay. So this is
how you declare array.
So we saw how we
usually declare an integer and stuff like that in Java. But here we are
declaring an array.
All right. So this is an integer array and you can see
square brackets here.
Alright, this tells jvm that we are trying
to Define array of type integer. Alright.
So again, we use
the same keyword which is nothing but Nu new keyword is used
to create a particular array.
All right, and here we are defining
an array of size five. So this is one way
of declaring an array.
The other one would be
who initializer itself when you declare it
you give what are the values that particular array
is holding up the first case
you're not giving the values
you are just defining an array which Those some some amount of memory right jvm would
reserve some amount
of memory or in this case. It's four bytes right array. So for integer,
it takes four bytes.
So it would Reserve 20 bytes
for array of size five. All right. So in the second case as I said,
it's directly initializing the array it's putting
these values directly into the memory location still
it would be consuming 20 bytes,
but the second variant
would have values directly initialized. So when you declare an array
of size 5 the range
of indexes would be from 0 to 4. If you try to access index 5 you would get this exception
exception is nothing
but a anomalies situation
right which or something which is not expected as occurred in your program
and Java expresses such event
by throwing out an exception. You can't access index fi. So different ways
of declaring an array.
We saw that it's
with new keyword. All right, so you have new int
10 which would declare array of size 10 again.
You could either have
the square bracket at the end of the variable or you could have it
in between the type
and the variable name. So behind the scenes it
everything is the same. It doesn't do anything
different for both
but these are different ways in
which erase could be declared. All right, the third one
is similar to the last one where in we have
BR initializing it directly.
Alright, we are putting
this value 12345 into this array. This one is again same you are
so within the square brackets,
you can see that you are not defining
the size of the array, but you have an initializer
at the end by which you express
that you want to put in
1 2 3 4 5 into this array. So basically one and two That
you see here does the same thing it declares the array of size.
The first case is 10
the second case is five though, but behind the scenes
it's doing the same thing. It's nothing different
when it comes
to actual preserving memory
and stuff like that. It's doing the same stuff and three and four
does the same stuff
only thing is syntactically it's varying but
what I'm trying to say is GBM doesn't do anything
different to actually executed.
So the length
of the array is set when it is declared and when an array is declared
array index gets initialized.
All right, so if you define an array and
if you try to print the length of it you could see
that it prints out in this case.
We have declared
an array of size 20 and when you do x dot length, when you print it out you
could see that it prints 20.
All right. So what are different types
of arrays that we have again similar to what we have
in Programming languages,
we have single dimensional array and multi-dimensional array
single dimensional array is what we saw earlier
like you define array
of integer of size 5 that is
a single dimensional array. So in this case, you could see a array
been initialized with value
2 4 6 8 and 10 that's
a single dimensional array since we have just
one dimension one row right? Say for example,
you want to store marks
scored by a student or marks towed by a particular
student just one student. That would be
a single dimensional array.
All right. So say for example, the first one is
the marks code in math.
The second one is the sign
and so on and so forth. All right, so
that single dimensional array. So now what's multi-dimensional
array so taking the same example
of storing marks code
by a student. So by a particular
student it would be a single dimensional array,
but suppose you want
to show your marks code by all the students
in all the subjects. If you want to store it,
it would be
multi-dimensional array. So one particular row that you see here would be
a mosque secured by a student
by just one student
in all the subjects. The first row would be
by student won. The second row would be
by student to the third row
would be by student
3 and so on right? So that's where you
have this application of multi-dimensional array.
So how you access it is nothing but you want to access
the first element the first index it
would be a of 0 0
and this would be of 0 1
and so on so as I said if the First Column is for math if it's a marks secured in math
this entire The First Column
that you see would be marks secured by all
the students in math. That would be the First Column
whereas the first row is
the Mach secured by student a in all the subjects. So basically This
Could Be Imagined as
a table in a database, right you have a table
where in you have rows and columns so
columns are nothing
but you have Fields
within a table and the rows that you have
our different entries that you have within a table.
So This Could Be Imagined
in the same way. So you could see
how the index is you could see how the indexes
are aligned so X increases
when you go down and Y increases as you go to the right
the memory allocation of array, so for single dimensional array
of type integer,
1 integer value takes
four bytes, right? So now when you declare
an array of size 5, you would have 20 bytes Reserve.
That's how memories
been allocated right if you have a character
array of size 5, it would be ten bites
since each character
takes two bites in Java. So you would have
10 bytes reserved up front. All right, so that's
about memory location a location
in single dimensional array and when it goes
to multi-dimensional array this case you have
like five elements,
right you have array of 55, which means that you have
25 elements stored within the array
right 25 integer element
stored within the array and each integer value takes
four bytes for storage. So it would be a hundred bytes.
All right, so if you have array of if you
define a multi-dimensional array of 5 into 5,
you would have basically a
hundred bytes allocated for it. Let's write some programs and understand more about
how this arrays operate.
So we have an array
of five elements. All right, as you could see here 2 4 6 8
and 10 write a program to access
element at a specific index. Okay, so you have an array
of five elements 2 4 6 8 and 10 and we want to access it.
We want to access
particular element. All right, so let's write
so I create a class. All right, I Define
this as our a demo,
so I don't give
a package name here because I am defining
a class within a package so you could see here
the package came directly
because I right
clicked here right and then created a new class. So yeah, you get
this particular class here.
I Define a main method as a type main it
would give me a suggestion. So this is the entry point again
for this particular class
and suppose I Define the jar. Ray and suppose
I Define 2 4 6 8 and 10, right so you could see here.
We have an array
defined of size five. Okay, and you have
initialized it as well. So what I was trying to say
is you need to have length
of the array given
up front right? If you don't do that, it would show you an error
so you can do something like
array of integers is equal to Nu so you could see here
array initializer expected. All right.
So either you will have
to initialize it or give some value to it. So if you put here
10 you could see
that it compiled right? So either you will have
to mention some indexes here or the length size
of the array or the ways
to initialize this okay. Now you could see
the compilation error as gone. So what I'm trying
to say is it jvm has
to know about the size
of the array of And if it doesn't know then it
would flag you with an error. All right, so we have defined
this array of let me keep it
as is okay. So now we have defined
an array of size here five and we have initialized
values as well.
Now, let's try to print
out values, right? So just to keep
it simple suppose. It ranges the index
would range from 0 to 5,
in this case. So this value to is stored at index 0 value for is stored
at index 1 value 6 is stored
at index 2 value
8 is stored at index 3 and then is to that index
for all right. So let's try to print
0 by the way.
I want to copy it. Yeah, so I'm just sprinting
0 1 and 4 and let's see what it gives up.
Right so it should print
2 4 and 10, right? So you could see
here to 4 and 10. Now.
The other thing
that I wanted to show is if you try to access
so let me show you what happens there.
All right, so if you try to access at index
5 which doesn't exist at all. No, it should give
you a exception So
in Java exceptions could be nothing but God and you
could do something with it. So here you could see
that it gives it gave you array
index out of bounds exception since five doesn't exist at all. The index five doesn't exist
at all for this array.
Okay. Now let's define
multi-dimensional a write code to find the length
of rho 0 right.
So let's define
a multi-dimensional array. Alright, so we have
a multi-dimensional array here. So how you define
multi-dimensional array is
something like 1 2 3 4 Alright, so this is a multi-dimensional
array that you have. Okay, so we have defined
a multi-dimensional array
the size of this array
would be 2 by 2. Right 2 by 2 is
the size of this array since you have two elements here
or let me put it
to remove the confusion. Let me put it this way. So right now we
have like 2 by 3,
right so you have like
two columns and 3 rows. All right. So now let's print actually
it has to be 3 by 2 rather.
Okay. Now, let's print the size
of this array 0 right. So how we do it is
again println now you
have multi-dimensional array and you have 0 so 0 to 1 refers
to this 0 1 and 2, okay.
Dot length, so as you could see
here that individual row that you have
within multi-dimensional array
itself is an array is
a single dimensional array. So multi-dimensional array
is nothing but it's a array of single dimensional array.
Okay. So let me print here
size of first array. I miss Plus.
So as you could see here, there was an exception
and since there was an exception you won't have this
particular statement executed
since there was exception here. So basically to execute
this particular statement, you should handle
this particular exception,
but we are not talking
about handing the exception yet. So I'll have to comment
this to pass through. So now you could see
that it has printed out to which
is your size of first array. So this is a program that we actually did right
now create an array having
many characters write
a program to copy elements from created array
to another array and also write a program to
delete an element from an array.
Okay, so I will just talk
about this right here. So we have an array here
of characters, right? So basically when you want to
delete something from my array,
what you will have to do is you will have to shift
the indexes, right? You can't delete something
directly from an array.
So what you will have to do is if you want to remove
something then you will have to shift the indexes
what happens is suppose you have
an array of five integers and suppose you are deleting
the second element right. Now.
What you would do
is you would shift if you are deleting
the second element within the array you
would shift all the elements
that follows the second element
to the left, right? So the third element
would become the second element. What would become third
and the fifth one
would become the fourth. So basically you shift it. That's how you delete
something from an array.
All right. So other thing is about copying
elements from the array, we have a utility class
which is nothing but
system system is a class itself. So as you could have seen that when I'm printing out
something I do system dot
out dot println, right? So this system it's
a utility class in Java where an IT exposes lot
of functions within a lot
of methods utility methods. So one of them being our a copy, so here you have to give source
and the starting index
and the destination and what we are trying
to do here is copy 5, so this is how we copy
from one array into
another starting from index 0. So this is copying
and the other one that you see here
is about delete.
So as I said deleting is nothing but we have A logic
written here to shift the indexes to the left.
So here we are trying
to delete one at index 3 and we are just shifting elements
after this index 3 to the left. That's how we delete
something from an array.
Now. Let's see what our strings
so string is nothing. But again the data type
with in Java.
So why do we have strings at? All? Right.
We have array of characters then
why do we have string at all? So here's an example where in you have lot
of loads of data?
So you could imagine
a role of a data analyst who has to analyze through lot
of data coming in right? So nowadays, it's like petabytes
of information being processed
throughout a day, right which would be
very difficult to handle if you had to deal
with character array.
So that's where that's where Java has come
up with strings, which is nothing
but a group of characters,
but you don't have
to deal with it Java by Itself has a class which would take care
of this strings and
since strings are widely used within a program you could
imagine that name or anything that any identify
that we have is mostly we have
to store it as the string. So one of the data types that widely used within industry
or which is widely used
in programming is string, right. So Java has some kind of string management
as well to make sure
that programs run or make
effective use of strings. Okay. So here what's been mentioned
is James is a data analyst
and he's finding is really
difficult to actually deal with character array to store
patients names every time so that's where we have string.
So string a solving the problem of actually dealing
with character array. So Java is actually
having character array
is touring characters or the characters in the string
in a form of character array, but It doesn't expose it
to the outside world.
You can just use
this class to deal with it, but you don't have to deal
with character arrays. So Java string is nothing
but sequence of characters,
they are objects
of type string class. Once the string
object is created. It cannot be changed.
This is the immutability
functionality of java. We're in once you write to it. You can change the value.
So this is specifically
important when it comes to multi-threading when you have multiple threads
accessing a particular string
or same string. So that's when immutability helps us to make sure
that you know,
multi-threading is it's thread-safe we call
it as thread safe because multiple threads
can access the same string just
because it is immutable. All right. So what are different ways
in which you declare a string?
So you have string Str
is equal to new string which we are not initializing
the value of the string here which could Any value and you
have string str1 is equal
to Ed Eureka wherein you
are initializing the value of the string right away. The other one is
the character array
similar to the integer array
that we discussed. We have character array as well. So immutability of the string.
So why do we have immutability
one is for security. So string stores lot
of useful information, like even the credentials
and stuff like that,
which shouldn't be accessed
by external users. So this immutability factor of string helps us
to keep it secure
so that no one else
can see it synchronization. So this is what I spoke about when you have multiple threads
accessing the same string,
you don't have to synchronize
it Java by itself through its immutability
feature would ensure that multiple threads
can access the same string
without hampering it
or it would run as it's expected. Shing so caching is nothing
but you have a string pool.
So basically if you have
two strings with the same value, it won't store it. It won't store
redundant copy of it.
There would be just one copy
in the string pool and both this references
would be pointing to that value. If you happen to change one of
these references it would point
or it would create a new value
in the swimming pool and point the other reference
to it sort of so basically what we do is why
caching is required is
as you could
imagine in application, as I said string is
widely used data type and you could have
multiple references pointing
to the same value of a string. So we don't want to have
duplicate values stored. That's where this caching comes
into picture to utilize
memory efficiently. So what is shrinking pool as I said string pool is
all the constants
that you define
within the string within the application
would be stored in the string pull string tool
used in Java is a spool
of string stored
in Java Heap memory. So we have heat memory. We're in the objects
are created and that's
where string pool
resides as well. String pool is Possible only
because strings are immutable. You can't change
once it is defined.
You can change it. If you change it, then you can change
that particular memory location.
It creates one more entry
in your string pool and the reference would point
to the new entry. So the actual memory location
is not getting changed.
That's what immutability is all
about string pool helps in Saving lot of space
for Java runtime. We are breaking
on the redundancy Factor here.
So if you have multiple strings or if you have multiple strings
holding up the same value, it won't create.
People copies of it there
would be just one value in the string pool, which would be accessed
by all the references.
So basically string pool as we discussed is
or resides in Heap memory. So string is not a
primitive data type
unlike character character CH AR is a primitive
data type string is not a primitive data type
is the wrapper class
to array of characters and this is specifically done so that Java has a mechanism
to manage strings.
Well, which is widely
used it arrived within any application or any programming language
for that matter.
Della strings are stored
in string to love Heap area which we already discussed
so we can see a string pool. So we have stack memory
and Heap memory.
So when you have
a local variable when you define something locally, the reference is created
in the stack.
All right, and it points to the actual object
is created in the Heap, but the reference
is created in the stand
so you could see as pointing
to hello in string pool. Okay, so s is nothing but a reference reference
to this ring.
Okay, so here we can see
that we are concatenating. Right? So this would give you
fair amount of idea.
What immutability is
all about, right? So here we have string S1
is equal to happy. All right,
and what we are printing
out the original string that is happy, right? So you could see here
S one is a reference
that's been created
in the stack. You have a string pool
within your HEAP memory which would store all
the strings all the constants
or literals that you
have defined here. So you could see happy
been stored in the string pool and S1 pointing to it.
Now you are trying
to concatenate S1 with learning, right? So it's happy learning.
So you could see that the memory location
that s one is pointing to is not changed right
still pointing to happy.
But this one more constant
that's been created in the string pool
that second category. The nation of happy
and learning so you could see
happy learning also created but what's important
to note here is s 1 is still pointing to happy.
It's not pointing
to happy learning. All right, so if you want S1 to actually point
to happy learning this is
how you do so you have S 1
which has the value happy. All right. So you do S1 dot concat learning
and you assign it to S 1.
All right. So you are assigning
to the same reference as S1 and you are printing
out s 1 in this case,
what would happen is
unlike the previous example that we saw there in S1 is still
pointing to happy you would see that as one is pointing
to happy learning.
So here you could see that this one is pointing
to happy learning. So basically you
move the reference
from happy to have Peter. All right. So, let's see what our strings
how do we operate on strings?
Right? So let me create
a new class here. Just ring demo.
I create a main
main method again. All right. Now what we do is string
s is equal to and Eureka.
All right. So let's first print
the length of the string. All right.
So this is how this
utility class or this is how this wrapper class helps us. So it has all these utility
methods right you just have
to do else dot length. It would give you length
of the string so had we not had strings and
if you want to deal
with the character arrays, you would have to print
the size of the array here. Alright, so when we run it,
it should print
it it is the size of the string at Eureka. Let's have substring.
So it's a beginning index. So suppose we give to so it would give you
substring from index 2.
So basically we
are getting substring. We are getting part
of the string substring is nothing but part
of a string right
from from a particular index. So since we have given
to hear it starts from index to so you have 0
he's at 0 and x 0 D is at index 1 and U is
at index 2 so it starts from you till the end of the string
you have compared to you.
Could Define two strings and you could actually
compare them and see the value so basically So
you could have one more
string defined here something of this sort. Alright, so here we compare it.
So we are doing s 1 dot
compared to To him, it's true. So we are comparing S1 with S2. So it compares the given string
with current string.
So here you can see it
as shown minus 1 right since B is one ahead of a so if you have same string
it would show you zero.
So if it's exactly the same
it would give you zero. You have he's empty suppose. You don't have anything
within your spring.
You could check it
whether it's empty. He's empty returns
a Boolean variable which means if it's true it is empty
and if it is false,
it has some value then we have to lower case
we have to upper case in this case suppose you want
to have could be scenario
in which you want to change or you want to
change the casing. So I'll just take one
of that I make it to uppercase.
Okay, so s 1 is nothing but we have Ed Eureka stored
within and we are so when I run this
you should have said
Eureka printed in uppercase. So here we have written camel
casing and let's see the output. So here you can see
the string was converted
or translated into upper case. So similarly you
could do lowercase which would print
string in lowercase.
Now we have value of is nothing
but the value of a string value of some of the data type so you could pass integer
and you could do value
of and it would give you
a convert integer into string, right so value of is
a method within string which takes different data type
and converts it into a string.
So just to give you
an example you could have like teacher I is equal to a hundred String dot value
of and you give I it
converting this I into string. So it would print
the same value hundred but it's converting
it into spring
you could replace something
within the string. If you want to replace particular character
within the string
which could be done
with replace method. So replace method takes two parameters replaces
a method within string
which takes two parameters. First one is the character that you want to change
and the second one is
the new character that you
want to change replace to. Okay so here to show S1 dot replace I could replace
e Within a be alright,
so we are making it lowercase
and as you can see here, it's printed in uppercase E
was changed to lowercase e so that's about replace.
We have contains which again gives you
Boolean type result, which says whether
a particular value
of particular character
is present in a string. All right. So in this case we check
whether we have
a stew with a TLD. Oh and you
replace t with L, which becomes hello,
and now we are checking with
the replaced string contains D, which it doesn't contain it, right so it would
give you false.
So that's about contains
equals is basically checks for the equality of string. It takes one argument
and it Compares it
against the string object against which you invoke
the equals against. All right, so to give
you an example,
so you have S 1 which is at
Eureka Eureka now to print it. So here we do S1 Dot. printing equality of string So
since it's the same
it would give you true if had it been different it would give you false.
So you can see here. It's printing both the strings are the same you
have different methods,
like compare ignore case where in this case we
compared with case, right? If you would have had Eureka
in lowercase, right?
If it would have start with lowercase e you
wouldn't have got 0 here. All right, whereas this one more
method which is s 1 dot
compared to ignore case when it doesn't consider
the case, right? So even if there
is a case change
if this how one
in uppercase and one in lowercase still it
would match all still it would give the value as 0
which means both the strings are
the same we could get some character out
from a string. Okay.
There is a method character at there's ends with which again
returns a Boolean value saying that That a string ends
with a particular character.
Alright, so here what we are doing
is we are checking whether the string P
which holds the value happy
learning is ending with you, which doesn't right. That's the reason
it gave you false.
Had it been G here it
would have given it true. Now that's about strings. Now.
Let's talk about different
variant of strings. And why do we need it? So there are like three variants
of string one is
the string class itself. The other one is stringbuffer
and you have a string Builder. So we'll talk about why
do we need this variance
at the first place? So string buffer is nothing
but good for multi-threading when you have multiple threads.
Usually it's good
to have string buffer because all the reads and writes
that you do on the string. It is synchronized.
So when I say synchronized
there's only one thread that could access a particular
method within a class at any given point
so you can't have
multiple threads going in and changing the value
or doing something. So basically if you have a
string within your application,
which is been accessed by
multiple threads it's better to go with stream buffer or if there is lot
of not accessed as such access.
One factor, but of course if there are a lot
of modifications done and stuff like that
like with stream
before you could append a pain
to a particular string which cannot be done in string right
in stream buffer.
You could actually do lot
of things it cannot be done and string and just
to make it thread safe. They have made all the methods
that modify the string contents
as synchronized so that only one thread can access
it at any given point. So see you can see insert
here right in string.
You don't have all these methods
you don't have methods to manipulate the strings
in string, right? Whereas in stringbuffer
you have methods
to manipulate the strings. So when I say strings those
are literal strings, right not the string class.
All right. So here we have string buffer and we are trying to append
something to the string buffer.
So we define a class
we Define stringbuffer. So you could have
like S1 dot append and when you see
a pendant you could see
that it appends any data type. This is the important factor
in stringbuffer you have lot of utility methods
within or you have lot of
methods to manipulate the string which you don't have
within string class. All right.
So this is mutable, right you are changing
the values suppose. I append three exclamation
marks do it, right.
So what we are doing here
is we are just printing out the new string. All right.
So basically you could you
should see at Eureka and the three exclamation marks. As you could see
here it got upended.
So basically it's a mutable
string change the value with them insert is nothing but inserts a new character
at the given position.
So here we are saying
that inside w at position zero. You could replace
it replace particular or replace substring
with a new string.
So here what we are saying
is replace index starting from 0 till to with
this new character sequence. You could delete something
from it delete sequence of it.
So here we are saying from
index 0 delete one character. So if you have two then it
would delete two characters. So basically when you
say two characters even
this e would have been gone. Okay, in this case, we are just
deleting one character.
So basically this delete method
takes the starting index and the number of characters
following the starting index. Zebras you have like you
could reverse the entire string.
Okay, so just to show
you again new string dot if I reverse it. So basically this is a kind
of utility methods
which we often use right so you can see it's
been reversed here. All right, you
can see the capacity
of the string capacity
of the string buffer is nothing but I think it reserves
16 characters initially when you declare it
and it keeps on incrementing it so it has a growth factor
defined within which you did not take care
of at this point,
which you did not think
about it at this point because those are internals
to Java but initially when you declare a string
string buffer storage space
for 16 characters, which is 32 bytes. If you have stringbuffer by do
we have string Builder, right?
So string buffer
as I said has some drawbacks. What are the drawbacks is more
about string buffer is synchronized when I
say synchronized which means
that only one thread
can enter it only one thread can process it. So basically if you have
a multi-threaded application,
you should go
with synchronization because synchronization has
some overhead, right? It has its own trade offs.
So when you
when you synchronized what happens is when you move out of
the synchronized methods
DVM internally has
to do some operations which takes some time. So basically it's good
to avoid synchronization
and which would make the application much
more faster and that's where stringbuilder
comes into picture
if it's a
single-threaded application wherein you know that you
don't have multiple threads which are going to access
a particular string
in that case. You should go with string
Builder as against ring. First because stringbuffer
would give you a slightly
lower in performance
compared to stringbuilder. Most of the things that string buffer does is done
by stringbuilder as well.
As far as the functionality
is concerned but it's not thread safe stringbuilder is faster, but it's not thread safe
which means that you cannot have
multiple threats accessing it. All right, so to keep it simple, if you have multiple threads
accessing or string buffer,
then you should go
with stringbuffer. But if you have
a single-threaded application, you should go with string
Builder which would make
the application much more faster than stringbuffer again
with stringbuilder. The default capacity is 60
when you initialize it stores
as you could see
it allocated 16 space for 16 characters initially. So as far as the
demo is concerned,
it's pretty much
similar to stringbuffer. As far as the
outcome is concerned. It's pretty much similar to
stream buffer is no difference
as such but as far as
the performance is concerned stringbuilder is faster
than string buffer because it's not synchronized.
Okay, so you define
a string Builder with happy and you append learning to it? Okay, and if you
try to print s B1
which is appended with learning you will see happy learning
would see it been upended. Okay similar to stringbuffer
when you delete character from index position
zero and one character from that position you would see
that the H which is the first
character has been deleted out so you could see that at index 1 you
could insert welcome.
You can see the entire string that is welcome being
inserted between okay, then you have reverse
Could reverse the entire string
pretty much similar
to string buffer. So again, this one
is very similar. You have you are appending
you're deleting then you
are inserting here you
have reversing here. This is pretty much similar to
what we did for stringbuffer as far as the syntax
and semantics is concerned and the outcome is
the same as well. Just a performance change
in terms of speed right?
So, when do you stringbuffer
and stringbuilder as I said if you have multiple threads you should go with string buffer
to make it thread safe,
but it would be slower
as compared to stringbuilder. Okay stringbuilder is specifically good enough and you
have single-threaded application
and it would be faster since it's not synchronized. So to make it thread-safe
you have synchronization
which adds over it to the performance which takes
tool on the performance. That's why stringbuffer
is slower why to use
object-oriented Concepts? So let's talk about
classes and objects. So classes are nothing
but it has got a street
and behavior right as you could see
you have a class and you have
different objects, right?
There's a phone
which is a class and which has got different types
of phones right rotary phone. Then you have a touch-tone phone
and you have a cellular phone
this are objects
basically, right? So you define phone
which is pretty much Jen Rick and which has got State
and behavior class is something
that is generate that has got State and behavior
but objects is something that is an instance of a class
which would have
specific State and behavior. So phone by itself phone
is a Class by itself. Which may or may not have
specific behavior,
but you could see that the specific phones
will have its own behavior to could Define
its own behavior.
So all these three things that you see here
three types of phones and nothing but objects objects
of one class state is something
that is defined by
instance variables, right? It's a class level variable
right at the class level you define something
that gives State and behavior
is nothing but something that is defined by methods
like calculator was a class where in we had add
method and add method
basically gave some Behavior
to the calculator class, right? So what are attributes
so you have a class and you have
attributes attributes
and nothing but a property
of object and in Java, this is defined by your instance
variables basically class will have properties
which is nothing but the state
which would be defined
by instance variables and you could imagine every instance will have
its own set of properties.
It won't be the same right
in terms of the phone that we saw earlier. There were three different types
of phones you could imagine
that it would have
different properties right? It's not the same. So what are the naming
conventions in generally used
at the industry level for Java. So this is not something that is actually taken
care by compiler.
So even if you follow this naming conventions still
the compiler would pass through but these are best practices
or this is good to have thing
in the industry conventions is more about to keep On
the same page and make it easier for other developers
to understand more right
or keep things simpler. So that's why
we have conventions. If you wouldn't have conventions
then people would prefer
to write in their own way which would make
us difficult to understand. Alright.
So for class name it
start with uppercase as we saw in all
the examples you would see that I have always used
started with the uppercase
or it's rather camel casing. So in this case you could see
stringbuffer demo, right? So it starts with
upper case you have B,
which is again
upper case you have B, which is again uppercase. This is nothing but camel casing
it starts with upper case.
Basically it follows camel casing interface name is
again similar to class. It starts with upper case
you have method name
which would be lower case always which should start
with lower case, but you could have it follows
camel casing but it has
to start with lowercase. So maybe it's a predefined
method with in Java. Right?
So you could see main
starting with lowercase or I created a dry Tad is again put C uppercase.
If you would have say
for example at numbers you would have something
of this sort adverse. If you want to append
numbers to it,
it should start with uppercase. So basically it's camel casing
but starting with lower case where as class name.
It's a camel casing which starts with upper case
variable name is again camel casing we
should start with lowercase
and constant is always like it has to be
everything in uppercase. So basically if I Define
a constant final string,
I would write
something like this. okay, so and if you want
to add more words to it, it should be
like this underscore
So it should be separated
out band score. All right. So these are the conventions
that followed in Industry
by Java community. So mostly even
if you go to the source code if you want to see something dig
into the source code
of java you would see same naming convention being
followed types of variables. We spoke about the types
of variables again to brief you
through we have local variables
local variables are nothing but the variables
that are defined in a method. So if you define something
within a method
that's local variable so ARG 100 or suppose
I Define and T local where is equal to a hundred.
So this is
a local variable right? If you remember this is
within the scope of a method once the control goes
out of a method your variable
is no longer accessible and also it gives space for
the jvm for garbage collector to kick in and clean up
this particular memory space.
Variables are nothing
but it's defined at the instance level so
here for that matter. This constant is
also instance variable.
All right, so I
can Define integer variable starts with lower case
and it follows camel casing. So this integer is nothing
but an instance variable.
It's at the class level right
when your class is loaded when you refer
to this particular class, you will have your instance
variable initialized by Java.
So instance variables
are declared in a class, but outside a method
Constructor or any block. Okay class variables are nothing
but static variables
and it is one copy per class. So as against instance variable,
which is one per object, whereas static variable
or class level variable
are it's just one per class. So if you define static, this is just one per class
and this could be accessed
directly using calculator
calculator dot constant example, you would be able to access it
but for instance variable, you need to have
an object created.
This is non-static basically
non static instance variable. So one of the reasons
why you need to access instance variable is
because different instances
might have different values for a particular
instance variable, right? I could Define
calculator one right?
Let me put it as calculator and we have like
normal calculator. You could have
one more class which is
like scientific calculator. It's one more object. Now a normal calculator
can have its instance value
as 10 and scientific calculator can have its instance value as a hundred
you have different values,
but whereas in static
since it's one per class, it's not at the object level. So you have mod is
equal to new demo,
which is an instance
of a class demo. And you print message right d dot print message and it
should print this message.
So basically there's
a class demo which has got
a method print message and we are trying
to invoke that message
from the main method. Okay, let's talk about
the constrictor constrictor is nothing but when you invoke
new keyword new calculator,
there is a Constructor implicit
Constructor for each class, which is without any parameters. So we'll talk about that.
But when you do new calculator, basically there's a method which could be used by
the programmers to initialize
variables if they want
to initialize something. So for each instance, if you want the same value
for instance variable,
you could initialize it
with in Constructor. So basically Constructors are
for initialization or if you want to do some kind
of pre-processing
break on invocation if you want to initialize
something or do some kind of pre-processing
that could be done through
Constructor Constructor is used in creation of an object. It is a block of the code
used to initialize an object.
So when I say
initialize an object, it's nothing but initialize
some property or variable within your class Constructor
must have the same
name as the class. It is in and it does not have
any return type. So unlike method,
which has got a return
type Constructor won't have a return type at all because what we are trying to do
through Constructor is
just to initialize objects within but you can't return
something out of it. So basically you Constructor
is a special method
which you don't have control over you are not doing anything
within it you're not trying to actually return
something out of it,
right? You don't have control
over its invocation. It's done by jvm itself jvm
calls this special method
when you invoke knew or when you create an instance
of it by using this new keyword Constructors are of
two types default Constructor
and parameterised Constructor. So when I say
default Constructor and parameterised Constructor,
this is nothing but
so I am defining a Constructor now calculator as I said, it has to have
the same name as the class.
Okay. So this is a Constructor. And as I said,
this could be used
for initialization of variables. Say I initialize this 200. So for all the objects
you would see this
being initialized to 200. That's the initialization. Okay, so I have created
two instance of it to instance
of calculator class that is normal calculator
and scientific calculator. Let me do normal calculator
dot instance variable.
Okay. So here we are printing the
value of the instance variable. Let me copy
the same thing again,
but in this case. the second case I would be
As you could see here. We have a Constructor.
I defined a Constructor
here Constructor for a class which is initializing
the instance variable to Value 200.
So as in when you call this new
calculator a new instance of calculator would be created. The first thing
that would be called.
Is this Constructor
and which would initialize it. So basically what we are trying
to do here is we are right after the construction
of this particular object.
We are going to print the values
of instance variable to see if it assigned 202 it. So here you can see the value
200 being printed out.
So basically if I wouldn't have Constructor then the value
wouldn't have been 200. So let me comment out this one.
This is how we comment in Java. By the way. This is a block comment
which starts with Slash
and asterisk and which ends
with asterisk and smash. So I commented out that one I
comment out the Constructor and you would see the value
being initialized to 0
so you could see value
been initialized to 0. All right, so that's what
Constructor is all about. Now.
This is a default Constructor. You could have
parameterised Constructor, which is like integer
you provide some value right
and you assign
this value to variable. So instead of hard-coding
this value of 200 for the instance variable
you could pass on some value
during the construction
of the object. So basically what we are doing
here is I pass 30 here and bypass 40 here.
Alright, so I am passing 30 and I'm passing
42 the Constructor. And as you could see here,
we are initializing
the instance variable to that value. So basically for
normal calculator,
it should be 30
and for scientific. It should be 40. Yeah, as you could see
here you have 30 and 40
min printed out and this is
the parameterised Constructor. That's what this default
and parameterised Constructor and that's what it is all about.
So default Constructor
is you don't even have to specify any Constructor. So I commented this calculator
constructed still implicitly.
There is the Constructor
put in by jvm, which is the
default Constructor. So it's not mandatory
to have Constructor each time
unless you want
to initialize something. So what's the difference
between Constructor and Method constructive
must not have a return type?
Whereas method may
or may not have a return type here you could see that
unlike the methods add integer, which return something.
This doesn't say anything. This doesn't return anything because we are not doing
anything within it.
You're just initializing it initializing some instance
variables right Constructor name must be same as the class
so that This is a contract
this has to be followed Constructor has to have
same name as the class, since you are not invoking
the Constructor by yourself.
It's done by the jvm. You don't have control
over invocation of Constructor and you have to follow
the naming pattern that Java
recommends to or Java forces us
to you have to make sure that instructor is given
the same name as the class name. Whereas method can have any name
as we saw the add method you're
free to use whatever method name that you want to Constructor is used to initialize
the state of an object.
We saw the instance variable
being initialized within the Constructor method
is basically it gives some Behavior to a class right
we saw add method which is giving some Behavior
to the calculator method, which is nothing
but adding up two numbers.
Similarly. You could have multiplied
you could have divided and stuff like that
which adds more Behavior
to it Constructor is invoked. Implicitly so you don't have control
over invocation of Constructor,
which is done by Java itself. When you try to
instantiate a class or when you use the new keyword,
it's implicitly invoked
by Java by jvm. Whereas method you have
to invoke it manually. So basically when you
do this Constructor
is called by itself. Whereas when you want
to call add numbers, you have to
invoke it explicitly.
How does Constructor work
the moment object of a class is created The Constructor
of the class is called which initializes
the class attributes, right?
So we saw about this. So when you use the new keyword
jvm by itself would give a call to the Constructor
which could be
used for initializing initializing instance variables
within your class. So type of Constructors
this default Constructor and
this parametrize Constructor, which we already spoke
about the Constructor, which is created by the compiler
without any parameters is
the default Constructor and the Constructor
with specific number of parameters is called
parameterized Constructor.
So here we spoke
about this already. So we have integer value, right? This is a
parameterised Constructor,
since you are passing parameters
to the Constructor, whereas if you don't Define
anything Java by itself, so in this case you could see
that we didn't have
a Constructor for
this class straight. I read them all we don't have
Constructor for this class. So Java by itself puts
her default Constructor
for array demo, which is known as
default Constructor. So it's not mandatory
that you need to have
Constructor every time since Java takes care of it. That's the differentiation
between default Constructor
and parametrization. We use parameterised Constructor for passing values
to the Constructor
and initializing something
based on the value that's been passed
out past in brother. So the default Constructor
is used to provide
the default values to the object like 0 null
depending on the type right when I didn't have
any Constructor at all
for a moment. I am going to comment this. So this is a line comment
when you put two slashes.
It's a line comment. Okay, it's commenting just this particular line This
is a block comment
and this line comment block
comment is slash asterisk and ends with asterisk. / whereas line comment is
two slashes forward slashes.
Okay. So basically a comment
or disc instructors as well. Alright now we have this
calculator class now lets me.
Let me print the value
of the instance variable. value of instance
variable initialized by default Constructor.
All right, so we don't have
a Constructor at all. So that's what I
am trying to say here. I commented out
this Constructors, right?
So we don't have
a Constructor at all. And when you create
a new calculator jvm by itself would have
a default Constructor
which is used by jvm
to initialize variables within so you would see this instance variable has
zero value as 0 because that's
what the default
Constructor does. It assigns some value
to it has like specific values for integer it 0
if it's a class it would be null so you could see the value being
printed as 0 if it's a class it would assign value null.
So in this case you have string
right and you could see 0 null depending on the type
of instance variable that we are dealing.
We saw how we pass parameters
and initialized it. Constructor overloading is just
like method overloading without written type
Constructor overloading
in Java is a method of having
more than one Constructor with different parameter lists. Like we defined add we had
to add methods and now I have
renamed this to add numbers, but basically this
was add method right so you could have multiple
methods with the same name
but different parameter lists, which is known as overloading
similarly for Constructor. You could have
the same Paradigm.
So basically what we
are trying to do here is we have a Constructor
with 1 parameter that sing teacher I'll Define
one more Constructor here
with two parameters. So we Define one more parameter
here and I say for example, I put something like this.
So we are adding up
these two parameters and putting it
into instance variable. Okay, this is
Constructor overloading.
So here you have single
parameter been passed here. You have multiple parameters
being passed So based on whatever you pass
here suppose I say 10 and 20.
Or say I say? So on construction you should C-130 as the value
of the instance variable.
Okay, as you could see here, you have the instance variable
initialized to 130, which is nothing but edition
of hundred and ten and twenty
and you could have something
like this just hundred and ten, which is also K because you have
a single distinct defined
as well Constructor taking
a single value as well. And in this case, it would be just a hundred
and so Constructors are nothing
but methods which helps
in construction of object. All right, so you get
a hundred and ten here? So Constructor overloading is
in Java is a technique of having
more than one Constructor
with different parameter lists. So we had a demo about it as I showed there were
multiple Constructors
one with one parameter and the other one
with integer parameters and during runtime
based on whatever you
pass a particular instructor
would be called in this case. You could see that in the first case
which is shop s 1 you
could see the first Constructor been called which has
two integers as being passed. Whereas when you create
object S 2 which has
two integer parameters and one string you could see that second Constructor
is being called.
What's Constructor chaining
so Constructor chaining is the process of calling one Constructor from
another Constructor with respect
to the current object? The real purpose
of Constructor chaining is to pass parameters to a bunch
of different Constructor,
but the initialization should be done at a single place
Constructor chaining can be done in two ways within the same
class from the base class
and Constructor chaining
occurs through inheritance. So basically for
Constructor chaining, there are two key words
that we have.
So one is this this
itself is a keyword in Java this pH is
this is a keyword and the super keyword.
Let's see how we how we do it
for this particular Constructor. I have this Constructor
which has this value, right? So instead of
doing this directly,
what I could do is so here. I was initializing
this value directly to the instance variable.
What I could do
through Constructor chaining as I could do this and I could pass
the value comma zero.
So basically you're
chaining here, right? You could see that what I am trying
to do here is I am trying
to invoke this Constructor
from this Constructor. That's what the chain
is all about. So when you say this it
tries to find Constructor
within your class which takes two parameters
to integer parameters and this is the one
it finds out, right?
It has two parameters. And basically what we
are doing is we are keeping the second parameter is 0
which means it would initialize
the instance variable to whatever value you have here, right?
This is what Constructor
chaining is all about. It's more about calling
Constructor of the same class within the Structure
of the same class.
So basically from
this Constructor you are giving a call to this Constructor
that is constructive change. Super should be the first
it gives a call to
the super Constructor. So you have a subclass
and superclass, right? What do you do here is
you give a call to superclass?
For Constructor chaining. I think they
should be good enough where and you use this keyword
to call Constructors
within the same class. You basically chain
them together, right? We have demonstration
on Constructor chaining here.
When you create student you
could see there's a Constructor without any parameter and we could see
this Meghan been called.
So basically what we are trying
to do here is the default name would be Meghan, right? So and again we have
one more Constructor,
which is overloaded Constructor, which takes name and in that case it would give
a call with the specified name
and Mark as 70. So basically 70
is a default marks that we are signing and you
can is the default name here.
If you don't provide name,
it would be Meghan. All right. So this is what Constructor
chaining is all about.
Static keyword
static keyword again, we have spoken about
in couple of instances, but I'll just walk you
through this slide again.
The static keyword is used
for memory management static is non access modifier used
in Java accessible applicable for blocks methods class
variables static keyword
is used to refer the common
properties of an object. So as we spoke it's
at the class level, it's not at the object level.
We have it common
across all the objects right when the static keyword is used
to declare any parameter. Then memory is allocated
only once for that parameter.
So in this example, we could see that
since it is one per class. So you would have
this constant example
Define just once right
it would be allocated. Just once whereas the non-static
ones like this in. This variable you
would have memory allocated
for each and every instance. So basically for this instance, you would have memory allocated
for this instance variable
for again this normal calculator that we had earlier
you would again have a memory allocated
for instance variable.
All right, so it's
one per object whereas the static ones
are one per class. So yeah memory is allocated
only once for that parameter.
All right. So here we can see that this we have
a static string company
which has some company
named put in there and we are just displaying it right we can see
that we are displaying ID salary
and Company and you could see that for both the instances
for even and E2 you have two employees here
with ID 25 and salary
25,000 and we have employee to with salary 30. Sorry with ID 30 and
salary 3000 right?
So we are defining
two instances of employees and you can see here. We are not passing
the company name as a parameter
to the Constructor right still when you display it look
at the output at the right side. You can see
that it has displayed
twenty five twenty five thousand and SRT Traders
the company name came by itself because it's one per class.
So what we are assuming is this class is basically designed
just for one company, right that is SRT creators.
So all the instances of the class are
all the employees that you create here.
All the instances of employees that you create here will have
the same company name that is defined here
since it is one per class. Whereas their ID
and salary would be variable which would differ as
per the value that you
passed to the Constructor. here we can see that company is a static variable little
allocates memory only once So
here it could be seen that you as I mentioned earlier
you have reference variables being created out in the stack.
And in the Heap memory, you could see
values being stored. So ID is tri-five salaries
25,000 for E2 ID is 30
and salaries 3000 and you
can see the static variable. So basically static variable
is stored in a different space which is permanent
generation memory.
That's where the static
variables are stored. So method could have
static as well. When a method is static
you did not create instance
of a method to call
that method instance of a class to call that method
pretty much similar to static variables, right?
So basically I can have
one more static method here. So say for example I have
private static all right, so So what I was trying
to say here is you
could have calculator. . And you could directly
call the display method. So you do not have instance
of a class created its
at the class level. This is at the class level
rather write one per class. Let's talk about this keyword
that this keyword is used
as a reference variables to the current object. So basically what what it
is trying to say here is so
if I want to
print something here, let me print
the instance variable, right? So within the add method
what I am trying to do is
I am printing the value of instance variable
Within add numbers, right? So I'm trying to print the value
of the instance variable
within add numbers which would be
basically this is where we are calling at numbers.
So basically it should be
a hundred and ten, right? When we have such scenarios where and we refer
to an instance variable
within a method we could see
here printing the value of instance variable
within add numbers gives you a hundred and ten
right the implicitly
what happens is it puts this dot here
this dot instance variable. All right.
So what we are trying
to say is the instance on which the add numbers
was called on the same instance, whatever the value of
instance variable is just print
that thing out. So this is implicitly
put in here you need not use this keyword.
This keyword is usually used when you have something
like this right when you have instance variable suppose.
You have something of this sort. Right? One of your parameters
is same as
as the instance variable, right? So you want to differentiate
which is the instance variable and which is
this variable right?
So that's when you use this When you say
this dot instance variable, this is referring
to this instance variable
and this instance variable to the right hand side
is referring to this one. Alright, so that's
when you have to explicitly
put this or in other cases. It's done by the jvm itself. You did not take care of it.
All right, so So, this can be passed
as an argument in the Constructor call.
This can be used to invoke
current class method. This can be passed as
an argument the method call and this can be used to invoke
current class Constructor.
This could be past basically
if there is one more. so say for example, you have something of this sort
which is pretty big though,
but Admitted taking
calculator as its parameter. Okay, so I'm just trying
to demo you could actually take calculator as an argument
for any of the methods within.
All right. So you have ADD method which takes calculator
as its parameter.
Alright, so here say for example
within this method don't think about the logic it's
not logical though. I'm just trying to show
you it could be done.
Right? So I have ad and I put this
within your method you could have you could pass
as an argument you could pass
this as an argument. So basically you
are invoking this one. So now if I print it
you can see in add numbers you
have this method being called. So yeah here you
can see printing out the add method taking calculator
has its parameter.
So basically it's calling
this on by passing this. So here we spoke
about the Constructor earlier. We saw how this could be used
in The Constructor and one
of the use cases as I said here you could see
that similar to the example that I spoke regarding
the instance variable.
You could see
the parameter the name of the parameter is rule number which is same as the name
of the instance variable.
This one is pretty
much similar to that. You could see
that the name of the parameter that is passed to
the Constructor is same
as the instance variable name
the rule number two. The left hand side is nothing
but instance variable within the class info
whereas to the right hand side.
It's a rule number that is passed as an as
an argument to the Constructor similarly for the name
you have this dot name,
which is referring to the name
the instance variable in the class info
and to the right hand side. It's a parameter that's passed
to the Constructor.
That's a typical use of this. So we are creating a message
here and you can see that we are giving a call
within the Constructor.
This is within
the Constructor actually, so we saw this
in the previous example. Basically, this is
what it does write
this value of 0 that is what this is doing within
the Constructor you have this and you are giving a call.
So in this case this Annie would
give a call to message string n and would print it out. So how does it work
the main function is executed.
So again, this is a sequence
in which the things execute behind the scenes. The main function
is executed first,
when an object of the class
is created a default Constructor is called okay, in this case, the one
without parameter is called
right then you have this dot any which is nothing
but you're giving a call to the Constructor
within the same class,
but with the parameter
any so the jvm would check whether you have a Constructor
with parameters as string, so it finds it and it would give
a call to that Constructor,
which is nothing
but the Constructor that you see here
in a Blue Block right, then it would similar
to any method
after the method
invocation is done. It comes back
to the calling method, right? So after this and is called it
comes back here then it prints.
Welcome to edu Rica. And once this is done, it would go back
to the main method in general.
What happens is whenever
a method is invoked the local variables and everything is pushed
onto the stack similar
to C. Write in C. Also you have a calling stack. So your local variables
go into the stack.
The calling method is invoked after the method
is being invoked and is completely done.
It would come back to the stack and start off from
where it had left earlier. So typically how the subroutines
and everything work
in programming language. That's how it's done
in Java as well. So that's why we
have calling stack.
So that's the sequence
of execution that happens. So let's start off with object-oriented
programming Concepts.
This is pretty much generic. This is not something
that is just for Java. So this is object
oriented programming concept,
which usually all the object-oriented
programming languages use it or adhere to it.
So we have Which we'll
be covering up in the topics to come polymorphism, which is we have
like static polymorphism
and we have Dynamic polymorphism
cover it up in details. The coming slides will talk about what is
abstraction and also
how Java has encapsulation or how Java is aligned words
the encapsulation feature of object-oriented programming.
So let's start off
with inheritance just to give you an analogy you could think
of inheritance anything that is derived have
some super class
or you have something from which
other subclasses are derived when you have some feature
of your parents. We say that you inherited right
because you have got it
from your parent. So you have a parent so this could be an illogical
to something of that sort.
Maybe you are looks is inherited
from your parents sort of that is exactly
what inheritance is all about. You have a parent class
and you could have
subclasses out of it and this subclass
is would inherit. Features or inherited State
or the behavior?
I would say
of your parent class. So to give you an example as you could think of vehicle
right vehicle is generic thing
which could be a super class so vehicle could be thought
of as a superclass. Now, there are subclasses
to Vehicles you have bike
which is a type
of vehicle you have car which is a type
of vehicle you have buses, which is again a variant
of vehicle and truck
of course is again a vehicle. So basically this defines
easier relationship by if you read it out
you could Clearly say
that bike is a vehicle
car is a vehicle but it's a vehicle
and similarly truck is vehicle. So basically this is something
like it defines.
He's a relationship. So let's see about
how actually this classes or the sub classes inherit
from the parent classes just
to read out inheritance is a powerful feature
object-oriented programming through which one
object acquires some
or all properties. Behavior of parent object. So as I said,
it's an easy relationship.
So he's a relationship
is represented in Java through inheritance. It could also be seen as
a parent child relationship.
So subclasses are actually
child of parent classes in the previous case you have
by which is a subclass of superclass vehicle.
So vehicle is a superclass and henceforth we
would be talking in this terms of we would be using
this terminology is so
just wanted to be sure you get
it so vehicle is nothing but a superclass and by could be
henceforth referred
as subclass child classes
would be referred as subclass. So you have method overriding what do you achieve
by inheritance is more
about method overriding
to achieve runtime polymorphism. And the second thing
is code reuse ability as I mentioned
the subclass would inherit
properties and behavior
from your superclass. Your parent class so there
could be some method defined in your super class
which need not be redefined
in your subclass. It inherits by itself. That is the property
of inheritance.
If it has got a common Behavior
like say you have two kinds of calculator different types of calculated the example
that we spoke about yesterday.
There could be
a parent class calculator, which is adding numbers
as is you provide two numbers. It adds up and it gives
you maybe this add
Behavior could be added into the calculator
Claus now Suppose there is a subclass of calculator
where in you have this scientific
calculator or something which is modifying
this behavior of our
which is using the same behavior of add right basically
a normal calculator or a scientific calculator
will have the same add
Behavior adding up two numbers. Whatever you send
it as a parameter, it would add it up
and give you the result.
So basically you would Define
this ad in the calculator in the scientific calculator. That would be the subclass
of your calculator you need
Redefine this add method. It would inherit
from the calculator method. So that reduces would redundancy
or it helps you
in code reuse ability. You need not redefine
the add method we have lot of slides to come
about method overriding
and Method overloading so I won't talk it right away. This is inheritance.
You have a manager class
and you have like employee which is extending manager. So what we are trying
to show here is e dot salary
as you could see here. There's a salary property
in a manager and this employed to is extending manager
and we could see here that employee to in
Harrods salary property though. It doesn't have
a salary property.
We are able to access
the salary property from employee to let
me give you an example. You just have to click
on create new project
and give some project name. I'll give a dude a car modules 3 so it opens
up a new window you could go
to the source folder and you could right click on it
and Create a new class. So basically I'll do one thing.
I'll create an employee class. I'll follow the same example
that's been mentioned here. I create calm down
at Eureka dot manager class.
So calm down Eureka is nothing
but the package name and manager is your class name. So now I Define a property
here say salary in that case,
right suppose. I say maybe I will put
it as wrong salary. So I Define a property
within your manager,
which is salary. Now I Define one more class. So you could either Define it
with in the same file
or you could create
a new class for Simplicity. I create a new class. It will create employee.
So it created an employee class
within calm down Eureka package. Now, let's do main which is your entry point
for the program.
Now as you could see
I haven't defined salary within employ. The first thing
that I'll have to do is we
are talking about inheritance. So employ extends. This is a keyword
used for inheritance.
So employ extends manager. So now you could see
there is a property which is salary
which is defined in the manager
and this employee which is the subclass
of manager and let's see if salary is
accessible to employ.
This is a place of manager. So I Define employ EMP is
equal to Nu employ. This is how we create instance
of the class using new now.
Let's see if
just for Simplicity. I will give this e MP dot salary
you could see that right just to be sure I print out so
as we can see
here salary though. It's not defined in employ. It has been inherited
from rather from your manager.
We can have one
more instance created which is like manager is equal
to new manager. This is instance
of manager class.
Now, I do manager dot salary
is equal to salary of manager. Is it just printing it out? So what we have done
here is again,
I repeat the same thing. So we have
a manager within manager. We have defined a field salary
and we have employee
which is extending manager
and the employee class. We don't have the field or we don't have the property
salary defined here,
but we could see here in this example wherein we
created the instance of employ and we are accessing salary
property from here though.
It's not defined
specifically in employee. It's been inherited
from the parent class that's manager and manager
of course has salary field
which is been access of here and we could assign
some value to it. I run the program
it should compile
and create a class file out of it and it runs
the class file using jvm. So yeah, as you could see here,
it's printing out values
for salary of employee and manager as well. So that's about inheritance
it see inheriting
the property salary
from parent loss. Now, what are different
types of inheritance that we have this Bill
inheritance wherein you
have a parent class and you define a subclass
out of it so similar to what we spoke.
We had a manager class
and we had employee class which was inheriting manager. That's about single inheritance.
You can have hierarchical
inheritance wherein you could have multiple classes
inheriting from a same class. So you could have a
and be inheriting
from a single class. You could have multi-level
inheritance wherein you have one class inheriting
from another and again,
you could have subclass
of the subclass parent class you inherited or you subclass it
or extended whatever you say so there is one level.
So you have a child class. Now, you could have
one more sub class of this child class.
That's what multi-level
inheritance is all about. So as we go through the example, it should give you a clear idea
about what I'm talking
about so single inheritance, so we have vehicle
and we have bike which is extending vehicle.
So this Similar to
what we defined here. So what we did here
is single inheritance. You had a manager
and you subclass debt
and this is just single
inheritance one level. So what is
hierarchical inheritance? So you have a vehicle
and you have two subclasses
created out of vehicle. So there are two child's
of a parent class. So this could be
pretty much similar
to a parent having two kids
right there could be two cats and they inherit some property
from your parent. So it's pretty much
similar to that.
So you have a vehicle class which is the super class
and you have subclasses to it. So, let's see how this works.
So I create a vehicle class
which is the super class. I have a vehicle class and civically class
has a property
which says integer say
number of Wheels. This could be one of
the property of a vehicle class. You have say for example,
you have the mileage.
So these are common properties
that you have in vehicle. Say you have Motion
just to add a behavior to this particular class.
I Define method move and I just print
this thing out here. I defend two properties here
for vehicle class,
which is number of wheels and the mileage and add
a behavior to the class by introducing method
which is move which is nothing
but I'm just printing it out. So ideally you would have
some functionality written within or you would have lines
of code written within just
because we are talking
about inheritance just to show the properties and behavior is been
inherited by the subclass
for Simplicity sake we don't have any logic
written within move. It's just printing it out saying
that just to indicate
that you know, there's a move method
within the vehicle class is being called.
We're just printing it
out there but in reality as I said there would be
actual logic written with them. So now I Define car class
and I defined by class.
So now I say that car is extending
which is nothing but sub class of vehicle.
So remember we said
easy relationship. Chip car is a vehicle. So what we are
saying is subclassing
or we are inheriting properties
of vehicle into car suppose. I change the property of any you method within or say
I can have its own moment
when car cross. So basically we
are overriding it. What we are trying
to do is we are trying
to whatever method you had
within your car class or the vehicle class. You are overriding it
for the car class.
You are trying to change
something similarly in your by class. You could overwrite the move.
So first thing that we'll have to do is bike
should extent your vehicle. So bike is a vehicle we
are extending it now.
We are again overriding
this move method to say move in by class. So now basically we
can have seven more just
for simplicity's sake we have
just a class wherein you would write the main method. So this is generally
Practice were in such classes
are called as client classes where in you have a main method
and you do something with it? I just call it as
automobile management class.
So you have a main method
so suppose you want to change the number
of wheels for a car. So what you would do is
car car is equal to Nu
or it won't be carved would be like suppose I put
Mercedes is equal to new car by create Mercedes.
I create BMW is equal
to new car. So now what we do is I want
to overwrite the property that is number of wheels
for Mercedes to for similarly.
I could have a bike class say
r 1 is equal to Mu by something of this sort you
could have Ducati is equal to Nu by so this is just
to give you an idea of
how we have classes
and objects right now. You could imagine
what objects is all about. So Mercedes is object
of car BMW is object of car.
Arvin is object of bike and Ducati is again an object
of by so now I could overwrite the properties here
say number of vehicles
as to so yeah, this is what it is all about. This should give you some idea
about how we use Java you have
a class you have subclasses, then you kind of create objects and you could override
the properties with them
and you could change when I say override is
nothing but you could modify the values within
your subclasses and similarly,
you could change
the behavior vehicle by itself would have
some Behavior defined but Mercedes and BMW,
which is a car would have
its own kind of behavior, which is not
inherited from parent you're overriding it
when you say
this this could be
an illogical to something like kid kid doesn't have
the same features as a parent. It is something
like it's been overridden right?
It's peculiar to
that particular kid, and that's what this is. About so you could override it.
Now. Let me print move or let
me call the move method on BMW so you could see a move method
and when I run it it should show
move method in car class since it's a movement that called on car BMW
is instance of car.
So this should give
you some idea about how are we inheriting properties
and behavior from parent class. So here we can see
that move in car class.
So again, you could
Define your own method within your subclass, which is not something
that is inherited
from your parent class. So BMW by itself or car by itself could have
something like sector board
which is not in vehicle. Maybe this is specific to car. So this is what we spoke about
is hierarchical inheritance.
Now, let's talk
about multi-level inheritance. So basically it's
nothing but say you have a super class category.
So let me use the same example. You have a vehicle class
you Have a car which is extending vehicle.
Now I Define one more class, which is nothing
but superclass Supercar which is extending car.
Basically, I can put this turbo
in Supercar rather that would make more sense. This is like
kind of multi-level.
So I am putting this turbo
here in supercars. You have a vehicle class
you have a car which is surplus of vehicle.
You have a Supercar
which is a subclass of car. So all the properties that you have in vehicle class
could be accessed
in car as well as Supercar. That's what we want to see here. So you could have something
like say change Wheels
which is void which is
not returning anything here. I just want to show you that we can still access number
of Wheels here though.
It's not defined
in car or Supercar but in vehicle class you could actually it
is still visible here
and you can modify it. That's the beauty of it again. Brief, you have a vehicle class
you have a car class,
which is extending
vehicle class. You have a Supercar class,
which is extending car class. So basically there
is a multi-level
of inheritance and all
the properties and behavior that you have in vehicle class
would be visible to car class as well as Supercar cross
and Supercar class can access
properties and behavior that is there specific
to car class. What I'm trying to say is
if you define a new method here,
so I just mention here Behavior
specific to class to car. So there's some behavior
that is specific to car that we have defined
within the car class.
Now Supercar class
can access this one as well. So you could see here
you could access Behavior specific to car as well.
If you look it as a tree. This is a leaf node. This is super car class
can access everything
from vehicle and car class. Whereas. Our class can access everything
from vehicle class,
but it's not the other way
around car cannot access something that is
specific to Supercar. There's a turbo method
that we have put in
into the Supercar class. Now. If you try to access
Turbo from here,
you won't be able to access it. All right, so it's
not the other way round. So you cannot access something
that is specific
to your subclass in your super class. Whereas you can access anything
that is there in your superclass
into your subclass. So it's a one directional flow
from superclass to subclass. Now, let's talk about has
a relationship has
a relationship is nothing but you have properties
within your class, which is has a relationship.
All right. So say for
example employee, right? We defined the employee class
and employee would have
an ID specific to employ and it can have salary
and stuff like that which is has a relationship
which is nothing but employ as
ID sort of right so a department in a class Let's talk about this example
a department in a college
has several professors without
existence of departments. There is good chance for the professor's to exist
hence professors and Department
are loosely associated. And this loose Association
is known as aggregation. So one can exist without other
which is loose Association
and such thing is
nothing but aggregation. So here you could
see employ here. You could see name
name class itself,
which has got first
and last name. So basically you
have a name class which has got property as first
and last and which is nothing
but the first name and the last name of any entity. It's not associated
with anything right now.
It's a different entity name is
a different entity which would have first
and last name now this employee info class,
which has got ID and
which has got name so you can see name hear
this name property is nothing but The instance of name class
that is there
the left hand side. So this is has a relationship. This says that
employee info has name.
So basically this is what it is when you talk about has
a relationship its containment. Basically you have class
as a property in a class.
So in this case
name is a property within your employee info and similarly this name could
be used somewhere else as well.
It's not that it has to be used
just in employee info. That's a kind of Detachment
they have right. It's not tightly coupled.
It's Loosely coupled
or decoupled. So basically you have name which is altogether a different
entity defined as a class
which would have first
and the last name and you would have an employee
in for which is containing name which has name.
So this is has a relationship and also to give you idea
about has a relationship. It's not just
it has to be object.
Right so vehicle has number
of Wheels vehicle has Uh, this could be thought
of as a relationship. So let's talk
about polymorphism.
Now when one task is performed
by different ways, then it is called as
polymorphism Polly is multiple of ism is forms.
Basically, that's
the meaning behind it. So multiple forms. That's what polymorphism means
and when one task is performed
by different ways, then it's called as
polymorphism this person which is the super class.
You have a subclass student is
again person millionaire is a person these
are super classes. So you have a person class
you have super class student
and millionaire you
have a behavior, which is nothing but P Bill and which would be specific
to both of them.
So as we move on you
would get much more idea about the different kinds, but basically you
have multiple forms.
That's what polymorphism
is all about. So, what is Method overloading
so we spoke about this yesterday if you remember we spoke
about Constructor
overloading we're in you Had multiple Constructors Define
one was integer integer, and the other one was
like it was taking
three parameters integer integer n 3 integers, right? So basically this is what method
overloading is all about to have
the same name of a method but you have different number of
parameters passed to the method or you have different type
of parameters passed
to the object to the method and based on that. It would understand
which is a method
that needs to be called. So suppose you have ad with
two integer parameters Define and you have ADD with three
integer parameters defined now
when you invoke add method
on a particular instance of calculator and you
pass two parameters to it, it would appropriately call
add method with two parameters
and if you pass
three parameters to it, it would call one
with three parameters or it would resolve it
during the runtime which one
to be called rather. It's not overloading
doesn't happen during runtime. It's done during the linking
of the resolving operation.
Ben's during the
compile time itself. That's why it's
static polymorphism method overloading is nothing
but static polymorphism.
So return type is not taken
into consideration when it comes to Method overloading. It's just the parameters
that a particular method takes.
So Alex wants to write a code which can be used to find
out the area of triangle as well as of circle.
So generic code which
would have area of triangle and circle so such are
the instances wherein you could use method overloading.
So what's the thought behind
is I want to find area of both the shapes here
area is the common method. It's there for both the shapes.
It's therefore rectangle. It would be there for square. It would be there for Circle
and so on and so forth.
So basically you
would have a shift method which would have area
which is a common method. So instead of writing
two methods of different names.
I will write area as
the method name for both shape. And a path different arguments according to
the respective shape.
So instead of defining
multiple area methods you would have just
a general area method defined in your shape class
and your subclasses
would overloaded as per the type of shape. So here we can see that this
area class there's area method
which is taking integer since it's a triangle
its base and height. So it's taking base
and height as parameter.
So Java doesn't understand
base and height. This is user defined by the way. It understand.
There are two integer parameters
passed through the area Whenever there are two integer parameters
passed to area method. This one would be called.
The other one is again, we have one more method which is area which is
by the same name
and which is taking just
one integer parameter, which is radius. So this is supposedly
for circle Pi R square.
So during runtime
when you call it, so I'm not repeating
this exercise again, because we did the same.
Yesterday if you remember we kind of had multiple add methods
in the calculator and we saw that it was getting resolved
to the proper one
based on the number
of actual parameters that you pass. So I will just read
through the slides to make you
give more explanation on this but it's pretty straightforward. So here you have area method
which is ticking for six
which is nothing but
it would get resolved during compile-time this particular area method
invocation would get resolved
to this one since it is taking
two integer parameters. Second one is taking just
one integer parameter,
which is 5 so it understands that it has to call
this area method the second area method
that's been defined
in method demo and it
would call it accordingly. So here you could see that when you run this
particular program you could see
that the first one resolved it
to Triangle and it said that the area of triangle is
nothing but 4 into 6 into point five,
which is nothing
but 12 the second one goes 2 pie R square. And it gives answer as
seventy eight point five.
So you could see there are
two different invocations done based on the number
of actual parameters. Now, let's talk about type
of parameter the method
overloading can happen
on type of parameter as well. So you could have multiple
methods with the same name taking same number of arguments
but different data types one could be taking
integer as a parameter. The other one could be taken
string as a parameter
and during runtime ordering
compile time itself. It would resolve that, you know, this one should be resolved
to this invocation
and the other one should be
resolved to the other one. So basically it tries to resolve
based on the parameter based on the data type
of the parameter
that you pass. So here's the example wherein
you have two different methods. I will take this one.
Say for example,
I Define public integer. So it's a dummy value
to be printed one of the best practices
when you write Java code is
to express it, right. So you can have
a big variable name you shouldn't be restricting
on variable name
which makes it difficult for other programmers
to understand. So it's good to have big
variable name versus small one,
which is not that expressive. So here I said dummies
string value to be printed. I'm printing integer value is
nothing but dumb integer value
and here I am printing so we have two methods
with the same name but it's taking different
data types as argument
and we are just printing it out. So I Define a main method here
and I Define manager. So we have instance
of manager senior manager grade
2 dot display I
pass integer to it. I pass hundred to it and I pass so I have to Method
invocations here.
One is first one. We are passing
hundred the second one. We are passing a string to it
and it gets resolved.
You could see that the first one would go
to this display method which says printing
integer value the next one
would go to this. Display method which
print string value so you could see here.
Right? So first one is
printing integer value. The second one is
printing string van.
So based on the type
of the parameter that you pass through are passed
to the method particular method would be called This
is static polymorphism.
Now what's runtime polymorphism. So since it is resolved
during the compile time, it is static polymorphism.
There are few things that gets resolved
during the runtime or the compiler cannot judge
it up front what the instance
would be and that's when it does it
during the runtime and that is nothing
but dynamic polymorphism
or method overriding so
method overriding is mostly used in an easy relationship. So in one of the methods or we
saw in vehicle and car example,
we have a move method here
and here we overrode it. You can see override annotation
here for the move because you're overriding
it overriding the behavior
of vehicle in car class. So that's where it says that this Easy relationship
method overriding must be used
in case of inheritance that is easy relationship method
must have the same name as in the parent class.
We saw in the move
in the example move. We have the same name as
in this super class. So huichol has a method move
and car has a method move
as well method must have
the same parameters as in the parent class as
against method overloading which has different
parameters method overriding
you have to be sure that it takes the same parameter
if I change this to integer if I add an integer
parameter to it,
so it's not taking it as
overriding you could see it. It's not been taken as overriding because you have
integer parameter to it.
So basically it has
to have same number of or it has to have the same
signature as your parent class. So that's about
method overriding.
Let's have a demo on this so
which we already saw but I will again A trait on that so basically this example you
could see there's a man class
which has got a pay method which is adding Behavior
to the man method and you could see
it's a dummy printer
and you have a millionaire is
a man and you could see it overrides the pay behavior and you run this program.
One thing to note here is you
can assign me linear to man. You can assign
unlike all the examples that we saw we are creating
instances of the same class
or assigning the instance
of a class to the same class. But in this case you
could see the instance of millionaire is being assigned
to reference of man.
This is something that happens only in Easy
relationship or inheritance. So what I am trying
to say here is a go-to
automobile management I have car I have a new car which is Mercedes I could assign
this Mercedes to vehicle
since Mercedes is a vertical it should be a sign you
should be able to assign it. This is something
that you need to keep in
mind your subclass object could be assigned to superclass. So here we have Mercedes
being assigned to vehicle.
But one thing to note here
again is the tricky part is vehicle itself has
its own move method, which Moving vehicle class
and Mercedes which is car
itself has its move method with this move in car class. So the tricky part here is
when you would do something
like vehicle dot move just give a thought about it
which one should be called. So you have two variants
of move method here.
You have one in car
and one in vehicle. So the one in vehicle
is printing out moving vehicle class and one
in car is the overridden version of vehicle with says
move in car class. Now, what we are doing
here is we are creating
an instance of a car class and we are assigning
that instance to vehicle and we are calling
the move method.
So just give a thought whether the move method
on the vehicle class would be called or a move method
on the car class
would be called. So this is where method overriding comes
into picture so method
overriding is nothing but
it's a runtime polymorphism which is done at the runtime. So during the runtime
jvm would see
that Mercedes is nothing
but the instance of car though, it's assigned to vehicle which is super class still
an instance of class.
So during compile-time jvm
wouldn't have a friend knowledge that which move are you calling? Is it on vehicle class or is
it on something else
or some sub class of vehicle? So it doesn't decided during
the compile time it delays it or there's a lazy binding
that happens delays it
till the time you run it. So when you run it, it understands that this vehicle
is actually pointing to car.
That's Mercedes. So when you run
this you could see that I will comment
out this piece of code.
So this is how we comment out
that's a block comment. So when I move
this you could see that move glass
on car has been called
and not vehicle that is what is if you get this concept, you're pretty good in terms
of object oriented.
By the way. This is an important Concept
in object-oriented Paradigm. So you could see here move
in car classes.
Called similarly vehicle could have I call it
as vehicle one, right? I Define one more vehicle here,
which is like new vehicle and I invoke the method on vehicle to so
the second variant
would call the move method
in your vehicle class. The first one calls on the curved glass the second
one calls on the baker was
since its object
of vehicle itself. So basically you have to see
on the right side, which is the object
that's been assigned
since its object of vehicle. It's vehicle. But since this one
is object of car,
that's the reason you have
car class being called. So we had some discussion
on this keyword yesterday. So super keyword is similar
to that super keyword is just
that it is called on superclass. This is called on the same
class super is called on the immediate subclass
immediate parent class you
could have multi levels, right? But this one is calling
the immediate parent used to refer immediate parent.
Us instance variable used
to invoke parent class method and there's one more
Super keyword one more form in which you could use is
to have class Constructor.
So basically whenever
you create a class whenever you call a class
whenever you call Constructor of a class by default jvm
by itself would give a call
to the superclass Constructor, which we would be looking
at the further slides. So here we have vehicle leaven,
which is a super class which defines string
Wheels vehicle moves because of wheels
so that the string
that the property
of a vehicle you have a truck which extends vehicle
and then within truck you have your overriding
the wheels property saying
that truck has four wheels. This is kind of your
overriding the property. It's not called
overriding though
when it comes to properties. But basically you
have changing the values within your truck class print
wheel is nothing but a method
that's defined in. Truck which would bring
the number of wheels in your truck class
and it has got super dot Wheels
which would print the number
of wheels in your or print the value of the Veals
not number of Wheels value of the wheels property
within your vehicle class.
So we will look at this one. So we have a vehicle class
and we have string Wheels which is a property
within a vehicle class
which has some value
put in right? We have a truck class again, which has got wheels
and it is overriding the value.
It is just changing the value as truck has four wheels with interrupt class you
have print will method
which is printing
the wheel or the value that this particular
Wheels property holds it would print it first
one would be the value
that this particular truck class
would hold and the other one that you see here
the second print statement, which is doing super dot Wheels
is actually printing the value
of wheels in vehicle class. So, let me show you
a quick demo on this thing. So we Have a vehicle class
which were in we are defining
the default number of Wheels as for say for example, and now we have a bike class,
which is overriding
vehicle class. And what we are going
to do here is we are going to change the value
of number of Wheels.
I have a method to print
number of fields, which would give suppose
I change your number of Wheels to say to so here we
print number of Wheels first
and I would have
one more print statement which would be printing
super DOT number of Wheels within a by class.
We have a print number
of bills method first. We are changing the number
of Wheels to 2 and then we are printing
the number of wheels for bike
and number of wheels
on the superclass. All right, and by default we
have set the number of wheels in the vehicle class
to before so we have
a bike class now I remove this to so now I print
the number of Wheels. So I create the instance
of bike and I invoke
print number of Wheels. Now you could see that first it would print
to and on super dot.
Basically. This is what it's going
to call so first it will print to so basically here
we need to have one more
teacher number of fields when it comes
to instance variables. It's not overridden as
such so I have like number
of Wheels defined here again and here I change number of Wheels to to so
let me run it again.
So when it comes
to instance variable when you define one more field
here of the same name, it's not overriding it.
It's rather creating
a new instance variable. So now you could see that when you print number
of Wheels it's printing out
to which is nothing but the value here value
of this instance variable. Whereas when you do
super DOT number of Wheels,
you have a default value of 4
here which is been printed out. So on super it gives
a call to superclass. So here you are creating.
It's at the Constructor level. And we can see
that so it's more about as I mentioned
within your Constructor.
The first thing that is called when you create an instance
is a super Constructor is called first
and then your sub class
Constructor or I mean to say is when you create instance of car. So your first thing
that would be called
is the Constructor of vehicle and it would do
all the initialization that's required in vehicle.
And then it would call
the cars Constructor. So what I mean to say
is for example, I create a Constructor here
and I print saying
that we are within Constructor
of fecal of superclass vehicle. Now we have this car class
and say we have Constructor for car class as well.
Remember we said that there's a default
Constructor implicit Constructor that's already been
put by GBM itself.
You don't have to
take care about it. So I don't do anything here. So basically you
need not create you do.
Right Constructor jvm
by default right Constructor, unless you want to write something or you want
to initialize something.
That's when you would
write explicitly you would write Constructor. But in this case since we
are not initializing anything
as such I won't put
a Constructor car. What I'm trying to say
is we are creating an instance of car here.
And let's see when we
create the instance of car. There is a super Constructor
that's been called. That's what I wanted to show.
So that's why we created
a Constructor here for vehicle. This is not a method. This is constructed by the way,
since it has got
the same name as your class and it doesn't have
any written value. So so I have printed
it out saying
that we are in the Constructor
when we call this now when we create the instance
of car you could see that this Constructor
of superclass that's vehicle
that's been called. So this is done
implicitly by compiler. You don't have to care about it.
So here you could see whenever you create the instance
of car you would see that we are in construction.
Of superclass vehicle
and the second print statement that you see is directly
for the vehicle sensation. So even for car you could see
so this will get
rid of confusion. So there's only one instance
of car being created and we can see that it
is calling vehicle Constructor
and it's implicitly put we don't have to explicitly
put it jvm by itself operates that way
and how it calls is nothing
but by Super Final keyword we again touch based on this one
earlier in the session. Number one final keyword is non
access modifier applicable only
to variable method or a class
when it's applied to a variable. We say that the variable content
cannot be changed usually use final when you want
to define a constant
within your application. So that's final a method
could be defined as final you define a method
as final when you say
that your subclass
cannot overwrite it that's when you define it
as final you define a class. As final when you say
that there cannot be
any subclass of that class. So you cannot subclass it like if you try to extend
on a final class you
would get an error
compile time error saying that you cannot extend it. So just to show you maybe
if I make this as final your car
would show an error saying that you cannot inherit
from final class. That's Comdata recorded pickle.
So that's about final class. And if you make
this method final you would again get an error
in the class saying
that you cannot overwrite
this the car class you are trying to override
the move method since its final it showing
you an error saying that move
cannot overwrite move
in calm dot Ed u-- recorded vehicle overridden
method is final. Let's remove this finer
and you should see
the error is gone. And also if you want to see
at the instance level if you define this as for number
of Wheels as for now
within this vehicle, if you're trying to modify
this number of Units to to it would throw
you an error saying
that cannot assign a value
to final variable. All right, so that's
what it does it. It's not access modifier,
but it regulates it in a way that you can't change the value
in case of variables you can change the value
in terms of class.
You can't subclass it or you cannot create
a child class of a final class and in terms of methods,
if you have final method
you cannot override that particular method
in your subclass. So final modifier can be applied
to class method instance
variable class variables local
variable and Method parameters. So final variable is used to create constant variables
when it comes to variable
as I said, usually you use final variable when you want to
have constants, right
and it would be final static. By the way. If you have a constant
usually final and static
static final final methods
is used to prevent method overriding in terms. Method the demo that I
showed you previously we saw
that we cannot override it
in terms of class. When you have a final class, you won't be able to create
subclass of it which we saw.
All right, it gives you
an error some examples of final clause in string class. So system class
in Java dot Lang dot package
is final as well string class that we have been
using string class that's been exposed by
or Java itself has
or Java by itself defines it
that class is final as well. If you try to
extend string class, it would show you an error
it would give you an error.
So system is kind of
putting a contract or Java by itself is putting
a contract or is saying that cannot extend
the string class.
You cannot extend Its Behavior. You can't change anything
any of the behavior within your string class by yo,
that's why they have marked
it as final if a method is declared as final then
it cannot be overridden in your child class.
If a Variable is declared
as final then you cannot change the value
of that particular class or cannot change the reference
of that particular class
when it comes to objects. So we will see that later a Constructor
cannot be declared as final.
So that's the rule you cannot
declare the constructors final and blank final variable should
be initialized in Constructor. So maybe in this case
if you wouldn't have
any value here, you declared this as final if
you don't have any value here. It has to be assigned
an Constructor right now.
It's giving an error saying that it's not initialized
if you mark it as for it should be gone.
So it's mandatory that if you put instance
variable as Final in class, it's mandatory that you assign
some value in the Constructor.
If you don't then compiler would throw an error so
here you can't override it. So basically you have
a final method void run
and you have a sub class of vehicle and you're trying
to override Run method, it shows you an error.
So this is what we saw
in case of was Final and when we try to override it
in car we got an error and it's all compiled sign
if you declare any class as final you
cannot overwrite that class which we saw it gives
you a compile-time error.
So when it declared a vehicle as
final and when you try to extend when you try
to create car class, which extends vehicle class
it gave you an error
because vehicle class was
fake lettuce final again. This is a compile time. Now what's Dynamic binding
which is also known as runtime polymorphism is
nothing but during runtime it decides which instance
of which instance
of a method should be called or which method
should be called. So this is in case
of again inheritance
and when you override
the method in your subclass, so we saw this earlier
again to just to show you we had this move method here
and in I have this move method
and in automobile management, we did this thing
we have a Mercedes that is assigned
to vehicle class class reference
rather vehicle class reference of reference named by vehicle
1 and in the second thing we have vehicle itself.
So first one is pointing
to an object of car, which is Mercedes and the second one is referring
to the object of vehicle itself.
So this is what dynamic
polymorphism is all about. The first one gives
a call to the move method in car the second one
second one gives a call
to the move method in vehicle. So yeah, you could see here. So move in car class
and then it calls
a moving vehicle class and it happens at run time. That's why it's
runtime polymorphism.
So abstraction is a mechanism of hiding the implementation
details from the user and only providing
the functionality of a user.
So basically you
could have abstraction. We're in on the first day. We spoke about the shape class
and the circle class
and Wrangle and square
and stuff like that. Right? So basically shape is a class
which is abstract class,
which doesn't know all
the functionality up front door. It doesn't have all
the behavior of front. It doesn't know
what would be the behavior
of a circle class or it doesn't know. What is the behavior
of a square class
when I see Behavior. It's nothing but calculation
of area calculation of area is nothing but it
adds Behavior to the class
and calculation of area in your Square class would be
different calculation of area in your circle class
would be different.
So shape by itself doesn't know what the implementation
of area method I would say. So that is what is attraction.
There are two ways
in which you could provide abstraction in Java one is
by abstraction class, which is not hundred
percent abstract,
which could have like abstract methods like area
in this case is about Track but there could be some methods
which is same throughout
or common throughout all the subclasses of shape say
for example printing area. You just have to have
a print statement
which is printing area
for a particular shape from the implementation per se it's same throughout
all the classes area method
would be something
that is abstract. Whereas display area
could be something that is not an abstract method.
So in such cases wherein you have blend of abstract as
well as non abstract methods, that's where you
use abstract class.
So it's not hundred
percent abstract. Whereas in interface it has
to be interface is something which says that it has to be
a hundred percent abstract.
So interface is
altogether a new construct that we have in Java when it comes to abstract
class abstract is just
a modified to a class. So you write class and you
just prepend it by abstract which makes that class
and abstract class.
Whereas interface is something
that is a new construct that we are going
to see in the coming. Slides upset class
and Abstract methods
so abstract method is as I said area
would be abstract method in this case wherein you don't
have a concrete implementation
of area in your shape class. That's the scenario
in such cases wherein you don't have a complete
concrete implementation
of a particular method
you would declare it as abstract method and
if you have an abstract method, if you have at least
one abstract method
in your class, you have to declare
that class as abstract class or else compiler
would throw an error.
So whenever you have
a abstract class, it means that there is
at least one method within that particular class
which is declared as abstract.
So when you suppress
this abstract class so shape for that matter when you subclass shape shape
has got a area method
which is abstract. Now when you subclass it
when you create Circle, which is nothing
but class Circle
which extends shape now you
are creating surplus of it. That case you have to ensure
that you implement area. If you don't Implement area,
it is still kept as abstract
and you will have to make circle class
as abstract as well. If you don't give
the actual implementation.
So an abstract method is
a method that is declared without implementation any class that contains one or
more abstract methods
must be declared
with abstract keyword and abstract class is a class that is declared
with abstract keyword
and abstract class may or may not have
all abstract methods. So as I said,
it's a mixture of abstract
and on abstract methods and abstract class
is mostly used for inheritance. So let me take the same example
of shape and shapes.
So we Define a shape
which would have abstract area. This is what I was saying. So when you have at least
one abstract method the compiler
will throw an error. So in this case it is saying that you have abstract method
but your class is not abstract.
So we have to make
this one as abstract. And as I said abstract class
is nothing but a modifier you just have a modifier
that you need to prepare
into the class. This is abstract method
and you say you have a method which is public void.
It's not returning anything. We are just displaying area now
rather than defining it here. Maybe I will put something
like So we have a shift method
and now I declare
Circle method now, this circle method
is extending shape now. It's throwing an error and it
says you have to implement
the abstract methods shape as got abstract method if you don't implement it
as I mentioned earlier,
if you don't implement it if you choose not to implement
the area method then you will have to make this abstract.
If you make this abstract
error would go off. But in this case since we know the concrete
implementation of area
for Circle will have
to implement it when I say we will have
to implement it we say area and we override it.
So for Simplicity reason, I'll just put
some value here for now since we are talking
about abstraction.
I'll just keep it simple. So basically what we
are trying to do here is we have implemented area
which would be nothing
but your Pi R square actually, so here we have a shape class and we are overriding
the idea method here.
And this is how you abstract it. When you run it, so basically you
could have something
like suppose I create
a shape utility class. So this is pretty much
like overriding methods. So you could have a shape
class shape circle is equal
to New Circle and you
could call Circle dot area. So basically what you would get
is nothing but a float value, which is your area area
of let me put it
this way area of circle when I want to print it. What I would do is
circle dot display area
and I print area of circle what we have seen here is
there was abstract method area which was implemented
in your subclass that Circle and
when I give a call to it and here you could see that again similar
to vehicles that we spoke
about instance of circle
is being assigned to shape and when you give a call to
it you could see that method on circle is being called
and not on shape
because shape by itself doesn't
have any implementation of area. So one thing to note here is
when you have Class. So here you could see this value
being printed operate abstract
class would have one or more
abstract methods for sure. And when you subclass it, you have to ensure
that you give implementation
of your abstract methods. If you choose
not to implemented, then you will have
to make the subclass
as abstract as well. So execution of abstract method. This is very much similar
to normal exhibition
that we have. So the main method you have
instance of mobile class created this case then there's
a default Constructor
of mobile class gets
created gets executed. So pretty much similar
to normal execution when you create
an instance of Nokia,
which is subclass of mobile. As I said the first statement that you have the Constructor
of subclass is nothing
but super or it calls
the super Constructor. So here we can see that the default Constructor
for super is being called
when you try
to instantiate Nokia as we are running run method, but in Mobile class run
is an abstract method so
run method from Nokia class gets
executed similar to the example that we saw so shape
area class area method on Circle got executed
and not on shape.
What is the encapsulation that encap solution is
the methodology of binding code and data together
into a single unit.
So basically everything
it's a encapsulation. It's put as one so you
could imagine class being put as one right classes
called this for that matter.
You see everything
been encapsulated as one right you group these together you group this integer and long
which is a property of vehicle
and it has got some Behavior as through this move. It's all encapsulated as one
or it's all put
together as one entity that is nothing
but encapsulation. So basically you could
imagine a capsule right
which has got
multiple ingredients which has multiple made sense
or chemical components which are put together
into one capsule
and you have you think
capsule has one mixing but it's basically combination
of chemical components Within Thing is
for encapsulation.
There is access modifier comes into picture you have
this access modifiers or private and you have public
you have protected
you have default this access modifiers restrict or it restricts the visibility
of regular component
of a class say method or variable or anything. So that's encapsulation feature
of object-oriented programming.
You can't see everything. It's not that everything
is open for everyone. So you can have
restriction you have
different levels of restriction when it comes to visibility
of this components that is a part
of encapsulation as well.
So to achieve encapsulation in Java declare the variables
as private usually the best practices
not to expose everything
because once you expose
something as public or once you expose it for the application
to access you have to ensure that you maintain it right
because anyone can access it.
So your class is becoming
much more fragile a I won't talk about
this topics right now because fragile D is something
that is related to code quality
or coupling we say so I don't want
to touch on that. But basically the best practice
is to have less
visibility restrict visibility or different visibility
as much as possible. Try to make it as much less
as possible make it private.
Basically if you could make all the variables as private
it would be good thing. So basically all non private
or public variables are
liability for application. So it increases the maintenance
of the application and it's easy to break that way
if you make some changes
to a class it becomes very difficult the future
to maintain it. So usually the general practice
is to keep the methods variables
as private not methods variables
as private and we have Getters and Setters method which exposes which are public
methods or mutator methods
which would expose this variable to the outside
world through public. So usually we don't
have Setter methods.
We restrict
Setter methods again. Usually you have a private since variable and you
have a getter method
which is a public method which is nothing
but Returns the value of the instance variable
to the outside world.
So data hiding the user
will have no idea about the inner implementation
of the class. What are the advantages
of data hiding user
need not know the core
implementation of the class. It increases flexibility. We can make variables
and methods read only
and right only as
per the requirement. So imagine if you didn't have
all this access modifiers, there's only one that is public
which is exposed to everyone
so it would create a Havoc. So this is basically based
on your requirements. You could have
different patterns
of this access modifiers used
within the application. It makes testing easy. So basically Hotpoint is
reuse ability easy to reuse
and easy to change
with the new requirement. So with reusability, even the maintainability
of the particular
application is improved when you have this encapsulation
and easy to reuse in the sense if imagine The way around
where in you have
only private methods so a class could access
only the instance variables within a class nothing
from outside world.
It cannot be accessed
from outside as well. Imagine such a scenario
right in that case. You would have a lot of code
redundancy right everywhere.
You would write the same code. It might be the same thing. We have already implemented
in some other class,
but you will have
to re-implement it since it's not accessible
outside the class. So that's how encapsulation
increases the reusability of who
and it makes testing easier. Of course. So here you could see
that employ one.
So this is the encapsulation
mutator method that I was talking about. So basically you
have employee one
which has got string name, which is private
you could see here. It's defined as private when I
say private this name property
would be used only
within this class. If you try to access it from outside class
you would get an error
but there might be scenarios in
which you want to Says this name from outside class you
want to understand what its value is in that case.
You would have something
like this right? You would have
getter method get name, which is nothing but
it's written type is string
which is the data type for name and it's returning the name. Now one thing to observe
here is this is public.
This one was Private name was
private but get name is public which means it could be accessed
from outside as well. Similarly.
You could have Setters
which is not a good practice. By the way, you
shouldn't have Setter methods. So again Setter is something
like you pass the value
that you want to set
this particular name variable. So basically you are saying
that whatever you send through this method is going
to set to the name variable.
So we are referred to this particular
example in Maine. So you create an instance
of employee one
who have edad set name
you're sitting at well X and when you access it
you do e dot get name. So basically what we
are trying to say here is
a demo end caps is a Glass it's not the same class. So you have employee one and you
have demo end caps as
a different class though. It's a different class till you are able to access
your name employee name
from this class. This is again, a private instance variable you
are able to do this just
because you have
this Getters and Setters, let understand interfaces
interfaces are nothing but could imagine
interface as a blueprint
or it is something that
it's a specification rather, right and interface could be
thought of as a specification. This is how it should be.
So basically it could be
a company manufacturing bottles or remote rate. It would say that this is
how it should be basically there
should be so-and-so buttons. There should be
this button should be here. This button should be there
and something of that sort.
So basically through interphase what we do is we specify
the contract we say that this is
how it should be now.
For example, you could have specification
mentioned in a piece of paper. This is how Remote should be
and there could be different
vendors for this remote who would be actual
manufacturing remote and which would be aligned
to this particular
remote specifications. Then you could check that. Okay, so and so specifications
are met which means
that this this particular thing
could be used as a remote. So basically these are nothing
but the specifications for the system so
through interphase you say
that this is how it should be and you
would have different vendors or you would have
different implementations
that align to the specifications and if they match up
to the specification, it means that it's
a correct one.
So hence an interface contains
all the specifications and can be used
for creating a new remote. So all you see here,
there's a joystick
this AC remote this TV remote and everything. It has got different things
but there's something
in common and that's what you specify through interface and interface
contains variables and methods
but the methods declared inside interface or by
default abstract methods. As we saw in the earlier
slide interface is
hundred percent abstract. So all the methods that you have
within interface is abstract and interface is used
to achieve abstraction.
It is used to achieve loose coupling when I
say loose coupling. It's like you are not binding
everything into a class.
Basically you say
that fits a remote. It has to have
this features, right? So basically your kind
of decoupling it or you can see
that all the implementations of remote will have
so-and-so specifications, which is been introduced
by interface also in Java,
you cannot have
multiple inheritance. You cannot have a class which extends multiple
classes cannot have car
which extends vehicle and
which extends the for example locomotive locomotive is
one of the classes if for example,
so, you cannot have a class which extends to classes
that is multiple inheritance. Do you could have levels
and you could have
hierarchical inheritance, but you cannot have
multiple inheritance. But through interfaces you
can have multiple inheritance
you could parlament
multiple interfaces, but not multiple classes again, since this is
inheritance interface is
hundred percent abstract class. And basically you
create sub classes from or you implement
an interface is nothing
but it follows
he's a relationship. So what's the difference
between interface and a class and interface can
never be instantiated
just to give you an example, I'll show you what interface is. So instead of this class.
I will make this interface. So this is how we Define an
interface we Define interface, but as I said,
the interface is
hundred percent abstract. Everything has to be attract. You cannot have methods
something of this sort.
You cannot have a concrete
implementation of method though. You could have a default method
which we would be looking at in the in the slides to come
but at this point,
let's imagine that you have
a ship class and whatever methods you
have you declared within your ship class has
to be Track a by default.
It is abstract. You did not even mention it by default jvm puts
it has abstract.
Even if you mention it abstract,
it's not a problem. It is abstract. So now when I unlike extends
that we do on glass
or for the face you implement it so you implement shape class. So you'll have to make it public
by default the access modifier
for a method the face is public. So here you can see that we have implemented
it we could see
that it has a hundred
percent abstract. So with this you could see most
of this differences being listed here and interface
should contain abstract methods,
which we saw class can contain
only concrete methods. We are talking about normal class here
not the abstract class.
The members of the interface
are always public which we again saw when I didn't implement
this one as public Circle
it gave me an error. So by default it is public the members of the class
can be private public
or protected and interface
can I have a Constructor since we are not
creating instance. The first point you
can see that interface is
cannot be instantiated since we
cannot instantiate interface. There's no need of Constructor
a class can have constructed to initialize the variables
which we met yesterday
implements keyword is used for inheritance and whereas
in terms of class, we have extends
which we saw now right
for interfaces you we changed it to implements
rather than exchange after extends keyword.
Any number of interfaces
can be given this is multiple inheritance
that we spoke about whereas after extends
you can have only
one and only one class. You cannot have multiple classes
cannot contain instance Fields. The only field
that can appear in our interface
must be declared both static and final
can contain instance Fields. So only the constants
would be declared
when your interfaces
whereas with in class. You can have all levels
of all the instance variables. Classes have implementation
whereas this is between class
and abstract class. So classes have implementation
abstract classes have no implementations or they
can have implementation as well.
So it's a mixture of abstract methods
and non abstract methods as we saw.
So abstract class is
not hundred percent abstract right unlike interfaces. You could have
concrete implementation
as well concrete classes
are instantiated to create object abstract classes cannot be instantiated
similar to interfaces
abstract classes cannot be
instantiated a concrete class can be final and abstract
class can never be final as it has no defined functions
for abstract class
to be a complete. It has to be extended. That's what the focus
is abstract class
and interface is an abstract
class can be extended with class using keyword extends and whereas interface
can be implemented
to a class using implements which we saw. Abstract class can extend
only one class at a time
and interface can extend number
of interfaces at a time. So yeah, this is one thing we're
in your interface can extend other interfaces, right
and you could have
multiple interfaces extended abstract class can have
private default protected and public members
and interface members are
default or by default public in abstract class keyword
abstract is mandatory to declare a method
as an abstract method
which we saw okay in interphase. It's not mandatory because by jvm by default put
set abstract classes
are to achieve zero to
hundred percent of abstraction, which means that you could have some concrete
implementation as well.
Whereas interfaces
or hundred percent abstract. You cannot have anything you
cannot have any implementation within but you could have
a default methods abstract class
can have abstract and on abstract methods
again here abstract class can have Constructors.
Interface cannot have
Constructors which we saw earlier abstract class can have abstract
and non abstract methods
since it's not a
hundred percent abstract. Whereas interface can have only
abstract methods by the way from java it as I said,
there's a default
method being introduced which is nothing but you could have a concrete
implementation written
within interface class interface
relationship you have class which extends other class you have class
which implements interface
you have interface which can extend other interface if there's an interface already
defined and you want to inherit
some methods or you want
to inherit the methods that you have within
the other interface would do it using extends
a class extends another class
while implements an interface and interface extends
another interface class cannot extend multiple classes,
but can Implement
multiple interfaces. So here you could see
that this one class. Which is extending
the class on the top
and this one at the right side. It's time to extend it. If you try to extend
multiple classes,
it would give you
a compile-time error. It won't allow you to inherit
from multiple classes. Whereas in this case,
you could see it's implementing
multiple interfaces on the top. You could see one interface
been implemented by this class and there's one more
interface to the right
which is being implemented
by this class class cannot extend multiple classes, but it could Implement
multiple interfaces
which gives an opening
for multiple inheritance when any interface gets compiled
compiler automatically adds access modifiers to the members.
So this is done by default
its internal Edition. So here you could
see interface demo which has got one variable
that is int count is equal to 10 and it has got a method
which is output now when this demo dot Java,
which is an interface, which gets compiled you See
that by default. It has put it as public static
final so count 10 would be given
access modifier public static
final so four variables jvm by itself puts public static final and four methods it would put
it as public abstract.
So that is the reason
when we had the area method when we try to override
it it gave an error saying that it has to be public.
So John went to a bank he
wants to credit some money to his account. So let's see this one.
So basically here you could see
to implementation of it you have money interface and you have
operation as its method. So now you could see
two implementations of it
one is debit and the other one
is credited with in debit. We are just saying that we are writing
a dummy statement.
They're saying that we are
debating money from this account whereas credit is nothing. But again, we
are printing saying
that we are crediting
money to this account. So now when you create
instance of money or you create in It's off credit
and assign it to money
and money dot operation. You would have operation method on credit being called
in this example.
We can see that there's
a shape interface which has abstract area
and there's a circle which returns this value right
and say I declare one more class
which is square which implements shape and its
again three main error saying that you will have
to declare it.
You will have to
implement the method so I will read this and say
I written some dummy value like hundred you have a square
and said Circle say circle area.
We are just hard
coding it right now. We don't have to implement it. So it gives you two hundred.
It's returning 200 as float. And this one
is returning hundred. So what we can do here is
we have this shape utility.
So here we have this thing
called on Circle. So I will just print
it out here saying And now I have one
more say for example,
I create one more shape which is square nothing
but Nu Square now what we are doing is we
are going to print out
where dot area so instead
of assigning to a variable you could do it this way
as well area of a square. What we did is we
have interface shape
and we have a area method
which is abstract. We have two concrete
implementations of it Circle and square
and we are instantiated circle and square here and we
are calling area method on it. By the way,
you could see here that this is
dynamic polymorphism Circle and square is been assigned
to the shape reference. It's not directly to the circle.
You would see hundred and
two hundred mean printer know so Circle was 200
and square was hundred and you could see two hundred
and hundred so it's basically
Dynamic polymorphisms followed in interface as well. You could extend an interface
with another interface.
So suppose you have
one more Switch is for now just too. So I create
an interface test interface
which has like test method. So you have a test interface
which has void test and you could have shape which
is extending test interface.
Now your circle and your Square
would give an error because there is one more method
that you need to implement. If you don't implement
it you will have
to either make this abstract. If you make it abstract, it should go off
but in this case suppose
we want to implement it
then you will have to ensure that you implement test method
as well once implemented the error should be gone
similarly in square.
You will have to find it. So that's what is extending one
interface with another right? So basically here you
could see there's walkable.
There's a runnable
and when you do it when you implement runnable, you will have to ensure
that you implement Walk and Run
both the methods. It's a class extending one class and implementing more
than one interface.
There's two interfaces
Walk and Run so you could see animal which implements walk and So
then it will have to implement
both the methods Walk and Run whereas there's a human glass
which extends animal. So this is basically
there's a class
which is implementing
multiple interfaces and which has to ensure that it implements
both the methods.
So in this case walk and run
it has to ensure that it implements Walk and Run
and this one class which is extending
from this particular class
and you could see here that you could assign human
which is extending which is a subclass of animal
we could see that human could be assigned
to walk and run as well since it is implemented from there.
So you could have H 1 dot walk and H 2 dot run sort
of you have given a call to this methods.
So basically this is again if you understand the idea
of runtime polymorphism or dynamic polymorphism,
which is nothing
but assigning the instance of subclass to superclass
you should get idea of me. All this thing we are pretty
much talking the same thing
all this is talking
about Dynamic polymorphism. If you get that thing,
right you have good enough. So we are talking
about default method right
since Java it you could
have default implementation within your interface. You could say that you
cannot have a concrete method
but you could have if you put a concrete methods
something like this, it would give you an error.
Okay, it gives you
an error saying that it's not allowed but you
could have it as default. Once you define is default.
It's good enough. So all this methods are all
these classes circle square and all these classes
would get would inherit
this they can't override it. They can't do anything with it, but they would inherit this we
can give a call though,
but he can't override it. So basically I'll
just show it here. So basically you
have default method
which is say say and
which is printing out. Hello. Welcome to edu Rekha, right
and you can see here. Flash interface demo, which is implementing welcome
and you could see here.
Hello bean concrete
implementation of L, which is nothing but
it's printing out the message that is passed
to the hello method so
though default class
interface demo doesn't declare say method it
inherits from welcome. When you do out dot say you
could see the default method
being invoked here. We could see that you know, hello welcome to edu
Drake has been printed out
which is nothing but the output
of default method so basically default methods
are not but method which cannot be overridden
but is available
for all the classes that implements a
particular interface or implements that interface
so rules for using
private methods in interfaces following all the rules
for using private methods in interfaces private interface
method cannot be abstract
private method can be used only inside interface
private static method can be called from other static.
Non-static interface methods
private non static methods cannot be called
from private static methods. This might look confusing
at this point,
but you could think that first
of all private interface method cannot be abstract because we want it
to be implemented in some
other implementation, right? We cannot keep it
private since interface by itself doesn't have
the implementation of it.
You want to implement
that method in some other class. So it cannot be private
private method can be used only inside interface.
So if we Define a private method
within an interface, it can be used only
within the interface. So basically you
could have a default method
which is private, right? So basically default method
itself cannot be private but within default method,
so what I am trying
to say is so here you could have private void
which is doing nothing but here your default method
would call this private method.
So private method can only
be used within the interface and it's usually used 24
get private static method can be called from other static.
This is pretty much similar
to other classes normal classes private non static methods
cannot be called from private static methods.
This is a common rule that we have private non
static methods cannot be called from private static method.
So if you have a static method
within the static method, you cannot call
a non static method. Remember we mentioned it earlier
unless we create
the instance of it. We can't call it. But in this case you
cannot call it at all.
So it's not on a class
you're invoking it basically within an interface. So private methods is
specifically you could call
Private methods from within
your default method in interface and since private methods are
not accessible from outside. That's the only reason you
could have private method
near interface static methods
in an interface. So you could have
something like this where in you have
interface one and you
have a static method display? You remember static
methods are more of a class level method, right?
You need not have to create instance of a class
to invoke a static method if an interface has
a static method you could call
it directly by interface dot
the name of the interface does the name of the method so we can have a static
method like static.
So this method could be called so you could have something
like this method and you could call it directly
using the interface name.
So we have this so now within shape utility
you could wreck akahl, like as you could see here,
you could call the static method directly by the name
of the interface. You cannot have
normal methods within it
unless it's a default
one interface features four different jdk version. So interface has evolved
throughout the versions
of JD case. So just to brief on that. We have jdk 121 .7
having normal interfaces
with constant static variables as we said the variables that you would have in a The
freezer typically constants
which is public static final
and with abstract methods, of course in Java 8 it evolved
and we have a default method as I said,
there would be
one default method which would be inherited by
all the interfaces extending that interface and you have
static methods as well,
which was not there earlier
in Java 9 and later versions. So in Industry right now, it's mostly Java 8
that's been used across
very few have gone to Java
9 all the big data Frameworks and everything we have
is supporting Java it at this point.
So with the latest version that's Java 9 and above we
have static constant static variables abstract methods
default method static methods
and they have come up
with this two methods which are nothing
but private methods and private static method,
which was not there earlier. Now you could have
this things as well. It makes very little sense to
have all this scope variables,
but maybe they might Have or something as
a part of evolution, but at this point,
I believe since this private
methods cannot be called from outside it just that you have control
over the default method.
So basically maybe if you have a big
logic to be written within your default method
just to modularize
it just to break it into multiple methods not to
have one monolith big function or big method you could have
this private methods.
That's what I can think. What is the package we have been
using package since day one. So package is nothing
but it's a namespace
it's for avoiding Collision. So basically I could write
a name class with name shape and maybe someone else
within my team would
write the same thing. Right? So basically at the end
when we archive it together
like we have a jar file, which is Java archive when we archive this files
together there is going
to be named Collision, right? You wouldn't know
which shape class. Are you referring to?
So basically namespace
is nothing but it adds. Stewart and it avoids
Collision classes in the same package can access
each other's members.
So basically you can have
within a package. So we'll talk about
the import statements that will give you
a clearer understanding
of what we are talking about. But basically within a package
as you could see here, we have not done anything
to refer any of these classes.
So it's within a package
we have calmed said Eureka and we have all these classes
within this package so you could see that employ
or maybe manager
which is a different class
in the same package. We are accessing it directly. We are not doing anything
different for it.
But when you want to access it from a different package you
have to do something else which is nothing
but importing the package
the normal living convention
is usually domain name here. You could see we
wenshan calm down at Eureka. So it's usually something
of that sort dorji dot
example dot hyphenated name. It has to be lower
case usually written in lower case companies
use their reversed.
Net domain name to begin
their package names. So basically if you have
my package or example.com, you would have it
in reverse order.
This is typically a one of
the best practices of practices that's been followed
across industry to define the package but it
doesn't have any constraints
from the Java side as such you could do anything. So for example,
if I make it uppercase,
so basically it's saying that it's not showing error
because of its in uppercase, but basically you don't have
a directory starting
with uppercase Aspire Java
or from the Java side. You don't have any constraints. For example, I could do
something like So basically it
does convert it into lower case, even if you give uppercase. I don't know whether this is
a feature in IntelliJ IDE,
or it is of course it has
to do something with the ID because Heidi is converting it
into lower case as far as the Java naming
convention is concerned.
This is what we do but it doesn't have constraint
Java predefined packages. So Java itself
has many packages.
So you could imagine
the entire language been written in Java source code. So basically all this you
would find in the source code
when we refer to the string when we refer
to string string is a class which resides in Java dot Lang.
There is Java dot language is
nothing but Java dot language. So string is something that resides in Java dot
Lang object is a class
which is a super class
for all the classes. So, you know,
what super classes are after we went through
the inheritance thing.
So you have super class
and you have subclasses. So the superclass All
the classes no matter what class you use with in Java.
All the classes are inherited
from a class called object. There is a class object in Java from which all
the classes have inherited
from our all the class inherit from this particular
class thread is used for multi-threading.
Java dot length of thread is used for multi-threading
multi-threading is nothing but 2 lightweight processes in
order to leverage the potential
of your processors. So if you have multi-core, then you could have
multiple operations happening
at the same instance of time. That's what thread is all for you make it faster
you have exception class
you have system class
Java dot language system. This package is used to achieve
the language functionality such as conversion
of data from string to fundamental data display
the output on the console and many more the package
is quoted by default.
So you don't have to
specifically explicitly import. This particular package is by default voted into
your application Java dot util.
This is like utility classes
you have Elections and stuff like that
into your Java dot util this package is used
for developing quality
or reliable applications
in Java or J2 ee this package contains
various classes and interfaces which improves the performance
of j2me application.
So basically these
are utility classes. It does something
in terms of performance or does some conversions
or something of that sort.
Java dot IO is a package
which contains something like file input stream
file output stream and stuff like that,
which is basically for interacting with
your files with your I/O. So basically if you want to load
something into your memory,
if you want to read
something from your file or write something go file
in your local directory, you would use something
like Java dot IO package
if you want to do some kind of
socket networking or some kind of network programming
you would use java.net which has something
like socket datagrampacket
datagram socket Etc. We have applet tablet is
nothing but application that gets loaded
into your browser.
It's not you. So as of now earlier
it is to be used but now there are a lot
of other technologies
that have come up
but this is something like an applet is a Java program which runs in the context of
w WR world wide web for browser.
You have Java dot e WT
which is like event-driven like you could
have UI applications. If you click on your checkbox
or button there
would be even triggered and you would have
an event handler handling it if you click on a mouse
or something you would have
a even triggered. So basically all these classes
are grouped into this package, which is Java dot AWD
so you could see
the Java dot w dot even which has like Mouse listener. This is specific to event
without this classes.
It is impossible to handle events generated by
G UI components. So as far as the front end
is concerned as
far as all this a WTF that is concerned. It's not in use basically.
Java is much more useful
in terms of back and program which means you take data
and Do something with your data and stuff like that,
but it's not well suited
for UI applications and it's not used to that extent
in Market or industry. You have Java dot SQL
which is nothing
but your database related stuff. So we want to connect to your post gray or if you
want to connect to Oracle.
You have all the stuff
written in Java dot SQL. So mostly in Java data skill, you have interfaces
and this interfaces
as I said, it's nothing but specifications and this specifications are
implemented by database vendors.
So it's nothing
but interface is just an abstract method it would have
like four five abstract methods within so all
this concrete implementation.
Someone will have two women
to use this interfaces or someone will have a class which will implement
this interface has and we
as developers can
use those classes to interact with databases. So Wenders like Oracle will have
its own set of implementation
to the Patients that are mentioned
in Java dot SQL as I said most of the thing
in Java dot SQL or interfaces.
So about the access modifier. We have spoken earlier. We have public we have protected
private and default modifier
public is nothing but
it could be accessed from anywhere within
your application. So you could have your methods
as public you could have
your class as public you could have your instance
variables as public which means that particular
method could be accessed
from anywhere within
your application. You could have protected
modifier protected modifier is nothing but your subclass
is can access it
and your current package
whatever the package in which a particular method or particular class resides in
which you have protected method.
You could access it
from that class or any class from
that particular package access the protected methods defined
within a class that package
so I will give you an example since we have spoken
about inheritance now, so I will give you a demo
on protected private.
Modifier is basically
it's private. It's within a class. You cannot access
it from outside.
If you try to access it, you would get a compile
time error saying that it's not visible default
modifier is package is public
within package So within package
any class can access it. So basically it's like protected right
protected can be accessed
within the package
plus it has like if a sub classes are
outside the package, even though subclasses
can access it
whereas in default. It's just within the package. So protected has wider scope
then default modifier.
This is kind of public so public
has almost like everything so why didn't scope then comes
protected then comes default and then comes private so access
modifiers public word Republic.
So when you have Public Access modifier
within a class in this case, you have two packages.
Are you Ricardo back one and a new record out back to
and you have some public members within your class one,
which we can see here
that all this public. Members could be accessed
by Class 2 class 3, which is there in the same
package as class 1 that is
at Eureka dot Pack 1. So now there are two classes
in a do record back to one is a class
which doesn't have
any relationship with glass one but still it
can access it though. It's there in
a different package.
But still it can access
the public members of class one. You can see class for which
is a child of last one since it extends class one,
but it's there
in a different package but still it can access
the public members of class 1 so protected protected is nothing
but it could be accessed
within the package in which the class is defined and it
could be accessed by members that are outside the package but
child of that particular class.
So in this case we can see that there are few protected
members in class one which could be accessed
by Class 2 and class 3
since they are in the same
package as class 1 plus 3 and class two are defined
in Eddie cannot pack 1 we have class 5 Is not related
to class 1 which means
it's not a subclass or it doesn't have any relationship with class
1 in that case class
5 cannot access any protected
members within class 1. So here we have class for which
extends class 1 which is nothing but plus 4 is a subclass
of class 1 which is there
in a different package
at your record back to but it can access
the protected members of class one
since it is there
in a different package private member is nothing
but it can be accessed just within the class
in which it is Define.
So in this case you could see
that this is private members. So you have class one
which has got private members and you can see
that class to contacts
is it class three contacts? Is it either class 4 or
plus 5 no one can access it. It's just that class
one can access private members.
So we have seen this in examples that we took in session
one default package. So default package is nothing
but only within the package
in which it is defined. It so in this case
you have class one which has got default members
with default scope
and you can see that class 2
and class 3 can access it but not class 4 and Class
5 since they are out of this package
since Class 2 and class 3 are
defined in the same package as class 1 that is
a deal-breaker DOT back one. That's the reason you
could access from there.
This is same for
attribute or method. There's a table here, which is summarizing whatever
we discussed so far you
have modified public. So yeah, it's within the class. Yes.
It's within the package. Yes, if it's
within the subclass. Yes and within the world days
so everywhere it
could be accessed right? That's why you have public
protected is within the class. Yes, within packages
within subclass.
Yes, but not within world. So just within
package and subclass, but if you have
different package or
if you have different package, but it's not a subclass. Then you can't access it.
No modifier, which is a default scope
within the classes within the Yes,
but we saw that it cannot be accessed
within the subclass if the subclass is
in a different package
when we save world world
is nothing but any package and they are not related in
this case the previous example that we should saw
last five is something
that could be thought of as laws
that are unrelated. But reside in a different
package private is just within the class you can see
