java intrvw conecpts details.docx
TRANSCRIPT
-
7/25/2019 java intrvw conecpts details.docx
1/70
next prev
Variable and Datatype in Java
1. Variable
2. Types of Variable
3. Data Types in Java
In this page, we will learn about the variable and java data types. Variable is a name of
memory location. There are three types of variables local, instance and static. There are
two types of datatypes in java, primitive and non!primitive.
Variable
Variable is name of reserved area allocated in memory.
1. intdata"#$%&&'ere data is variable
Types of Variable
There are three types of variables in java
local variable
http://www.javatpoint.com/unicode-system-in-javahttp://www.javatpoint.com/internal-details-of-jvmhttp://www.javatpoint.com/variable-datatype#variablehttp://www.javatpoint.com/variable-datatype#typesofvariablehttp://www.javatpoint.com/variable-datatype#datatypehttp://www.javatpoint.com/internal-details-of-jvmhttp://www.javatpoint.com/variable-datatype#variablehttp://www.javatpoint.com/variable-datatype#typesofvariablehttp://www.javatpoint.com/variable-datatype#datatypehttp://www.javatpoint.com/unicode-system-in-java -
7/25/2019 java intrvw conecpts details.docx
2/70
instance variable
static variable
Local Variable
( variable that is declared inside the method is called local variable.
Instance Variable
( variable that is declared inside the class but outside the method is called instance
variable . It is not declared as static.
Static variable
( variable that is declared as static is called static variable. It cannot be local.
)e will have detailed learning of these variables in ne*t chapters.
Example to understand the types of variables
1. class(+
2. intdata"#$%&&instance variable
3. staticintm"1$$%&&static variable. voidmethod-+
#. intn"/$%&&local variable
0. . &&end of class
Data Types in Java
-
7/25/2019 java intrvw conecpts details.docx
3/70
In java, there are two types of data types
primitive data types
non!primitive data types
Data Type Default Value Default s
boolean false 1 bit
char 4u$$$$ 2 byte
byte $ 1 byte
short $ 2 byte
int $ byte
long $5 6 byte
float $.$f byte
-
7/25/2019 java intrvw conecpts details.docx
4/70
double $.$d 6 byte
Why char uses 2 byte in java and what is \u0000 ?
because java uses unicode system rather than (78II code system. 4u$$$$ is the lowest
range of unicode system.To get detail about 9nicode see below.
JVM (Java Virtual Machine)
1.Java Virtual Machine
2.Internal Architecture of JVM
:V; -:ava Virtual ;achine is an abstract machine. It is a specification that provides runtime
environment in which java bytecode can be e*ecuted.
:V;s are available for many hardware and software platforms -i.e.:V; is plateform
dependent.
What is JVM?
It is
1. A specificationwhere woruntime
?nvironment.
3. Runtime Instance)henever you write java command on the command prompt to
run the java class, and instance of :V; is created.
What it does?
The :V; performs following operation
5oads code
http://www.javatpoint.com/internal-details-of-jvmhttp://www.javatpoint.com/internal-details-of-jvm#jvminternalarchhttp://www.javatpoint.com/internal-details-of-jvmhttp://www.javatpoint.com/internal-details-of-jvm#jvminternalarch -
7/25/2019 java intrvw conecpts details.docx
5/70
Verifies code
?*ecutes code
@rovides runtime environment
:V; provides definitions for the
;emory area
8lass file format
>egister set
Aarbage!collected heap
Batal error reporting etc.
Internal Architecture of JVM
5ets understand the internal architecture of :V;. It contains classloader, memory area,
e*ecution engine etc.
-
7/25/2019 java intrvw conecpts details.docx
6/70
1) Classloader:
8lassloader is a subsystem of :V; that is used to load class files.
2) Class(Method) Area:
8lass-;ethod (rea stores per!class structures such as the runtime constant pool, field and
method data, the code for methods.
3) Heap:
It is the runtime data area in which objects are allocated.
-
7/25/2019 java intrvw conecpts details.docx
7/70
4) Stack:
:ava 7tac< stores frames.It holds local variables and partial results, and plays a part in
method invocation and return.
?ach thread has a private :V; stac
-
7/25/2019 java intrvw conecpts details.docx
8/70
=efore 9nicode, there were many language standards
ASCII-(merican 7tandard 8ode for Information Interchange for the 9nited
7tates.
IS !!"#-1for )estern ?uropean 5anguage.
$I-!for >ussian.
%&1!'3' and &I%-"for chinese, and so on.
Tis caused to pro*lems:
1. ( particular code value corresponds to different letters in the various languagestandards.
2. The encodings for languages with large character sets have variable length.7ome
common characters are encoded as single bytes, other reDuire two or more byte.
To solve these problems, a new language standard was developed i.e. 9nicode 7ystem.
In unicode, character holds 2 byte, so java also uses 2 byte for characters.
loest value:4u$$$$
i+est value:4uBBBB
Constructor in ,avais a special type of methodthat is used to initialiEe the object.
:ava constructor is invoked at the time of object creation. It constructs the values i.e.
provides data for the object that is why it is
-
7/25/2019 java intrvw conecpts details.docx
9/70
There are two types of constructors
1. Fefault constructor -no!arg constructor
2. @arameteriEed constructor
Java Default Constructor( constructor that have no parameter is
-
7/25/2019 java intrvw conecpts details.docx
10/70
Q) What is the purpose of default constructor?
Fefault constructor provides the default values to the object li
-
7/25/2019 java intrvw conecpts details.docx
11/70
Java parameterized constructor
( constructor that have parameters is
-
7/25/2019 java intrvw conecpts details.docx
12/70
Example of Constructor Overloading
1. class7tudent#+2. intid%
3. 7tring name%
. intage%#. 7tudent#-inti,7tring n+0. id " i%
. name " n%6.
/. 7tudent#-inti,7tring n,inta+1$. id " i%
11. name " n%12. age"a%
13. 1. voiddisplay-+7ystem.out.println-idNJ JNnameNJ JNage%
1#.
10. pu*licstaticvoidmain-7tring argsKL+
1. 7tudent# s1 " ne7tudent#-111,JOaranJ%16. 7tudent# s2 " ne7tudent#-222,J(ryanJ,2#%
1/. s1.display-%2$. s2.display-%
21. 22.
Test it o
Mutput
111 Karan 0
222 Aryan 25
Difference between constructor and method in javaThere are many differences between constructors and methods. They are given below.
Java Constructor Java Method
8onstructor is used to initialiEe the state of an object. ;ethod is used to
object.
8onstructor must not have return type. ;ethod must hav
8onstructor is invo
-
7/25/2019 java intrvw conecpts details.docx
13/70
The java compiler provides a default constructor if you dont have any
constructor.
;ethod is not pro
case.
8onstructor name must be same as the class name. ;ethod name ma
class name.
Java Copy ConstructorThere is no copy constructor in java. =ut, we can copy the values of one object to
another li
-
7/25/2019 java intrvw conecpts details.docx
14/70
Mutput
111 Karan
111 Karan
Copying values without constructor)e can copy the values of one object into another by assigning the objects values to
another object. In this case, there is no need to create the constructor.
1. class7tudent+2. intid%
3. 7tring name%. 7tudent-inti,7tring n+
#. id " i%0. name " n%
. 6. 7tudent-+
/. voiddisplay-+7ystem.out.println-idNJ JNname%1$.
11. pu*licstaticvoidmain-7tring argsKL+12. 7tudent s1 " ne7tudent-111,JOaranJ%
13. 7tudent s2 " ne7tudent-%1. s2.id"s1.id%
1#. s2.name"s1.name%10. s1.display-%
1. s2.display-%16.
1/. Test it o
Mutput
111 Karan
111 Karan
Q) Does constructor return any value?
Ans:yes, that is current class instance -Pou cannot use return type yet it returns a value.
Can constructor perform other tasks instead of initialization?
http://www.javatpoint.com/opr/test.jsp?filename=Student7http://www.javatpoint.com/opr/test.jsp?filename=Student7 -
7/25/2019 java intrvw conecpts details.docx
15/70
Pes, li
-
7/25/2019 java intrvw conecpts details.docx
16/70
7uppose there are #$$ students in my college, now all instance data members will get
memory each time when object is created.(ll student have its uniDue rollno and name so
instance data member is good.'ere, college refers to the common property of all objects.If
we ma
-
7/25/2019 java intrvw conecpts details.docx
17/70
Program of counter without static variableIn this e*ample, we have created an instance variable named count which is incremented in
the constructor. 7ince instance variable gets the memory at the time of object creation,
each object will have the copy of the instance variable, if it is incremented, it wont reflect to
other objects. 7o each objects will have the value 1 in the count variable.
1. class8ounter+
2. intcount"$%&&will get memory when instance is created3.
. 8ounter-+
#. countNN%0. 7ystem.out.println-count%
. 6.
/. pu*licstaticvoidmain-7tring argsKL+
1$.11. 8ounter c1"ne8ounter-%
12. 8ounter c2"ne8ounter-%13. 8ounter c3"ne8ounter-%
-
7/25/2019 java intrvw conecpts details.docx
18/70
1.1#.
10. Test it o
Output:1
1
1
Program of counter by static variable
(s we have mentioned above, static variable will get the memory only once, if any object
changes the value of the static variable, it will retain its value.
1. class8ounter2+
2. staticintcount"$%&&will get memory only once and retain its value3.. 8ounter2-+
#. countNN%0. 7ystem.out.println-count%
. 6.
/. pu*licstaticvoidmain-7tring argsKL+1$.
11. 8ounter2 c1"ne8ounter2-%12. 8ounter2 c2"ne8ounter2-%
13. 8ounter2 c3"ne8ounter2-%1.
1#.
10. Test it o
Output:1
2
3
2) Java static methodIf you apply static
-
7/25/2019 java intrvw conecpts details.docx
19/70
Example of static method
1. &&@rogram of changing the common property of all objects-static field.
2.3. class7tudent/+
. introllno%#. 7tring name%
0. static7tring college " JIT7J%.
6. staticvoidchange-+/. college " J==FITJ%
1$. 11.
12. 7tudent/-intr, 7tring n+13. rollno " r%
1. name " n%
1#. 10.
1. voiddisplay -+7ystem.out.println-rollnoNJ JNnameNJ JNcollege%16.
1/. pu*licstaticvoidmain-7tring argsKL+
2$. 7tudent/.change-%21.
22. 7tudent/ s1 " ne7tudent/ -111,JOaranJ%23. 7tudent/ s2 " ne7tudent/ -222,J(ryanJ%
2. 7tudent/ s3 " ne7tudent/ -333,J7onooJ%2#.
20. s1.display-%2. s2.display-%
26. s3.display-%2/.
3$. Test it o
Output:111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT
Another example of static method that performs normal
calculation
1. &&@rogram to get cube of a given number by static method
2.3. class8alculate+
. staticintcube-int*+#. return*Q*Q*%
0. .
http://www.javatpoint.com/opr/test.jsp?filename=Student9http://www.javatpoint.com/opr/test.jsp?filename=Student9 -
7/25/2019 java intrvw conecpts details.docx
20/70
6. pu*licstaticvoidmain-7tring argsKL+/. intresult"8alculate.cube-#%
1$. 7ystem.out.println-result%11.
12. Test it o
Output:125
Restrictions for static method
There are two main restrictions for the static method. They are
1. The static method can not use non static data member or call non!static method
directly.
2. this and super cannot be used in static conte*t.
1. class(+2. inta"$%&&non static3.
. pu*licstaticvoidmain-7tring argsKL+
#. 7ystem.out.println-a%0.
. Test it o
Output:Copile Tie !rror
Q) why java main method is static?
(ns because object is not reDuired to call static method if it were non!static method,
jvm create object first then call main- method that will lead the problem of e*tra
memory allocation.
3) Java static block
o Is used to initialiEe the static data member.
o It is e*ecuted before main method at the time of classloading.
Example of static block
1. class(2+2. static+7ystem.out.println-Jstatic bloc< is invo
-
7/25/2019 java intrvw conecpts details.docx
21/70
3. pu*licstaticvoidmain-7tring argsKL+. 7ystem.out.println-J'ello mainJ%
#. 0.
Test it o
Output:static "lock is in#oked
$ello ain
Q) Can we execute a program without main() method?
(ns Pes, one of the way is static bloc< but in previous version of :FO not in :FO 1..
1. class(3+
2. static+3. 7ystem.out.println-Jstatic bloc< is invo
-
7/25/2019 java intrvw conecpts details.docx
22/70
. this can be passed as an argument in the method call.
#. this can be passed as argument in the constructor call.
0. this
-
7/25/2019 java intrvw conecpts details.docx
23/70
1. Test it o
Output:0 null
0 null
In the above e*ample, parameter -formal arguments and instance variables are same
that is why we are using this
-
7/25/2019 java intrvw conecpts details.docx
24/70
If local variables-formal arguments and instance variables are different, there is no need
to use this
-
7/25/2019 java intrvw conecpts details.docx
25/70
2) this() can be used to invoked current class constructor.
The this- constructor call can be used to invo
-
7/25/2019 java intrvw conecpts details.docx
26/70
0. 7tudent1-intid,7tring name+. tis.id " id%
6. tis.name " name%/.
1$. 7tudent1-intid,7tring name,7tring city+11. tis-id,name%&&now no need to initialiEe id and name
12. tis.city"city%13. 1. voiddisplay-+7ystem.out.println-idNJ JNnameNJ JNcity%
1#.
10. pu*licstaticvoidmain-7tring argsKL+1. 7tudent1 e1 " ne7tudent1-111,J
-
7/25/2019 java intrvw conecpts details.docx
27/70
Pou may invo
-
7/25/2019 java intrvw conecpts details.docx
28/70
3. 7ystem.out.println-Jmethod is invo
-
7/25/2019 java intrvw conecpts details.docx
29/70
Test it o
Output:10
6) The this keyword can be used to return current class instance.
)e can return the this
-
7/25/2019 java intrvw conecpts details.docx
30/70
. (# obj"ne(#-%6. 7ystem.out.println-obj%&&prints the reference IF
/.1$. obj.m-%
11. 12.
Test it o
Output:A522"3ea5
A522"3ea5
next prev
Inheritance in Java
1. Inheritance
2. ypes of Inheritance
3. !hy multiple inheritance is not possible in "ava in case of class#
Ineritance in ,avais a mechanism in which one object acDuires all the properties and
behaviors of parent object.
The idea behind inheritance in java is that you can create new classes that are built upon
e*isting classes. )hen you inherit from an e*isting class, you can reuse methods and
fields of parent class, and you can add new methods and fields also.
Inheritance represents the IS-A relationsip, also eusability.
Syntax of Java Inheritance
http://www.javatpoint.com/opr/test.jsp?filename=A5http://www.javatpoint.com/aggregation-in-javahttp://www.javatpoint.com/this-keywordhttp://www.javatpoint.com/inheritance-in-javahttp://www.javatpoint.com/inheritance-in-java#inheritancetypeshttp://www.javatpoint.com/inheritance-in-java#inheritancenotmultiplehttp://www.javatpoint.com/opr/test.jsp?filename=A5http://www.javatpoint.com/aggregation-in-javahttp://www.javatpoint.com/this-keywordhttp://www.javatpoint.com/inheritance-in-javahttp://www.javatpoint.com/inheritance-in-java#inheritancetypeshttp://www.javatpoint.com/inheritance-in-java#inheritancenotmultiple -
7/25/2019 java intrvw conecpts details.docx
31/70
1. class7ubclass!name e/tends7uperclass!name
2. +3. &&methods and fields
.
The e/tends 0eordindicates that you are maelationship between two classes is ro+rammer IS-A .mploee.It means
that @rogrammer is a type of ?mployee.
1. class?mployee+
2. floatsalary"$$$$%3.
. class@rogrammer e/tends?mployee+#. intbonus"1$$$$%
0. pu*licstaticvoidmain-7tring argsKL+. @rogrammer p"ne@rogrammer-%
-
7/25/2019 java intrvw conecpts details.docx
32/70
6. 7ystem.out.println-J@rogrammer salary isJNp.salary%
/. 7ystem.out.println-J=onus of @rogrammer isJNp.bonus%1$.
11.
Test it o
ro-raer salary is:400000
Bonus o& pro-raer is:10000
In the above e*ample, @rogrammer object can access the field of own class as well as of
?mployee class i.e. code reusability.
Types of inheritance in javaMn the basis of class, there can be three types of inheritance in java single, multilevel
and hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface
only. )e will learn about interfaces later.
http://www.javatpoint.com/opr/test.jsp?filename=Programmerhttp://www.javatpoint.com/opr/test.jsp?filename=Programmer -
7/25/2019 java intrvw conecpts details.docx
33/70
Note: ultiple inheritance is not supported in java throu!h class.
)hen a class e*tends multiple classes i.e.
-
7/25/2019 java intrvw conecpts details.docx
34/70
3.
. class=+#. voidmsg-+7ystem.out.println-J)elcomeJ%
0. . class8 e/tends(,=+&&suppose if it were
6.
/. @ublic 7tatic voidmain-7tring argsKL+1$. 8 obj"ne8-%
11. obj.msg-%&&Row which msg- method would be invo
-
7/25/2019 java intrvw conecpts details.docx
35/70
1) super is used to refer immediate parent class
instance variable.
Problem without super keyword
1. classVehicle+2. intspeed"#$%
3. . class=i
-
7/25/2019 java intrvw conecpts details.docx
36/70
Test it o
Output:50
2) super is used to invoke parent class constructor.The super
-
7/25/2019 java intrvw conecpts details.docx
37/70
the first statement of the constructor.
Another example of super keyword where super() is provided by the
compiler implicitly.
1. classVehicle+2. Vehicle-+7ystem.out.println-JVehicle is createdJ%
3. .
#. class=i
-
7/25/2019 java intrvw conecpts details.docx
38/70
7elcoe
In the above e*ample 7tudent and @erson both classes have message- method if we
call message- method from 7tudent class, it will call the message- method of 7tudent
class not of @erson class because priority is given to local.
In case there is no method in subclass as parent, there is no need to use super. In the
e*ample given below message- method is invo
-
7/25/2019 java intrvw conecpts details.docx
39/70
voidanotherEat*+ ) super-eat*+0 11
publicclassest)
publicstaticvoidmain*,tring23 args+ ) Animala 4 newAnimal*+0 a-eat*+0 %ogd 4 new%og*+0 d-eat*+0 d-anotherEat*+0 11
The output is going to be
animal / eatdog / eatanimal / eat
The third line is printing "animal:eat" because we are calling super-eat*+. Ifwe called this-eat*+, it would have printed as "dog:eat".
Aggregation in Java
If a class have an entity reference, it is
-
7/25/2019 java intrvw conecpts details.docx
40/70
Why use Aggregation?
Bor 8ode >eusability.
,imple Example of Aggregation
In this e*ample, we have created the reference of Mperation class in the 8ircle class.
1. classMperation+2. intsDuare-intn+
3. returnnQn%.
#. 0.
. class8ircle+
6. Mperation op%&&aggregation/. dou*lepi"3.1%
1$.11. dou*learea-intradius+
12. op"neMperation-%
13. int rsDuare"op.sDuare-radius%&&code reusability -i.e. delegates the method call.1. returnpiQrsDuare%
1#. 10.
1.16.
1/. pu*licstaticvoidmain-7tring argsKL+
2$. 8ircle c"ne8ircle-%21. dou*leresult"c.area-#%22. 7ystem.out.println-result%
23. 2.
Test it o
Output:(85
http://www.javatpoint.com/opr/test.jsp?filename=Circlehttp://www.javatpoint.com/opr/test.jsp?filename=Circle -
7/25/2019 java intrvw conecpts details.docx
41/70
When use Aggregation?
8ode reuse is also best achieved by aggregation when there is no is!a relationship.
Inheritance should be used only if the relationship is!a is maintained throughout the
lifetime of the objects involved% otherwise, aggregation is the best choice.
$nderstanding meaningful example of Aggregation
In this e*ample, ?mployee has an object of (ddress, address object contains its own
informations such as city, state, country etc. In such case relationship is ?mployee '(7!(
address.
Address.java
1. pu*licclass(ddress +2. 7tring city,state,country%
3.. pu*lic(ddress-7tring city, 7tring state, 7tring country +
#. tis.city " city%0. tis.state " state%
. tis.country " country%
6. /.
1$.
Emp.java
1. pu*licclass?mp +
2. intid%3. 7tring name%
. (ddress address%#.
0. pu*lic?mp-intid, 7tring name,(ddress address +. tis.id " id%
6. tis.name " name%
/. tis.address"address%1$. 11.
12. voiddisplay-+
13. 7ystem.out.println-idNJ JNname%1. 7ystem.out.println-address.cityNJ JNaddress.stateNJ JNaddress.country%
1#. 10.
1. pu*licstaticvoidmain-7tringKL args +
-
7/25/2019 java intrvw conecpts details.docx
42/70
16. (ddress address1"ne(ddress-JgEbJ,J9@J,JindiaJ%1/. (ddress address2"ne(ddress-JgnoJ,J9@J,JindiaJ%
2$.21. ?mp e"ne?mp-111,JvarunJ,address1%
22. ?mp e2"ne?mp-112,JarunJ,address2%23.
2. e.display-%2#. e2.display-%20.
2.
26.
Test it o
Output:111 #arun
-9" india
112 arun
-no india
prev
Object Cloning in Java
The o*,ect clonin+is a way to create e*act copy
of an object. Bor this purpose, clone- method of Mbject class is used to clone an object.
The,avalan+Clonea*le interfacemust be implemented by the class whose object clone
we want to create. If we dont implement 8loneable interface, clone- method
generates CloneotSupported./ception.
http://www.javatpoint.com/opr/test.jsp?filename=Emphttp://www.javatpoint.com/encapsulationhttp://www.javatpoint.com/opr/test.jsp?filename=Emphttp://www.javatpoint.com/encapsulation -
7/25/2019 java intrvw conecpts details.docx
43/70
The clone() metodis defined in the Mbject class. 7ynta* of the clone- method is as
follows
1. protectedMbject clone- tros8loneRot7upported?*ception
Why use clone() method ?
The clone() metodsaves the e*tra processing tas< for creating the e*act copy of an
object. If we perform it by using the new
-
7/25/2019 java intrvw conecpts details.docx
44/70
Output:101 ait
101 ait
download the example of ob"ect cloning
(s you can see in the above e*ample, both reference variables have the same value. Thus,
the clone- copies the values of an object to another. 7o we dont need to write e*plicit code
to copy the value of an object to another.
If we create another object by new
-
7/25/2019 java intrvw conecpts details.docx
45/70
The final
-
7/25/2019 java intrvw conecpts details.docx
46/70
2) Java final methodIf you ma
-
7/25/2019 java intrvw conecpts details.docx
47/70
1. class=iFHR9;=?>%#. ...
0.
Que) Can we initialize blank final variable?
Pes, but only in constructor. Bor e*ample
1. class=i
-
7/25/2019 java intrvw conecpts details.docx
48/70
Method Overriding in Java
1.Understanding problem without method overriding
2.Can we override the static method
3.method overloading vs method overriding
If subclass -child class has the same method as declared in the parent class, it is
-
7/25/2019 java intrvw conecpts details.docx
49/70
0. pu*licstaticvoidmain-7tring argsKL+. =i
-
7/25/2019 java intrvw conecpts details.docx
50/70
1. class=anateMfInterest-+return$%3. .
#. class7=I e/tends=anateMfInterest-+return6%
. 6.
/. classI8I8I e/tends=anateMfInterest-+return%
11. 12. class(SI7 e/tends=anateMfInterest-+return/%1.
1#.
10. classTest2+1. pu*licstaticvoidmain-7tring argsKL+
16. 7=I s"ne7=I-%
1/. I8I8I i"neI8I8I-%2$. (SI7 a"ne(SI7-%
21. 7ystem.out.println-J7=I >ate of Interest JNs.get>ateMfInterest-%22. 7ystem.out.println-JI8I8I >ate of Interest JNi.get>ateMfInterest-%
23. 7ystem.out.println-J(SI7 >ate of Interest JNa.get>ateMfInterest-%2.
2#.
Test it o
Output:
SBI ;ate o& Interest: 8
ICICI ;ate o& Interest: (
A
-
7/25/2019 java intrvw conecpts details.docx
51/70
Ro, static method cannot be overridden. It can be proved by runtime polymorphism, so we
will learn it later.
Why we cannot override static method?
because static method is bound with class whereas instance method is bound with object.
7tatic belongs to class area and instance belongs to heap area.
Can we override java main method?
Ro, because main is a static method.
Difference between method overloading and
method overriding in java
There are many differences between method overloading and method overriding in java. (
list of differences between method overloading and method overriding are given below
No. Method Overloading Method Overrid
1
;ethod overloading is used to increase the readabilityof the
program.
;ethod overriding i
specific implementa
already provided by
2
;ethod overloading is performed within class. ;ethod overriding o
have I7!( -inherita
3
In case of method overloading,parameter must be different. In case of method o
must be same.
;ethod overloading is the e*ample of compile time
polymorphism.
;ethod overriding i
polymorphism.
-
7/25/2019 java intrvw conecpts details.docx
52/70
#
In java, method overloading cant be performed by changing
return type of the method only. Return type can be same or
differentin method overloading. =ut you must have to change
the parameter.
Return type must b
method overriding.
Java Method Overloading example1. classMverloading?*ample+2. staticintadd-inta,intb+returnaNb%
3. staticintadd-inta,intb,intc+returnaNbNc%.
Java Method Overriding example1. class(nimal+
2. voideat-+7ystem.out.println-Jeating...J%3. . classFog e/tends(nimal+
#. voideat-+7ystem.out.println-Jeating bread...J%0.
Encapsulation in Java
.ncapsulation in ,avais aprocess of wrapping code and data together into a single unit,
for e*ample capsule i.e. mi*ed of several medicines.
)e can create a fully encapsulated class in java by ma
-
7/25/2019 java intrvw conecpts details.docx
53/70
=y providing only setter or getter method, you can ma
-
7/25/2019 java intrvw conecpts details.docx
54/70
olmorpism in ,avais a concept by which we can perform a single action by different
ways. @olymorphism is derived from 2 gree< words poly and morphs. The word JpolyJ
means many and JmorphsJ means forms. 7o polymorphism means many forms.
There are two types of polymorphism in java compile time polymorphism and runtimepolymorphism. )e can perform polymorphism in java by method overloading and method
overriding.
If you overload static method in java, it is the e*ample of compile time polymorphism. 'ere,
we will focus on runtime polymorphism in java.
Runtime Polymorphism in JavaRuntime polmorpismor 4namic 5etod 4ispatcis a process in which a call to an
overridden method is resolved at runtime rather than compile!time.
In this process, an overridden method is called through the reference variable of a
superclass. The determination of the method to be called is based on the object being
referred to by the reference variable.
5ets first understand the upcasting before >untime @olymorphism.
Upcasting
)hen reference variable of @arent class refers to the object of 8hild class, it is
-
7/25/2019 java intrvw conecpts details.docx
55/70
Example of 8ava 9untime Polymorphism
In this e*ample, we are creating two classes =i
-
7/25/2019 java intrvw conecpts details.docx
56/70
Rote It is also given in method overriding but there was no upcasting.
1. class=anateMfInterest-+return$%
3. .
#. class7=I e/tends=anateMfInterest-+return6%.
6./. classI8I8I e/tends=anateMfInterest-+return%
11. 12. class(SI7 e/tends=anateMfInterest-+return/%
1. 1#.
10. classTest3+1. pu*licstaticvoidmain-7tring argsKL+
16. =an< b1"ne7=I-%1/. =an< b2"neI8I8I-%
2$. =an< b3"ne(SI7-%21. 7ystem.out.println-J7=I >ate of Interest JNb1.get>ateMfInterest-%
22. 7ystem.out.println-JI8I8I >ate of Interest JNb2.get>ateMfInterest-%23. 7ystem.out.println-J(SI7 >ate of Interest JNb3.get>ateMfInterest-%
2. 2#.
Test it o
Output:
SBI ;ate o& Interest: 8
ICICI ;ate o& Interest: (
http://www.javatpoint.com/opr/test.jsp?filename=Test3http://www.javatpoint.com/opr/test.jsp?filename=Test3 -
7/25/2019 java intrvw conecpts details.docx
57/70
Auntime @olymorphism with multilevel inheritance.
1. class(nimal+2. voideat-+7ystem.out.println-JeatingJ%
3. .
#. classFog e/tends(nimal+
0. voideat-+7ystem.out.println-Jeating fruitsJ%. 6.
/. class=abyFog e/tendsFog+1$. voideat-+7ystem.out.println-Jdrin
-
7/25/2019 java intrvw conecpts details.docx
58/70
1#. a2"neFog-%10. a3"ne=abyFog-%
1.16. a1.eat-%
1/. a2.eat-%2$. a3.eat-%
21. 22.
Test it o
Output: eatin-
eatin- &ruits
drinkin- *ilk
Try for Output
1. class(nimal+2. voideat-+7ystem.out.println-Janimal is eating...J%3.
.#. classFog e/tends(nimal+
0. voideat-+7ystem.out.println-Jdog is eating...J%.
6./. class=abyFog1 e/tendsFog+
1$. pu*licstaticvoidmain-7tring argsKL+11. (nimal a"ne=abyFog1-%
12. a.eat-%
13. Test it o
Output: Do- is eatin-
7ince, =abyFog is not overriding the eat- method, so eat- method of Fog class is invo
-
7/25/2019 java intrvw conecpts details.docx
59/70
2. new #eyword
Java Strin+provides a lot of concepts that can be performed on a string such as compare,
concat, eDuals, split, length, replace, compareTo, intern, substring etc.
In java, string is basically an object that represents seDuence of char values.
(n array of characters wor
-
7/25/2019 java intrvw conecpts details.docx
60/70
1) String Literal
:ava 7tring literal is created by using double Duotes. Bor ?*ample
1. 7tring s"JwelcomeJ%
?ach time you create a string literal, the :V; chec
-
7/25/2019 java intrvw conecpts details.docx
61/70
that it will find the string with the value J)elcomeJ in the pool, it will not create new object
but will return the reference to the same instance.
Note: String objects are stored in a special memory area known as string constant pool.
Why java uses concept of string literal?
To ma
-
7/25/2019 java intrvw conecpts details.docx
62/70
e?aple
Java String class methods
The java.lang.7tring class provides many useful methods to perform operations on seDuence
of char values.
No. Method Description
1 char char(t-int inde* returns char value
2 int length- returns string lengt
3 static 7tring format-7tring format, Mbject... args returns formatted s
static 7tring format-5ocale l, 7tring format, Mbject... args returns formatted s
# 7tring substring-int beginInde* returns substring fo
0 7tring substring-int beginInde*, int endInde* returns substring fo
end inde*
boolean contains-8har7eDuence s returns true or fals
seDuence of char va
6 static 7tring join-8har7eDuence delimiter, 8har7eDuence...
elements
returns a joined str
/ static 7tring join-8har7eDuence delimiter, IterableGC e*tends
8har7eDuence elements
returns a joined str
1$ boolean eDuals-Mbject another chec
-
7/25/2019 java intrvw conecpts details.docx
63/70
1# 7tring trim- returns trimmed st
trailing spaces
10 7tring split-7tring rege* returns splitted stri
1 7tring split-7tring rege*, int limit returns splitted stri
limit
16 7tring intern- returns interned str
1/ int inde*Mf-int ch returns specified ch
2$ int inde*Mf-int ch, int fromInde* returns specified ch
with given inde*
21 int inde*Mf-7tring substring returns specified su
22 int inde*Mf-7tring substring, int fromInde* returns specified su
with given inde*
23 7tring to5ower8ase- returns string in low
2 7tring to5ower8ase-5ocale l returns string in low
locale.
2# 7tring to9pper8ase- returns string in up
20 7tring to9pper8ase-5oca
next prev
Immutable String in Java
In java, strin+ o*,ects are immuta*le. Immutable simply means unmodifiable or
unchangeable.
Mnce string object is created its data or state cant be changed but a new string object is
created.
5ets try to understand the immutability concept by the e*ample given below
http://www.javatpoint.com/java-string-trimhttp://www.javatpoint.com/java-string-splithttp://www.javatpoint.com/java-string-splithttp://www.javatpoint.com/java-string-internhttp://www.javatpoint.com/java-string-indexofhttp://www.javatpoint.com/java-string-indexofhttp://www.javatpoint.com/java-string-indexofhttp://www.javatpoint.com/java-string-indexofhttp://www.javatpoint.com/java-string-tolowercasehttp://www.javatpoint.com/java-string-tolowercasehttp://www.javatpoint.com/java-string-touppercasehttp://www.javatpoint.com/java-string-touppercasehttp://www.javatpoint.com/string-comparison-in-javahttp://www.javatpoint.com/string-handling-in-javahttp://www.javatpoint.com/java-string-trimhttp://www.javatpoint.com/java-string-splithttp://www.javatpoint.com/java-string-splithttp://www.javatpoint.com/java-string-internhttp://www.javatpoint.com/java-string-indexofhttp://www.javatpoint.com/java-string-indexofhttp://www.javatpoint.com/java-string-indexofhttp://www.javatpoint.com/java-string-indexofhttp://www.javatpoint.com/java-string-tolowercasehttp://www.javatpoint.com/java-string-tolowercasehttp://www.javatpoint.com/java-string-touppercasehttp://www.javatpoint.com/java-string-touppercasehttp://www.javatpoint.com/string-comparison-in-javahttp://www.javatpoint.com/string-handling-in-java -
7/25/2019 java intrvw conecpts details.docx
64/70
1. classTestimmutablestring+
2. pu*licstaticvoidmain-7tring argsKL+3. 7tring s"J7achinJ%
. s.concat-J Tendul
-
7/25/2019 java intrvw conecpts details.docx
65/70
still refers to J7achinJ not to J7achin Tendul
-
7/25/2019 java intrvw conecpts details.docx
66/70
)e can compare string in java on the basis of content and reference.
It is used in autentication-by eDuals- method, sortin+-by compareTo-
method, reference matcin+-by "" operator etc.
There are three ways to compare string in java
1. =y eDuals- method
2. =y " " operator
3. =y compareTo- method
1) String compare by equals() methodThe 7tring eDuals- method compares the original content of the string. It compares values
of string for eDuality. 7tring class provides two methods
o pu*lic *oolean e6uals(*,ect anoter)compares this string to the specified
object.
o pu*lic *oolean e6ualsI+noreCase(Strin+ anoter)compares this 7tring to
another string, ignoring case.
1. classTeststringcomparison1+
2. pu*licstaticvoidmain-7tring argsKL+3. 7tring s1"J7achinJ%
. 7tring s2"J7achinJ%#. 7tring s3"ne7tring-J7achinJ%
0. 7tring s"J7auravJ%. 7ystem.out.println-s1.eDuals-s2%&&true
6. 7ystem.out.println-s1.eDuals-s3%&&true
-
7/25/2019 java intrvw conecpts details.docx
67/70
/. 7ystem.out.println-s1.eDuals-s%&&false1$.
11. Test it o
Output:true
true
&alse
1. classTeststringcomparison2+
2. pu*licstaticvoidmain-7tring argsKL+3. 7tring s1"J7achinJ%
. 7tring s2"J7(8'IRJ%#.
0. 7ystem.out.println-s1.eDuals-s2%&&false. 7ystem.out.println-s1.eDualsIgnore8ase-s3%&&true
6.
/. Test it o
Output:&alse
true
8lic< me for more about eDuals- method
2) String compare by == operatorThe " " operator compares references not values.
1. classTeststringcomparison3+
2. pu*licstaticvoidmain-7tring argsKL+3. 7tring s1"J7achinJ%
. 7tring s2"J7achinJ%#. 7tring s3"ne7tring-J7achinJ%
0. 7ystem.out.println-s1""s2%&&true -because both refer to same instance. 7ystem.out.println-s1""s3%&&false-because s3 refers to instance created in nonpo
ol6.
/. Test it o
Output:true
&alse
http://www.javatpoint.com/opr/test.jsp?filename=Teststringcomparison1http://www.javatpoint.com/opr/test.jsp?filename=Teststringcomparison2http://www.javatpoint.com/java-string-equalshttp://www.javatpoint.com/opr/test.jsp?filename=Teststringcomparison3http://www.javatpoint.com/opr/test.jsp?filename=Teststringcomparison1http://www.javatpoint.com/opr/test.jsp?filename=Teststringcomparison2http://www.javatpoint.com/java-string-equalshttp://www.javatpoint.com/opr/test.jsp?filename=Teststringcomparison3 -
7/25/2019 java intrvw conecpts details.docx
68/70
3) String compare by compareTo() methodThe 7tring compareTo- method compares values le*icographically and returns an integer
value that describes if first string is less than, eDual to or greater than second string.
7uppose s1 and s2 are two string variables. If
o s1 77 s2$
o s1 8 s2 positive value
o s1 9 s2 negative value
1. classTeststringcomparison+2. pu*licstaticvoidmain-7tring argsKL+
3. 7tring s1"J7achinJ%
. 7tring s2"J7achinJ%#. 7tring s3"J>atanJ%
0. 7ystem.out.println-s1.compareTo-s2%&&$
. 7ystem.out.println-s1.compareTo-s3%&&1-because s1s36. 7ystem.out.println-s3.compareTo-s1%&&!1-because s3 G s1
/. 1$.
Test it o
Output:0
1
=1
String Concatenation in Java
In java, string concatenation forms a new string that isthe combination of multiple strings.
There are two ways to concat string in java
1. =y N -string concatenation operator
2. =y concat- method
1) String Concatenation by + (string concatenation)
operator:ava string concatenation operator -N is used to add strings. Bor ?*ample
http://www.javatpoint.com/opr/test.jsp?filename=Teststringcomparison4http://www.javatpoint.com/opr/test.jsp?filename=Teststringcomparison4 -
7/25/2019 java intrvw conecpts details.docx
69/70
1. classTest7tring8oncatenation1+2. pu*licstaticvoidmain-7tring argsKL+
3. 7tring s"J7achinJNJ Tendul
-
7/25/2019 java intrvw conecpts details.docx
70/70
Sac+in Tendulkar