Advance Java
Advance Java
StringBuffer StringBuilder
StringBuffer operations are thread-safe StringBuilder operations are not thread-
and synchronized safe are not-synchronized.
StringBuffer is to used when multiple StringBuilder is used in a single-threaded
threads are working on the same String environment.
StringBuffer performance is slower when StringBuilder performance is faster when
compared to StringBuilder compared to StringBuffer
Syntax: StringBuffer var Syntax: StringBuilder var
= new StringBuffer(str); = new StringBuilder(str);
No. String StringBuffer
2) String is slow and consumes more memory when we concatenate StringBuffer is fast an
too many strings because every time it creates new instance. consumes less memo
when we concatenat
3) String class overrides the equals() method of Object class. So you StringBuffer class do
can compare the contents of two strings by equals() method. override the equals()
of Object class.
Some Pointer :-
Q difference between return and System.exit(0)?
Ans:- return control ko calling method ke pass le jata hai and
System.exit(0) control ko main() method se bhi bahar le jata hai.
Web browser data ko http request ki help Web Server ko pahochata hai. and Web
Server http response ki help se data Web Browser ko deta hai.
Hum advance java ki help se Web Application banate hai.
HTML se hum form ye sab ready karte hai.HTML ke father Tim Berners Lee hai or es
language ki khoj unhone 1993 me ki thi.
CSS se uski styling karte hai.
Java Script se hum validation lagate hai. Validation ka mtlab check karna ki data
valid hai ya nhi.
Jo web Browser se data ko fill karte hai usse web server pr store karane ka kam
servlet karta hai. Servlet java ki ek class hai.
Hum pahle project Apache Tomcat ki help se Notepad++ me banana sikhege uske
baad NetBeans pr banayege kyo ki netbens bahot sare fetures by default deeta hai
but hum internal working ko samjhne ke liye pahle Notepad++ hi use karege.
Jis tarha AWT ka advance version Swing kahlata hai. Vese hi servlet ka advance
version JSP(Jakarta Server Pages) kahlata hai.
Server se aye hoye data ko store karne ke liye hum MySQL ka use karege.
Web Browser:- Web Browser ek client,program,software or tool hota hai. Jiske dovara
hum HTTP request web server ko sent karte hai. Ye janta hai ki ese server se kese
communicate kerna hai. Web Browser ka main purpose hota hai ki ye locate karna ki apka
content kaha hai World Wide Web pr . or jo server se response ata hai
image ,text,video ,audio ke form me usse display karna. Ex:- WWW , FireFox, Opera mini,
Safari, google Chrome .
Web Browser me Web ka mtlba hota hai jaal jisko computer ki language me
Internet ka name diya hai. Or Browser ka mtlab hota hai dhundna.
Web Server :- Web Server ko hum software bhi kah sakte hai or hardware bhi kah sakte
hai. Jo HTTP request leta hai or resources ko find ker ke response deeta hai Client
ko.Web Servers serf Web Application ko service provide karvate hai baki kise ko nhi.
Client or server ke beach me jo bhi communication hota hai vo usse HTTP request ke form
me hota hai.
Web Server bahot type ke hote hai jese apache hota hai jisne hume Tomcat web
server diya hai.
1.HTML
Html me ek <head> </head> and <body> </body> tag hote hai <head> me <title>
</title> hota hai and body me peragrah and heading ye sab hota hai.
Html ka full form hyper text markup language hai.
Created by tim berners-lee hai.
Ye specifically wirld wide web pages bana ne ke liye banaya tha.
Features of HTML
Html non case sensitive language hai.
Html atributes 2 “<” “>” ke ander likhte hai.
Html tags <html> </html> ke ander hi likhte hai.
Esme first <html> start tag hota hai and </html> ending tag hota hai.
Points
Yadi hum cahate hai line change ho jaye us String ko paragraph tag <p> </p> ke
beache me likhte hai.
Yadi background color change karna hai to <body > tag ke ander hume
bgcolor=”red” . Ex:- <body bgColor=”red”>
Yadi text ko align karna hai to Ex:- <p align=”Center”>Manish </p>
Yadi hum cahate hai ki word pr cursor le jane se kuvh msg show ho to
Ex:- <p title=”MSG”>Softwaves</p>
Heading me sabse bada size <h1> </h1> ka hota hai.hum heading me <h6></h6>
tak de sakte hai.
Heading by default bold hoti hai. peragraph nhi hota hai .
1 heading ke bad dusri heading next line se ati hai. Hum esme align and title
attribute bhi laga sakte hai.
Paragraph change karne pr by default 1 line ka gap chod deta hai.but yadi hum
cahate hai serf line change ho to <br> tag ka use karege jaha se line change karna
hai vaha.
Yadi text ko bold karna hai to <b>manish</b> ka use karege.
Yadi italic karna hai to <i>Manish</i>
Yadi under line karna hai to <u>Manish</u>
Yadi Striking karna hai to <s>Manish</s>
Jo kam <b> tage karta hai vhi kam <stong> tage bhi karta hai.
Yadi tag ko normal size se bada karna hai to <big></big>
Yadi normal se chota karvana hai to <small></small>
Yadi hum cahate hai ki base pr value aye like H2SO4 jesa hum likhte hai to
subscript tage <sub></sub> ka use karege
Ex:- <p> H <sub> 2</sub> SO <sub> 4 </sub> </p>
Yadi hum cahate hai power me aa ker show ho like 2 ki power 5 =32 so
Ex:- <p> 2<sup> 5</sup> =32</p>
Yadi font ka size change karna hai to <font size=”1”></font> tag ka use karge.hum
size 7 tak hi save ker sakte hai usse jiyada dene pr bhi vaha 7 tak hi manega.
Yadi hume font ka style change karna hai to face attribute ka use karege
Ex:- <font size=”1” face=”style name”></font>
Yadi hum horizontal line lana cahet hai to <hr> tag ka use karege.
Hum Color height and width bhi set kar sakte hai .
Ex:- <hr size =”10” width=”10” height = “10”>
Yadi hum cahate hai ki text screen pr move kare to hume <marquee> tag ka use
karna hoga . ye by default right se left direction me move karta hai.
Ex:- <p><marquee bgColor=”red”><fontcolor=”white”>softwaves</font>
</marquee></p>
Yadi hume direction change karna hai to direction=”left” lik sakte hai inside
<marquee> tag
Hum marquee ki hight and width set ker sakte hai .
Yadi hum content me word ke beach space cahate hai to   ka use karege
1 = 1 space hota hai.
Yadi hum cahate hai jesa humne likha hai vesa hi aa ker disply ho space ke sath to
preformeted text tag<pre></pre> ka use karege .
Yadi hum image display karvana cahate hai to
Ex:- <img src=”image name.type of image”>
src mtlab sorce mtlab image kaha pr rakhi hai.
Jaha program save hai vhi pr image ko rakhna hai.
Yadi hume image ka size set karna hai to width and hight ka use kar sakte hai.
Yadi kisi condition me image nhi ati hai to us condition ke liye hum ulternative
word de sakte hai. alt=””
Ex:- <img src=”Name” alt=”softwaves”>
Yadi image aa jayegi to alternative text nhi dikhega.
Hspace and vspace ki help se hum image ke beach gap de sakte hai.
Yadi hum image ke just pass se kuch text cahate hai to to image ki height, width
and align set karna hoga.
Yadi hum us image ke neache cahiye to utne break lagana hoga hum cahate hai ye
na karna pade to <br clear=”left”> kerne se jaha se image end hogi vhi se text
ayega.
Yadii hum cahate hai 10 image ek hi line me aye usme gap na ho to sabhi <img> tag
ko ek hi line me rakh do.
Table create karne ke liye <table > tab ke ander <th> and eske ander <tr> and eske
ander <td> tag ka use karna hoga.
Table me by default boarder nhi hoti hai.yadi hum lagana cahate hai to <table
boarder =”1”> </table> de sakte hai.
Heading ka data by default bold hota hai and center me bhi ata hai but row ka data
normal and left side me ata hai.
Table heading <th></th> ko kahi bhi likh sakte hai.
Yadi hum cahate hai ki table ka data center me aye to <td align=”center”></td>
Yadi hum table ander vale data and table ke beach space cahate hai to
cellpadding="" ka use karege.
Yadi hum dono border ke beach me space cahate hai to cellspace=”” ka use karege.
List 2 type ki hoti hai unOrder and Order
unorder me booletPoints ate hai <ul><li>java<li></ul>
Order me number ate hai <ol><li></li></ol>
Hum eska type bhi change ker sakte hai.
Definetion ke liye <dl><dt></dt></dl> . dl means definition list dt mtlab definition
type.
Form create karne ke liye sabhi kuch <form> tag ke ander likhege.
TextFiled ke liye <input type=”text”>
PasswordField ke liye <input type=”password”>
Button ke liye <input type=”button” value=”click”>
PalceHolder ke liye <input type=”text” placeholder=”Enter Name”>
Reset Button ke liye <input type=”reset”>
Submit Button ke liye <input type=”submit”>
Value attribute ki help se hum name change ker sakte hai.
Normal button khali ata hai kuch likhne ke liye value ka use karna padta hai.
Reset button pr reset likh hota hai eske click pr text fields ka data remove ho jata
hai.
Submit ke click pr flow <form> ke pass jata hai yadi hume kuch action karvana hai
to <form action=””> likh do.
Yadi hum <input type=”Email”> dete hai to @ lagana jaruri hai while filling
information. Otherwise it will give alertBox.
Radio button ke liye <input type=”radio”> hoga .
Yadi hum cahate hai ki dono me se 1 hi select ho to usko same group me rakhna
hoga Like Male<input type=”radio” name=”M”> femail<input type=”radio”
name=”M”>
CheckBox ke liye <input type=”checkBox” checked> yadi hume by default check
cahiye to uske ander checked likh do.
Choice banana ke liye <select> <option>java</option> </select>
Yadi list banana hai to <select multiple> <option>java</option> </select>
CSS
There are three type of CSS :- inline CSS ,Internal CSS , External CSS.
Yadi hum single - single tag me CSS Apply karte hai to usse Inline CSS kahte hai.
Yadi page ke <head> me CSS Apply karte hai to usse Internal CSS kahte hai. esse
head me change karne pr us pure page me change aa jayega.
Yadi hum cahate hai ki 1000 page hai us sabhi me change ana cahiye to hum eka
lag page banyege esse hi External CSS kahte hai.
Ancher tag ke under line ko hatane ke liye style =”text-decoration:none” karna
hoga.
Line height ka mtlab ek letter se dusre ke beach ki distance.
Font size badhane ke liye style=”font-size:100px”
Image set karne ke liye <img src=”image name with extention”
Border set karne pr by default clock wise direction me property set hoti hai.
Id ko # se and class ko . se show karte hai CSS me.
Gradiant set karne ke liye background:liner-gradient(r,g,b);
Unorderlist ke list ke data ko ek line me lane ke liye display:inline-block ka use
karege.
Background me light shedo lane ke liye background:rgba(0,0,0,0.5); ka use karege.
JavaScript
JS ka use hum web page pr validation apply karne ke liye karte hai.
JS clint side programming language hai.
Q15 yadi hum java se bhi security provide ker sakte hai to fer JS ki jarurat kyo padi ?
Ans:-JS clint Side programming language hai jabki java server side programming language
hai.yadi hum java ka use karte hai and kuch invalid datte web page pr dete hai to vo direct
web server ke pass jata hai check hone and fer jo response hota hai vo ata hai esa hi bar
bar hota hai jab jab invalid details dalte hai to jisse bar bar server se ane jane me time
weste hota hai . esliye JS se web page pr hi check ho jata hai and jiske karna bar bar server
pr nhi jana ana padta hai jisse time bach jata hai.
JS ko hum <Script type=”text/javaScript”></Script> tag ke ander hi likhte hai.ese
hum head and body dono me bana sakte hai.
Hum sabhi type ke data ke liye var data type ka use hai.
JS me all type ke arithmetic data type ko use kar sakte hai{+ , - , * , / , %}.
Bina data var type ka use kare bhi humara program proper work karta hai.
All type ke relational operator ka use kar sakte hai.yaha operator ka return type
Boolean hi hai.(< , > ,<= ,>= ,<<< , >>> , =).
Increment dicriment ka bhi use ker sakte hai. (++ , -- )
Logical operator ka bhi use ker sakte hai .(&& ,|| ,!)
bitwise operator ka bhi use ker sakte hai.(& , | , ^ ,~ )
Assignment operator ka bhi use ker sakte hai.(+= , -= ,*= ,%= , /=)
Ternary operator ka bhi use ker sakte hai.(+= ,-= , *= ,%= ,/=)
All type ke conditional operator bhi use ker sakte hai(if ,else ,nested if ,elseif
ledder ,switch case).
Ex:-
<html>
<head>
<script type=”text/javascript”>
if(false){
document.write(“ram<br>”);
}
else{
document.write(“sita<br>”);
}
</head>
<body>
</body>
</html>
Script tag ka use <body></body> and <head></head> dono hi ke ander ker sakte
hai.
Loops ka use bhi ker sakte hai sabhi type ke.
Ex:- <html>
<head>
</head>
<body>
<script type=”text/javaScript”>
for(i=1;i<=10;i++){
document.write(“sita<br>”);
}
</script>
</body>
</html>
Function create kern eke liye return type ki jarurat nhi hai. bas function keyword
ka use kerna hoga.
Ex:- function demo(){
Document.write(“ram<br>”);
}
Function direct bhi call ker sakte hai. Like demo();
Parameter bhi use ker sakte hai.
Ex:- function demo(int x , int y){
Document.write(x+y);
}
demo(10,20); // call function
return keyword ka bhi use ker sakte hai.
Ex:- function demo(int x, int y){
return x+y;
}
a=demo(10,20);
document.write(a);
Servlet
Servlet main code
<web-app>
<servlet>
<servlet-name>anyName</servlet-name>
<servlet-class>Class_Name</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Same_name of above</servlet-name>
<url-pattern>/duplicat_className</url-pattern>
</sevlet-mapping>
</web-app>
Clint site Applet hai and server site servlet hai.
Xml Page ka name fix WEB.xml hi hona cahiye.
Program humesa url-pattern me jo duplicate name dette hai usse hi run hoga.
Hum program ka duplicate name rakh dete hai and us name se hi hum program ko
run karvate hai esse original name kise ko pta nhi cahlta hai yahi sequrity ka
reason hai.
Sequrity ke purpos se xml ka use karte hai.
Eska ek or name deployment descript bhi hai.
Program run on browser:- localhost:8080/project_name/url-pattern_Name
Files save:- Apache->webApps->CreateProject(save All .html , .jsp files)-
>CreateOneFolder(WEB_INF(WEB.xml file))->createFolder(classes(All .classes files))
Web.xml file serf 1 hi banegi 1 se jiyada nhi.
Query String me Screen ka data url me bhi dikhta hai.
Query String Program run on web browser:-
localhost:8080/project_name/url-pattern_Name?un=”sita”&up=”gita”
html page ko run on web browser url :-
localhost:8080/project_Name/Htmlpage_Name.html
html page ke form me action me usse page ke servlet ka duplication name ko dete
hai like Login ka html page to Login ki servlet ki xml ka url patter mtlab duplicate
name.
servlet ki classes ko public hi rakhna hai.
Jab jab bhi hum servlet ki file ko compile kara ker paste karte hai .classes folder me
to tab tab server ko restart karna padta hai.
Eske S.o.pln ka use nhi ker sakte hai.
Ek out.println() me kitna bhi code likh sakte hai but ek hi line me hona cahiye.
Q What is servlet?
Ans:- servlet ek ese technology hai jiska use run time pr webpages ko junrate karane
me karte hai.esko sun micro system me banaya hai . yaha server side programming
hai.mtlab server mendatory hai. servlet ko run karane ke liye.
servlet ke pahle log CGI(Common Gateway Interface) ka use karte the. esme jese
jese request badhti thi to performance dicrese hota tha.
puri web application ke liye 1 hi servletConext create hota hai and ServletConfig
har servlet ke liye different – different create hota hai.
hum servletConfig and servletContext se hum xml se information ko read karva
sakte hai.
ServletContext se hum 2 application ke beach communication karva sakte hai.
Yadi puri web application ke liye esa unique object cahiye jo puri application me
same data ko share kara sake to ServletContext ka use karege.
1 servletConfig for 1 servlet and 1 servletContext for 1 web application.
Q what is RequestDispacher?
Ans:- ye ek interface hai jo object define karta hai. ye request ko receive karta hai jo ki
clint request karta hai usse and usse dispatch karta hai particular resourse me like (Servlet
, Html ,JSP files).
Server ye notice karta hai ki request kiske liye aai hai html page ke liye ya Servlet
hail iye .
Ab Server us servlet request ko Container ko de deta hai . container ab 2 object
request and response create ker ke us servlet ki duplicat thread/copy bana ker
uske curresponding service() method hoti hai and us method ke constructor me vo
2 perameter request and response jak er store ho jate hai.
Ab service method ye dekhegi ki request get() method se aai hai ya post() method
se
Yadi request get() method se aai hai to doGet() method ke consteructor me vo
perameter ko pass ker degi. yadi post name diya hai to doPost() method call hogi.
To request object se hum form se data fatch karte hai and response Object se html
output ko junrate karte hai. Ex:- request.getParameter() and response.getWriter().
By default vo doget() method hi leta hai.ab doGet() method html output Container
ke pass send ker deti hai.
Html output milte hi Container un 2 object ko destroy ker deta hai.
Us html output ko container web server ko de deta hai and web server html
output ko http response ke through web page pr show ker deta hai.
Cookie& Session
Bina Cookie ke dusra user bhi url se login ho sakta hai but hum cookie se fix ker
dete hai ki login ke bad hi main page open ho.
http protocol stateless protocol hai mtlab forgettable protocol mtlab ki vo previous
ko bhul jata hai ki ky chal raha tha.
Yadi hum ne web browser se web server pr first request sent ki hai and again ram
ne hi web browser se web server pr second request ker di to vo previous ko bhul
jayega.ese hi forgetful protocol kahte hai.
Particular user ko recognize (yaad) rakhne ke liye hume kuch techniques provide ki
gai hai session tracking ya session management ke liye.
i. Cookie .
ii. Http Session.
iii. URL rewriting .
iv. Hidden form field.
Q :- Cookie kaha create hoti hai?
Ans:- Cookie Web server pr create hoti hai.
Q:- What is Cookie?
Ans:- Cookie is small text file. Jo every request and response ke pare me web browser se
web server and web server se web browser pr travel karti rahti hai.
Cookie create to web server pr hoti hai but store web browser me hoti hai.
Jab web browser se request bhejte hai to http request jati hai but web server se
http response ke sath sath cookie bhi ati hai. then ager again request jati hai to
yadi cookie ke sath aai hai mtlab old user hai otherwise new user hai to response
me cookie ko sath pahochata hai web server.
Cookie hai mtlab old user hai and nhi hai mtlab new user hai.
Hum user ko recognize karne ke liye es condition me esa code likhte hai ki yadi
cookie hai to old user other wise new user.
Q type of Cookie?
Ans:- there are 2 type of Cookie:-
i. Non – persistent ii. Persistent
Non – persistent(dradh) :- Ese cookie jo single session ke liye valid hoti hai and web
browser ke close hote hi destroy ho jati hai. ase cookie non- persistent cookie kahlati
hai.
Persistent:- Ese cookie jo multiple session ke liye valid hoti hai. jo browser ke close
hone pr bhi destroy nhi hoti hai . ase cookie ko Persistent cookie kahte hai.
Q :- Cookie konse package me rakhi hai ?
Ans:- import javax.servlet.http.Cookie;
First time user successfully login ho jata hai to Cookie create ho jati hai.
Cookie Create Stapes:-
Import java.servlet.http.cookie;
i. Cookie Class ka object banao.
// Cookie ck=new Cookie(“Variable_name” , “Variable_Value”);
// Cookie ck=new Cookie(“UName” , “Ram”);
ii. Cookie ki expiry set karna hoga.
// ck.setMaxAge(60*60*24*30);
// ck.setMaxAge(Seconds*60*24*30);
iii. Cookie ko response object me add karna hoga . Web Browser se web server pr
pahocahne ke liye.
// response.addCookie(ck);
Session Sever side file hoti hai jo kuch Cookie client side file hoti hai jo web
data ko Server pr store ker sakta hai. browser pr store ker sakte hai.
Jese hi Browser close karte hai vese hi Cookie uske lifetime ke end ho jane pr
Session end ho jata hai. destroy hoti hai. jo hum time set karte
uske end ho jane pr.
Session Cookie pr depend hota hai. Cookie Session pr depend nhi hoti hai.
Session ko start karna padhta hai Cookie ko start karne ki jarurat nhi hoti
hai.ye local computer me store hoti hai.
1 Session me hum kitna bhi data store Maximum Browser pr cookie ka size
kar sakte hai.But yaha memory limit hai 4KB (4096 Byte) hoti hai.
jo ki 128MB hoti hai by default.
Session jiyada squired hota hai. Cookie less squired hoti hai.
Data encrypted form me store hoti hai. ye decrypted form me store hoti hai.
Cookie:-
ese sabhi page jinme hume security provide karna hai un sabhi ko java me likhna
hoga.
Cookie ka concept java ke pass hai html ke pass nhi hai esliye hume sabhi html
pages ko java me mtlab servlet vale page me likhna hoga.
Cookie c[ ]=request.getCookie() sari cookie ko fetch karne ka kam karti hai eska
return type array hota hai.
Yadi kuch data nhi hoga to by default null hoga.
Jitney bhi page me squirt provide karna hai unko java servlet page me hi likhna
hoga.
Cookie ko destroy karne ke liye uska time update karna padta hai mtlab time 0
karna hota hai.
Cookie Super globle variable ki tarha work karta hai.eska mtlab ye ki Cookie ke
variable me data ko kahi bhi fatch karva ker usse use ker sakte hai.
Hum kitni bhi Cookie create ker sakte hai.But variable name different hi hona
cahiye.
Q :- yadi humne Cookie ki Expiry set nhi ki to ky hoga?
Ans:- yadi humne Cookie ki Expiry set nhi ki to es condition me jese hi browser close
karege Cookie Distroy ho jayegi. Browser me bhi Cookie Section me last me likha
ayega “ When the Browsing session end ”
Q More than one Cookie ka use karne se ky benefit hai ?
Ans:- More than one Cookie ka use karne se hum more than one textFiled se data get
ker sakte hai.
Q Yadi Session ya Cookie me se koi ek hi hota to ky ?
Ans:- yadi hum Session ka use karte hai to hume vo security provide karta hai but eska
data server pr store hota hai to hum normal data ko store karne ke liye Cookie ka use
krate hai kyo ki ye local computer me data store karti hai.
Q Hume kab Session ka use karna cahiye and kab Cookie ka use karna cahiye?
Ans:- Jab hume information ko server pr use karna ho to Session ka use karna cahiye
and yadi data ko local computer me store karna ho to Cookie ka use karna cahiye.
Session
Session javax.servlet.http.session; package me hai.
Session ko create karne ke liye hume HttpSession interface ka use karna padhta
hai.
Ex:- HttpSession s=request.getSession();
Jis jis page me session ka use karna hai vaha vaha session ka object banana padhta
hai.
Session me data get karna hai to Ex:- String s1=(String) session.getAttribute(“un”);
getAttribute() method ka return type Object hai.
Session Distroy karne ke liye.
Ex:- HttpSession s1=request.getSession();
S1.invalidate();
Yadi hum request.getSession() me kuch pass nhi karte like true ka false to vo true
hi manta hai.
Q Difference between getSession(true) and getSession(false)?
Ans:- request.getSession(true):- ye Check karega ki ky HttpSession ka object exist ker
raha hai ya nhi yadi nhi karta to ye object create kerke return ker degi otherwise old
ka hi object return ker degi.
request.getSession(false):- ye bhi yah check karta hai ki ky pahle se HttpSession ka
object exist kar raha hai ya nhi yadi pahle se exist karta hai to use hi return ker degi
otherwise null return karti hai.
Q jab request.getSession() method session ka object return karti hai to ky yaha bar bar
new object create hota hai?
Ans:- nhi ye ussi object ko bar bar return karti hai.
Jitne bhi pages hote hai unke beach state o maintain karne ke liye hum Session ka
use karte hai.
Session variable internally Cookie ka use karta hai.
Yes New
Html Output
yadi new JSP page hai ya updated page JSP page hai to es case me compilation bhi
hoga and execution bhi hoga and fer servlet execute kara ker html output dega.
Yadi Old jsp page hai mtlab uska compilation and execution ho chuka hai to direct
servlet ko execute karva ker output de dega.
JSP ne hume functionality provide ki hai ki hum Html ko usme direct likh sakte hai
kyo ki servlet page me bahot likhna padhta hai out.println() ker ke.
Scriptlet tag<% %>
Yadi JSP page me java ka code likhna hai to Scriptlet tag <% %> ke ander hi likhna
hoga.
JSP bahot sare Object ko anak er implicitly ready ker deta hai to out un implicitly
bane Object me se bana hoaa ek Object hai.
Hum JSP page me pura java ka code likh sakte hai har features work karte hai.
Jitna bhi code hum Scriptlet tag <% %> ke ander likhte hai vo servlet ki service()
method me jak er put hota hai.
JSP me yadi hum java ke code ko Scriptlet tag ke ander nhi likhte normal jese hi
likhte hai to Html ko out.println() met likhna hoga. But yadi hu Html ko normally
likhte hai to fer java ke sare code ko Scriptlet tag <% %> ke ander likhna hoga.
Expression tag <%= %>
Yadi hume JSP page me method banana hai to declaration tag <%! %> ka use karna
hoga kyo ki eske ander ka likha hoaa data service() method me jak er store nhi
hota hai.
Q What is use of declaration tag <%! %> ?
Ans:- for declare global variable and for declare method.
Directives
Q What is directives ?
Ans: -Directives are elements that relay messages to the JSP Container and affect how
it compiles the JSP page.
This are the three Types:-
i. page.
ii. include
iii. taglib.
i.page:- page ka mainly use manually package import karna hai
Ex:- <% @page import =”java.sql.*” %>
jsp implicitly request object bana ker ready ker deta hai. esliye doGet() method
and PrintWriter() method ko call nhi karna hota hai hume JSP me.
ii. Include:- hum jo comman chije humare project me use hoti hai usse ek JSP me
page me bana dete hai and uss JSP page ko us karne ke liye jaha jis page me use
karna hai usme link karna hota hai esliye hum include ka use karte hai. inside
<body> </body> tag. Ex:- <% @include file=”PageName.jsp”%>.
Redio button se data fetch karvana hai to vo value ke through hoga . written at
26/09/2021
Data humesa name se hi fetch hota hai.
Regular Expression
Hum particular pattern me data dalne ke validation ke perpus se regular
expression ka use karte hai.
Regular expression 2 forward slesh (/) ke beach me likha jata hai and esse ek
variable me store karvate hai.
Yadi hum cahate hai ki password me kam se kam 1 decimal number ho to \d use
karte hai. Ex:- var x=/\d/ ;
Yadi hum cahate hai ki first letter hi number ho to ^\d ka use karna hoga.
Ex:- var x=/^\d/ ;
Esme ek test() method hoti hai jo check karti hai ki expression shih ai yan hi.
Ex:- function demo(){
Var x=/^\d/;
Var S=document.getElementById(‘t1’).value;
//t1 textFiled ki id hai.
If(x.test(s)){
Document.getElementById(‘y’).innerHTML=”Welcome”;
//y esme heading ki id hai.
}
else{
Document.getElementById(‘y’).innerHTML=”Invalid”;
}
}
Yadi hume End me Digit cahiye:-
Var re=/\d$/;
Templet
Method Overloading ka advance version Varargs(Variable argument) hai.
Varagrs me hum same type ke data type ki value hi pass ker sakte hai.ek method
me.
Templet Method:-
}
Yadi Abhi hum Templet class ko compile karte hai to warning aati hai.yadi hum
cahate hai ki von a aye to hume generic type dena hoga.
Ex:- A<Integer> a=new A<Integer>();
But ab hum only Integer type ka hi data pass ker sakte hai dusre type ka nhi. Yadi
kiya to Error aa jayegi. Ex:- a.get(10,10.8);
Yadi hume dusre type ka data pass karna hai to fer dusra Object create karna hoga.
Ex:- A<String> a2=new A<String>();
a2.get(“Ram” , ”Sita”);
Yr jo hum generic type dete hai vo upper T me jak er store hoga.
Generic class me hum only Class type hi pass ker sakte hai primitive data type nhi
de sakte hai Error dega. Ex:- A<int> a=new A<int>();
Yadi hum more than one different type ka data pass kerna cahate hai to fer hume
utni hi Generic class deni hogi.
Ex:- class A<T,U>{
T x;
U y;
Void get(T a , U b){
x=a;
y=b;
}
}
Object will be like :- A<Integer , String> a=new A<Integer , String>();
Q What is dimond Operator ?
Ans:- Yaha java version 1.7 ka ek concept hai. Yadi humne ek taraf generic type pass ker
diya hai to dusri taraf hume vo pass karne ki jarurat nhi hai vo automatic type ka anuman
infraretion ki help laga leta hai.ese hi dimond Operator kahte hai.
Ex:- A<Integer , String> a=new A<>();
Q What is infraration?
Ans:- Automatic type ka anuman laga lena hi infraration kahlata hai.
Type infraration me :-
Version 1.7 :- Dimond Operator.
Version 1.8:- lambda Expression.
Version 1.10:- var naya key word java me add hoaa hai.
Ye Type infraration ke according hi ate hai.
Bina compile kiya Program ko direct single command se compile and run karne ki
facility version 1.11 me aai hai. Ex:- java className.java
Hum method me jo bhi data pass karte hai vo Class ke form me hi ja ker store hota
hai T me ja ker.
Yadi hume String type ki value pass ki hai and yadu hum int me store karvate hai to
ClassCastException ayegi kyo ki String bhi ek class hi too hai .
Q Generic Type dene se ky advantage hai ?
Ans:- Greneric type dene se ek to hum TypeCasting karne se bach jate hai . and Second
hum ClassCastException se bhi bach jate hai.
Q What is covariant method overriding ?
Ans:- Covariant method overriding means Child class ki method ka return type different de
dakte hai but vo compatible hona cahiye mtlab ki parent class me method ka jo return
type diya hai vo high hona cahiye compared to sub class ki method ke return type se like
parent ki method return type Object and sub class ki method ka return type String to
work karega but eska ulta nhi karega.
Child class me parent ke compare me sub(chota) type dene se hum type casting se
bach jayege.
Ye sabhi facility like Covariant , Boxing , UnBoxing , AutoBoxing , AutoUnBoxing.
Ye primitive data ke sath work nhi karega.Only Object Leval mtlab class ke sath hi
work karega.
Yadi Super class ki Overriden vali method Exception ko thows nhi ker rahi hai to
sub class ki method bhi nhi ker sakti hai. But eska ulta ho sakta hai ki yadi super
class ki method Exception ko thows ker rahi hai but sub class ki method nhi ker
rahi to koi problem nhi hai ye work karega.
Yadi super class ki overridden vali method Exception ko thows nhi ker rahi to Sub
class ki overridden vali method bhi nhi ker sakti hai But Yadi Super class ki
Overridden method Exception ko Throws karte hai tai to sub class vali Overridden
method ya to same Exception ko ya uski child Exception ko hi Throws ker sakti hai
Uski Parent vali Exception ko Throws nhi ker sakti otherwise Error aa jayegi.
2. Object Class
Object class Sabhi class ki parent class hoti hai.
Object class java.lang package se ati hai.
Object class ke pass total 12 method hai.
Mathod name type
i. getclass() final
ii. hashCode() public
iii. toString() public
iv. equals() public
v. finalize() protected()
vi. clone() protected()
vii. wait() final
viii. wait(long ) final
ix. wait(long , int) final
x. notify() final
xi. notifyAll() final
xii. registersNative() private
Object class ki total 6 method final hai.
Object class ki total 2 method protected hai.
IMP Question final finally finalize me difference .
Hum CMD pr javap java.package_name.Class_Name likhege to us class se releted
sabhi chije aa jayegi.
12 number ki jo registerNative() method hai vo private method hai esliye javap se
dekhne pr CMD pr nhi dekhayega.
Yadi hume Private method ko bhi CMD pr dekhna hai to javap -p java.lang.Object
Command ka use karna padega.
Hum final, static, private type ki methods ko override nhi ker sakte hai.
Object Class ki total 5 hi method Override ker sakte hai.
i. hashCode()
ii. toString()
iii. equals()
iv. finalize()
v. clone()
Object class ko By default sabhi class extends karti hai.
getClass() method us class ka name deti hai class keyword ke sath. Ex:- class A
Yadi getClass().getName() method likhte hai to serf class ka name deta hai. Ex:- A
Har object ke currusponding HexaDecimal number different hota hai.
Jab jab bhi object ko call karte hai to us object ke currucponding toString() Method
call hoti hai.
Object class ki toString() method humesa Output ko hexadecimal number ke form
me return karti hai.
Q:- hum toString() method ko override kyo karte hai?
Ye jo garabage collector unused and unreferenced variable ko remove ker deta hai
ese hi automatic memory deallocation kahte hai
Finalization/finalize() method
Q Diffrence Between final , finally finalize()
JVM jab Object Distroy karta hai to vo Heap ka hi karta hai method area ka nhi.
Object ke destroy hone ke just pahle distructor call hota hai C++ me.
Jab kabhi bhi GC object ko destroy karta hai to Object ke destroy hone ke just
pahle internally un object ke corresponding 1 method finalize() call hoti hai clean
up ke purpos se . ese hi finalization kahte hai.
finalize() method Object class ke pass hai.
Finally() method ka return type protected hai. Like:- protected void finalize();
Object class ki finalize() method ki body empty hai.
Jo bhi object destroy ho raha hai us object ke corresponding jo class hai usme yadi
finalize() method ko override kiya hai to us class ke object ke destroy hone pr
Overridden method hi call hoti hai . varna Object class ke liye normal vali empty
body vali.
Yadi JVM ne GC ko call kiya and finalize() method me koi exception ati hai to usse
JVM automatically handle ker leta hai. But yadi hum manually karte hai to fer vo
Exception ati hai.
Q Ky hum finalize method ko manually ker sakte hai ?
Ans :- ha ker sakte hai but fer vo ek normal method ki tarha hi sequence me call hogi
fer usse JVM se koi mtlab nhi .Yadi hum call karege to exception ati hai but yadi JVM
ne call kiya to vo exception ko handle ker lega.
Yadi kise reference me null assign ker diya to fer hum uske reference se yadi
method ko call karege to run time pr NullPointerException ati hai.
Finalize() method ke call hone ke case me jitni bar GC ko call karege utne number
of cases banege.
JVM GC ko call karta hai and GC finalize() method ko call karta hai.
hume jaruri nhi ki har bar GC se request karna pade. Bina request ke bhi vo Object
ko destroy to ker dega but fer hume thoda wait karna hoga kyo ki vo fer JVM ke
mod pr depend hai ki vo GC ko kab call karega.
Q kise bhi class ki sari method ko count karne ka program banao.
JDBC me jo Class.forName() hai usme Class bhi ek predefine class hai.
Java ke pass ek predefine Method name ki class bhi hai jo ki method count ke
program me help karti hai.
Q ky class ki private method ko CMD pr display karva sakte hai ?
Ans:- ji ha hum bilkul karva sakte hai. reflection ki help se
Q ky hum private method ko bahar access ker sakte hai ky ?
Ans:- ha hum bilkul ker sakte hai.
Q Diffrence between Error and Exception?
Ans :- Error Exception
Singleton Class
Q What is Singleton Class in java ?
Ans:- Limited Object create karne dene ki permission se hum Singleton class ka use karte
hai. Esme hum us class ka serf ek hi object create ker sakte hai.
Cloning :- Java me object ko create karne ke bahot sare tarike hote hai unme se hi ek
tarika hai Object class ki clone() method.esme same data ke sath seprate object create
hota hai.
1. BigInteger
Yadi Hum normal factorial ke program me int lete hai to 13 tak shi dega uske bad
galat dega. Ese hi long ke case me 20 tak shi dega uske bad galat dega. Esse bade
number ka yadi hum factorial nikalna cahate hai to hume BigInteger ka use karna
hoga.int:- -2147483648 to 2147483647 ,long:- -9223372036854775808 to
9223372036854775807.
BigInteger ek class hai jo ki kitne bhi bade number ko store karva sakta hai.
Yadi hume Class ko data type me store karvana hai to wrapper class ka use karege.
Like String s=”10”; int x=s;
Java me jitni bhi class hai un sabhi ke pass ek method hai jiska name hai valueOf()
valueOf() method ki help se bhi hum String me int value store ker sakte hai.
String ke case me Arithmetic operators me se serf + ko use ker sakte hai baki ke
liye bed operand type error dega.
Int kabhi bhi BigInteger me ja ker store nhi ho sakta hai. Like BigInteger c=10;
Yadi hum store karvana hai to valueOf() method ka use karege.
Like BigInteger b=BigInteger.valueOf(10);
BigInteger kabhi bhi koi bhi operator ke sath work nhi ker sakta hai.
yadi hume kuch operation perform karvana hai to hume eski methods ka use karna
hoga.
Ex:- add(), subtract(), multiply() ,divide(), mod().
Ex:- x.multiply(y);
int and BigInteger ke beach operation perform nhi ho sakta hai.
BigInteger ne hume kuch constant provide kiye hai. ONE to TEN tak ese use ker
sakte hai. Capital hi hona cahiye.
BigInteger ki valueOf() method me hum serf long tak ki hi value store sakte hai.
Yadi hume long se jiyda badi value store karvana hai to hume BigInteger ka Object
bana ker value ko uske constructor me “ ” ke ander dena hoga.ye kitna bhi bada
number le sakta hai.
2. InnerClass
A class which is declare inside the class is called inner class.
Inner class ka use sabhi type ke project banana me bahot hota hai.
Inner class kai 2 type hote hai i. Non Static ii. Static.
Non static class ke 3 type hote hai. i.instance innerclass.
Ii:-local inner class.
Iii:-anonymous inner class.
Anonymous inner class ke 3 type hote hai:- i:-anonymous inner class that extends
by a class.
Ii:- anonymous inner class that implements by a interface.
Iii:- anonymous class that define inside the argument.
Humare program me jitni class hoti hai utni hi number of .class file banti hai.
Instance inner class ke ander hum kabhi bhi static method nhi bana sakte hai.error
dega illegal static declaration inner class.
Outer class me static method bana sakte hai.
Object create kar ke hum kise bhi type ke data ko acess ker sakte hai.
Instance variable mtlab Object variable vo object se hi access ho sakta hai.
Inner class ka object outer class ke object pr depend hota hai.
Hum inner class ka object 2 tarha se bana sakte hai. 1:- A a=new A();
A.B b=a.new B();
2:- A a=new A();
B b=a.new B();
st nd
Yadi same class me hi access karna hai to 1 or 2 dono tarha se work karega.
But yadi Different class me access kiya to 1st me error dega 2nd hi work karega.
Non static method static and non static dono type data ko direct access ker sakti
hai. But non static only static data ko hi karti hai.
Outer class me instance inner class ko direct access ker sakte hai.
this currant Object ke currosponding instance content ko point karta hai.
Outer class ke private data ko bahar access nhi ker sakte but usi class ke member
se access kerva ker usse bahar access ker do uska modifier change ker ke.
Outer class ka private data inner class ka member access ker sakta hai.
Hum Outer class ko kabhi bhi private declear nhi ker sakte hai.
Hum Outer class ke sath serf 5 keyword use ker sakte hai. i.default, ii. public, iii.
final, iv. abstract , v. strictfp .
Hum inner class ke sath outer class ke 5 keyword ke sath sath 3 or use ker sakte
hai. i. private ii. protected iii. static.
Hum kuch es tarha se Object bana ker bhi call ker sakte hai. New A().show()
Hum bina reference ka use kare bhi inner class ko call ker sakte hai .
Ex:- new A().new B().show();
Method ke ander instance block ho sakta hai static nhi ho sakti.
Inner class ka data kabhi bhi static nhi ho sakti hai.Only Variable static final ho
sakta hai.
Inheritance ke case me jo jo class extends hoti un sabhi ka constructor , instance
block, and static block call ho jata hai.
Abstract class ka object nhi bana sakte hai.
Serf inheritance ke case me inner class and outer class ka name same rah sakta hai
. Ese normal me nhi ho sakta hai.
Abstract data abstract class ya interface se hi call ho sakta hai.
Hum inner class ko bhi abstract bana sakte hai.
C++ me abstract method ko hi pure virtual function ka use karna hai.
Hum class ke ander class to banak er ready ker sakte hai sath hi method ke ander
bhi class bana sakte hai.
Humne jis class ko jis method ke ander banaya hai vo class us hi method ke ander
hi access ho sakti hai.
Yadi method ke ander class bani hai to class name ke pahle number aa jayega
jitney metho me bani hogi utna 1 me to 1 , 2 to 2 $ symbol ke bad.
Class ko cahe access karo ya na karo .class file to banegi hi.
Inner class ko hum kisi ke bhi ander bana sakte hai.
Inner class ke ander ki method ke ander ka variable bhale hi version 1.8 se hume
final declare nhi karna hota but vo internally final hota hai.kyo ki inner class ka
local variable partially final hota hai.
Jab tak hum use update nhikarege vo effectively final rahega update karne pr nhi
rahega. Esse hum method ke bhara se update nhi ker sakte hai method ke ander se
hi ker sakte hai.
Difference between A a=new A() and A a=new A(){};
A a=new A(); A a=new A(){};
Yaha pr class A ka object ban raha hai. Yaha pr ek class bani hai uska name
hai anonymous class.
Class A ke object ko class A ka refrance anonymous class ne extends kiya
Variable a hold ker raha hai. hai A ko.
new A(){}; ka matlab hai yaha
anonymous class ka object ban raha
hai.
Anonymous inner class ke object ko
super class A ka reference variable
a hold ker raha hai.
Jitni bhi anonymous class banegi utni hi number of class ayegi $ ke baad like $1,$2.
Yadi hum kise ek object ke corresponding value change karna cahate hai ya
override karna cahate hai to hume anonymous inner class ka use karna cahiye.
Yadi frame me setVisible(true) nhi kiya to cusrsore 1 second ke liye blink hoga and
terminate ho jayega.
Windows listener ke pass 7 method hoti hai jinhe override karna compulsory hota
hai.
Yadi hume frame ko close karna hai to windows listener ki sabhi method ko
override karna hoga bhale hi hume 1 hi ki jarurat ho but hume es ana karna pade
eske liye java ne hum eek feature diya hai jiska name hai Adapter class eski help se
hume jitni method ki jarurat hai utni hi method ko override karna hota hai.
Q how to create Adapter class ?
Ans:- i. Make one class with any name.
ii. Us class se us listener ko implements karo karo jiske liye apko Adapter class
banana hai.
iii. Us listener ki sari method ko us class me override ker do.
Hum return ke neache koi statement nhi likh sakte hai.
LambdaExpression:-
i. Anonymous inner class ka extended version lambda expression kahlata hai.
ii. serf functional interface ke sath hi hum lambda expression ka use kar sakte
hai.
iii. Functional interface and lambda expression java version 1.8 ke feature hai.
iv. Java programming ka kahna hai ki jab ek hi abstract method hai to uska
name mt likho hum samjh jayege ki vhi method hai.
v. Java ka kehna hai ki jab anonymous class ka object ban raha hai and use
interface ka reference variable hold ker raha hai to new Interface() ki
jarurat nhi bas uski jagha ye ()-> laga do hum samjh jayege.
vi. Vi and V point ek sath hi apply hona cahiye.varna error dega.
vii. Yadi hum anonymous class ki body nhi bhi dege to bhi work karega.
viii. Yadi hume perameter ka type nhi bhi diya to automatic considerd ker lega.
ix. Perameter me ya to dono ka datatype do ya fer 1 ka bhi mt do.
x. Yadi ek hi perameter hai ya nhi hai to () nhi bhi lagaoge to vo samjh jayega.
xi. Yadi more than 1 perameter pass kiya hai to () lagana jaruri hai.
xii. Yadi hume return keyword ka use nhi kiya to vo bydefault return keyword
leta hai lambda expression me esliye hum nhi laga sakte hai.varna error
dega.
xiii. Yadi hume anonymous class ki body di hai to fer hum return keyword ka
use ker sakte hai.
xiv. Lembda expression me hum jis type ka perameter dete hai vo hi method ka
type bhi hona cahiye return return ka use karte hai to.
Interface ke ander interface bana sakte hai.
Class ke ander interface bana sakte hai.
i. Advance Swing
Yadi hum click listener laga dete hai to Button ke click pr Operation perform ho jata
hai AWT me. But swing me nhi hota hai. Yadi hum karna cahate hai to hume JPanel
class ko extends karna padhta hai.
Humne abhi tak FlowLayout,BorderLayout,gridLayout,setLayout(null),CardLayout
padha hai.
FlowLayout AWT ka default Layout hota hai jo ki jitni size hogi utna hi bada
component dega.
BorderLayout swing ka default Layout hota hai. Jo pure Frame pr fel jata hai.esliye
bas last vala component hi dekhta hai.
gridLayout vertically component ke hisab se divide ho ker puri frame pr aa jata hai.
setLayout(null) jab hume Apne hisab se sab set karna ho puri Frame pr tab use
karte hai. Ye Blank frame dekhayega.
CardLayout ye bahot important Layout hai ye 1 ke neache 1 componant ko arrange
karta hai.
Container class ka object banana padega . Like :- Container cn=getContentPane();
And fer eske referance se actionPerformed() method me call karte hai.
Like:- cn.setBackground(Color.red);
cn container ka reference hai. Baki ki sabhi chije same rahegi
Hum kabhi bhi frame ke upper frame add nhi ker sakte hai.illigalArgument
Exception dega.
Yadi Hum frame ke upper frame add kerna cahate hai to JPanel class extends
karna hoga tab sakte hai.
Panel ko Panel me add ker sakte hai.
Frame me Panel ko add ker sakte hai. But Panel me Frame ko add nhi ker sakte hai.
CardLayout bahot important Layout hai . ye Component ko 1 ke neache 1 arrange
karta hai.
Eske pass total 5 method hoti hai:- first(), last(), next(), previous(), show().
2 layout ko hum ek sath use kar sakte hai but jo last vala Layout hoga vhi apply
hoga Frame pr.
show() method me pahle perameter me Container class ka reference and second
me jo String dalte hai apan components ko add karte time vo String dalte hai.
Like :- card.show(cn,”manu”); .
5.Advance Polymorephism
Inheritance ke case me jo class jis jis class ko extends karti hai un un class ki
property access ho jati hai automatic like static block, instance block ,constructor.
Only method ko hi manually call karna padta hai object se.
Method overriding me Jiski memory rahegi uski method call hogi.
Super class ka reference variable sub class ke object ko hold karta hai.
Java by default run time polymorephism ko support karta hai.jabki C++ bydefault
Compile time polymorphism ko support karta hai.
Yadi hum object ko print karvate hai to vo Class_NameHexaDecimalNumber ke
form me print karvata hai.
Har object ke currucponding hexadecimal number different hota hai.
Jab kabhi bhi hum kisi bhi object ko print karte hai to uske currusponding toString
method call hoti hai.
Blank final variable me yadi humne instance block se value assign ker di hai to fer
constructor se nhi de sakte varna error dega.
Yadi hum blank final variable me constructor se value assign karte hai to hume
sabhi constructor se value assign karna hoga.
Yadi hum method overriding ker rahe hai and parent ka reference le rahe hai to
parent class me bhi vo method present hona cahiye .kyo ki yadi reference hai to
pahle reference ke currusponding method ki prasentness check karta hai.
Runtime working object ke currusponding hoti hai and compile time binding
reference ke currusponding hoti hai.
Yadi hum cahate hai ki compile time binding ho to method ko static bana do.
Method overriding ka benefit ye hai ki yadi hume parent class ki method ki
definition pasand nhi aa rahi hai to use sub class me override ker ke change ker
sakte hai.
Q1 What is method Overloading?
Ans:- same class with different number of parameter or different order of parameter
or different type of parameter is known as method overloading.
Int number me by default int vala cahelga cahe fer long ho fer bhi .
Ex:- System.out.println() is overloaded as we have 9 or 10 println() method each accepting
a different type of parameter.
Q2 What are the rules of method Overloading?
Ans:- one of the important rule of method overloading is that method signature should
be different that is either the number of argument or the type of argument.
Simple changing the return type of method will give result in overloading .
Q3:- can we Overload static method in java?
Ans:- yes we can overload static method but we can not override static method.
Q4:- can we Overload main method in java?
Ans:- yes we can overload main method In java but the program does not execute. When
we run our program so we have to call the overloaded main method from the actual main
method. That means main method act as an entry point for the java interpreter to start
the execution of the application where as a loaded main need to called main.
Q5:- can we declare one overloaded method as static and another one as non static in
java?
Ans:- yes overloaded method can be either one static and one non static.
Q6:- How do compiler differentiate overloaded method from duplicate method ?
Ans:- Compiler uses method signature(parameter) to check where the method is
overloaded or duplicated .
Duplicate method will have same method signature that is
same , name_same , same number of argument and same type of argument . overloaded
method will also have same name but different number of argument or else type of
argument.
Child se parent ki or promote karta hai and data type me automatically int kea lava
kisi bhi data type me apne just neache vala data type lega.
Q7:-Is it possible to have two method in a class with same method signature but different
return type ?
Ans:- No , Compiler will give duplicate method error. Compiler checks only method
signature for duplicate not the return type. If two method have same signature , straight
away it give compile time error.
Q8:- In “MyClass” there is a method called “myMethod()” with four different overloaded
form. All four different forms have different visibility (private , public , protected , default)
?
Ans:- yes compiler checks only method signature for overloading of method not visibility
of method.
Q9:-can we overloaded method be synchronized ?
Ans:- yes we can overloaded method be synchronized.
Q10:-Can we declare Overloaded method as final ?
Ans:- yes, we can declare overloaded method as final.
Q11:-In the below class , is Constructor overloaded or is method overloaded ?
Ans:- Ex:- public class A{
A(){
--------
}
Void A(){
---------
}
}
Method name.
Number of argument.
Type of arguments.
Q What is method Overriding in java ?
Ans:- In any Object Oriented programming language overriding is a feature that allows a
subclass or child class to provide a specific implementation of a method that is already
provided by one of its super-classes or parent classes . When a method in a subclass has
the same name , same parameter or signature and same return type(or sub type) as a
method in its super-class , then the method in the subclass is said to override the method
in the super-class.
Note
Method Overriding is one of the way by which java achieve Run Time Polymorphism . The
version of the method that is executed will be determined by the time Object that is used
to invoke it . If an Object of parent class is used to invoke method , then the version in the
parent class will be executed , But if an object of the subclass is used to invoke the
method then the version in the child class will be executed . In other words , it is the type
of object being referred to(not the type of the reference variable) that detrermins which
version of an overridden method will be execute.
Q What are the rules of method overriding in java?
Ans:- * In java method can call only be written(Overridden) in subclass not in same class.
The argument list should be exactly same as that of the overridden method .
The access level can not be more restrictive than the overridden method’s access
level. For Example:- if the super class method is declared public then the overriding
method in the subclass can not be either private , default , or protected .
Private -> default -> protected -> public.
Return type should be same or a subtype of the return type declare in the original
overridden method in the super class .
Instance methods can be overridden only if they are inherited
A method declared final can not be overridden .
A method declared static method can not be overridden but can be redeclare in
the sub class with static keyword but that is called method hiding in java.
A subclass within the same package can be override any super class method that is
not declared private final or static.
A subclass in a different package can only override the non-final method declared
public or protected.
There are many rules if we talk about method overriding with exception handling
the rules are as follows :
If the super class method does not declare an exception:
i. If the super class method does not declares an exception , subclass overridden
method can not declare the checked exception but it can declare unchecked
exception.
If super class method declare an exception:
i. If the super class method declare an exception , subclass overridden
method can declare same , sub exception or no exception but can not
declare parent Exception.
Q Can we override a method which can throws unchecked exception ?
Ans:- Yes there is no restriction on unchecked exception while overriding on the other
hand , in the case of checked exception , an overriding exception can not throw a checked
exception which comes higher in type hierarchy ex:- if original method is throwing
IOException then overriding method cannot throw java.lang.Exception or
java.lang.Throwable.
Q can we override a non-static method as static in java ?
Ans:-Hiding happens when both methods in the pair are static method ; overriding
happens when both method in the pair are instance method when one of the two is a
static and the other one is an instance method , java consider it an error . It does not
matter if the instance method is final or not; it is also does not matter if the static method
is in base or in the derived class; java calls it an error either way.
Q can we override static method in java?
Ans:- No you can not override static method in java because method overriding is based
upon dynamic binding at Runtime and static method are binded using static binding at
compile time .
Q can we override final method in java?
Ans:- No we can not override final method in java , final keyword with the method is to
prevent method overriding . we use final when we don’t want subclass can change the
login of our method by overriding it due to security reason . This is why String class is final
in java. This concept is also used in templet design pattern where tamplate method is
made final to prevent overriding.
Q can we prevent(Rokna) overriding a method without using the final modifier?
Ans:- Yes you can prevent the method overriding in java without using the final modifier .
In dact , there are several way to accomplish it Ex:- you can marks the method private or
static , those cannot be overridden.
Q Can we override the a private method in java ?
Ans:- You can not . since the private method is only accessible and visible inside the class
they are declared, it is not possible to override them in subclass.
Through, you can override them inside the inner class as they are accessible there yes ,
compiler checks only method signature for overloading of method not the visibility of
method.
Q What method can be overridden ?
Ans:- Only inherited method can be overridden ?
Q What method can not be override ?
Ans:- Private , final , static can not be override .
Q how to invoke the overridden method ?
Ans:- Using the super keyword we can invoke the overridden method of super class.
Note :- Abstract method must be overridden by the first concrete(non abstract) subclass.
Constructor are special member function and have same name as class name. So, if
constructor were inherited in child class then child class would contain a parent
class constructor which is against the constraints the constructor should have same
name as class name.
Q How do you call superclass version of an overriding method as in sub class ?
Ans:- you call a super class version of an overriding method in the subclass by using super
keyword , for example to call the clone method from java.lang.Object class you can call
super.clone().
Q Is constructor overriding Possible ?
Ans:- Constructor looks like a method but name should be as class name and no return
value.
Overriding means what we have declared in super class , they exactly we have to declare
in sub class it is called overriding.
If you trying to write super class constructor in sub class , then sub class will treat that as a
method not constructor because name should not match with sub class name. Ans it will
give an compilation error that methods does not have return value so , we should declare
as void , then only it will compile .
Q Can we change argument list of an overriding method ?
Ans:- No You can not . The argument list is part of the method signature and both
overriding method must have the same signature.
Q Can we change the return type of method to sub class while overriding ?
Ans:- Before java version 1.5 it was not possible to override any method by changing the
return type . But now since java version 1.5 it is possible to override method by changing
the return type if sub class override any method whose return type is non-primitive but it
changes its return type to subclass type.
This is immensely helpful if original method return return super-class ex:- clone() method
return java.lang.Object by using this, you can directly return the actural type, preventing
client -side type casting of the result.
Q What is covariant method overriding in java ?
Ans:- The covariant return types are newly introduced since java 1.5 and used during
method overriding covariant return type allows us to change the return type of the
overriding method in the sub class ; however this return type in subclass method must be
a subtype of super class method return type . it is very helpful in case original method is
returning general type like Object class , because , then by using covariant method
overriding you can return more suitable Object and prevent client side type casting.
Q Can we override the main method in java?
Ans:- No you can not override the main method in java because main method is static and
static method resolved at compile time without needing Object information hence we can
not override the main method in java.
Q What is method hiding in java?
Ans:- When superclass and subclass contain the same method including parameter and if
they are static . The method in the superclass will be hidden by the one that is in the sub
class this machnism is known as method hiding.
Q What is difference between method overriding and method hiding in java ?
Ans:- Method Overriding Method hiding