Introduction JavaScript is a object-based scripting language and it is light weighted. It is first implemented by Netscape (with help from Sun Microsystems). JavaScript was created by Brendan Eich at Netscape in 1995 for the purpose of allowing code in web-pages (performing logical operation on client side). It is not compiled but translated. JavaScript Translator is responsible to translate the JavaScript code which is embedded in browser. Netscape first introduced a JavaScript interpreter in Navigator 2. The interpreter was an extra software component in the browser that was capable of interpreting JavaSript source code inside an HTML document. This means that web page developer no need other software other than a text editor of develop any web page. Why we Use JavaScript? Using HTML we can only design a web page but you can not run any logic on web browser like addition of two numbers, check any condition, looping statements (for, while), decision making statement (if-else) at client side. All these are not possible using HTML So for perform all these task at client side you need to use JavaScript.
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Introduction
JavaScript is a object-based scripting language and it is light weighted. It is first implemented by
Netscape (with help from Sun Microsystems). JavaScript was created by Brendan Eich at
Netscape in 1995 for the purpose of allowing code in web-pages (performing logical operation on
client side).
It is not compiled but translated. JavaScript Translator is responsible to translate the JavaScript
code which is embedded in browser.
Netscape first introduced a JavaScript interpreter in Navigator 2. The interpreter was an extra
software component in the browser that was capable of interpreting JavaSript source code inside
an HTML document. This means that web page developer no need other software other than a
text editor of develop any web page.
Why we Use JavaScript?
Using HTML we can only design a web page but you can not run any logic on web browser like
addition of two numbers, check any condition, looping statements (for, while), decision making
statement (if-else) at client side. All these are not possible using HTML So for perform all these
task at client side you need to use JavaScript.
Where it is used?
It is used to create interactive websites. It is mainly used for:
Client-side validation
Dynamic drop-down menus
Displaying data and time
Build small but complete client side programs .
Displaying popup windows and dialog boxes (like alert dialog box, confirm
dialog box and prompt dialog box)
Displaying clocks etc.
History
JavaScript is a object-based scripting language and it is light weighted. It is first implemented
by Netscape (with help from Sun Microsystems). JavaScript was created by Brendan Eich at
Netscape in 1995 for the purpose of allowing code in web-pages (performing logical operation on
client side).
Using HTML we can only design a web page but you can not run any logic on web browser like
addition of two numbers, check any condition, looping statements(for, while), decision making
statement(if-else) etc. All these are not possible using HTML so for perform all these task we use
JavaScript.
Using HTML we can only design a web page if we want to run any programs like c programming
we use JavaScript. Suppose we want to print sum of two number then we use JavaScript for
coding.
Features of JavaScript
JavaScript is a client side technology, it is mainly used for gives client side validation, but it have
lot of features which are given below;
JavaScript is a object-based scripting language.
Giving the user more control over the browser.
It Handling dates and time.
It Detecting the user's browser and OS,
It is light weighted.
JavaScript is a scripting language and it is not java.
JavaScript is interpreter based scripting language.
JavaScript is case sensitive.
JavaScript is object based language as it provides predefined objects.
Every statement in javascript must be terminated with semicolon (;).
Most of the javascript control statements syntax is same as syntax of
control statements in C language.
An important part of JavaScript is the ability to create new functions
within scripts. Declare a function in JavaScript using function keyword.
Uses of JavaScript
There are too many web applications running on the web that are using JavaScript technology
like gmail, facebook,twitter, google map, youtube etc.
Uses of JavaScript
Client-side validation
Dynamic drop-down menus
Displaying data and time
Validate user input in an HTML form before sending the data to a server.
Build forms that respond to user input without accessing a server.
Change the appearance of HTML documents and dynamically write HTML
into separate Windows.
Open and close new windows or frames.
Manipulate HTML "layers" including hiding, moving, and allowing the
user to drag them around a browser window.
Build small but complete client side programs .
Displaying popup windows and dialog boxes (like alert dialog box, confirm
dialog box and prompt dialog box)
Displaying clocks etc.
Comment
Comment is nothing but it is a statement which is not display on browser window. it is useful to
understand the which code is written for what purpose.
Comments are useful in every programming language to deliver message. It is used to add
information about the code, warnings or suggestions so that the end user or other developer can
easily interpret the code.
Types of JavaScript Comments
There are two types of comments are in JavaScript
Single-line Comment
Multi-line Comment
Single-line Comment
It is represented by double forward slashes (//). It can be used before any statement.
Example
<script> // It is single line comment document.write("Hello Javascript"); </script>
Result
Hello Javascript
Multi-line Comment
It can be used to add single as well as multi line comments.
It is represented by forward slash (/) with asterisk (*) then asterisk with forward slash.Example
<script> /* It is multi line comment. It will not be displayed */ document.write("Javascript multiline comment");
</script>
JavaScript First Program
Javascript simple example to verify age of any person, if age is greater than 18 show message
adult otherwise show under 18
JavaScript Example to verify age
Example
<html><head><script>function verify(){var no;no=Number(document.getElementById("age").value);if(no<18){alert("Under 18");}else{alert("You are Adult");}}</script></head><body>Enter your age:<input id="age"><br /><button onclick="verify()">Click me</button></body></html>
Result
Enter your age:
Click me
Way of Using JavaScript
There are three places to put the JavaScript code.
Between the <body> </body> tag of html (Inline JavaScript)
Between the <head> </head> tag of html (Internal JavaScript)
In .js file (External JavaScript)
Inline JavaScript
When java script was written within the html element using attributes related to events of the
A variable which is declared inside block or function is called local variable. It is accessible within
the function or block only. For example:
Example
<script>
function abc(){ var x=10; //local variable } </script>
or
Example
<script> If(10<13){ var y=20;//javascript local variable } </script>
Global Variable
A global variable is accessible from any function. A variable i.e. declared outside the function or
declared with window object is known as global variable. For example:
Syntax
<script> var value=10;//global variable function a(){ alert(value); } function b(){ alert(value); } </script>
Declaring global variable through window object
The best way to declare global variable in javascript is through the window object. For example:
Syntax
window.value=20;
Now it can be declared inside any function and can be accessed from any function. For example:
Example
function m(){ window.value=200; //declaring global variable by window object } function n(){ alert(window.value); //accessing global variable from other function }
Example of JavaScript
Here i will show you how to write you first javascript code, you only need to write your javascript
code inside <script> ..... </script> tag using any editor like notepad or edit plus. Save below code
with .html or .htm extension. No need to compile your javascript code just open your code in any
var i, no, fact;fact=1;no=Number(document.getElementById("num").value);for(i=1; i<=no; i++) {fact= fact*i;} document.getElementById("answer").value= fact;}</script></head><body>Enter Num: <input id="num"><button onclick="show()">Factorial</button><input id="answer">
</body></html>
Result
Enter Num: Factorial
Code Explanation
no=Number(document.getElementById("num").value);This code is used for receive input value form input field which have id
num.
document.getElementById("answer").value= fact;This code is used for receive calculated value of factorial and display in
input field which have id answer
<button onclick="show()">Factorial</button>This code is used for call show function when button clicked.
If else Statement
The if statement is used in JavaScript to execute the code if condition is true or false. There are
three forms of if statement.
If Statement
If else statement
if else if statement
JavaScript If statement
if is most basic statement of Decision making statement. It tells to program to execute a certain
part of code only if particular condition or test is true.
Syntax
Syntax
if(expression){ //set of statements }
Example
<script> var a=10; if(a>5){ document.write("value of a is greater than 5"); } </script>
JavaScript if-else statement
In general it can be used to execute one block of statement among two blocks.
Syntax
if(expression){ //set of statements } else{//set of statements }
Example of if..else statement
<script> var a=40; if(a%2==0){
document.write("a is even number"); } else{ document.write("a is odd number"); } </script>
Result
a is even number
JavaScript If...else if statement
It evaluates the content only if expression is true from several expressions.
Syntax
if(expression1){ //content to be evaluated if expression1 is true } else if(expression2){ //content to be evaluated if expression2 is true } else{ //content to be evaluated if no expression is true }
Example of if..else if statement
<script> var a=40; if(a==20){document.write("a is equal to 20"); }
else if(a==5){document.write("a is equal to 5"); }else if(a==30){document.write("a is equal to 30"); } else{ document.write("a is not equal to 20, 5 or 30"); } </script>
Looping Statement in
Set of instructions given to the compiler to execute set of statements until condition becomes
false is called loops. The basic purpose of loop is code repetition.
The way of the repetition will be forms a circle that's why repetition statements are called loops.
Some loops are available In JavaScript which are given below.
while loop
for loop
do-while
while loop
When we are working with while loop always pre-checking process will be occurred. Pre-checking
process means before evolution of statement block condition part will be executed. While loop will
be repeats in clock wise direction.
Syntax
while (condition) {code block to be executed}
Example of while loop
<script> var i=10; while (i<=13) { document.write(i + "<br/>"); i++; } </script>
Result
10
11
12
13
do-while loop
In implementation when we need to repeat the statement block at least 1 then go for do-while. In
do-while loop post checking of the statement block condition part will be executed.
syntax
do{ code to be executed increment/decrement}while (condition);
The switch statement is used in JavaScript to execute one code from multiple expressions.
Example
switch(expression){case value1:statement;break; case value2:statement;break; ......
default: statement;
}
Note: default code to be executed if above values are not matched
Note: in switch statement all the cases will be evaluated if we do not use break statement.
Example of switch statement in javascript.
Example
<script> var grade='B'; var result; switch(grade){ case 'A': result="A Grade"; break; case 'B': result="B Grade"; break; case 'C': result="C Grade"; break; default: result="No Grade"; } document.write(result); </script>
Result
Output: B Grade
Example of switch case in javascript
Example
<html><head>
<script>function myFunction() { var day; day=Number(document.getElementById("first").value); switch (day) { case 1: day = "Sunday"; break; case 2: day = "Monday"; break; case 3: day = "Tuesday"; break; case 4: day = "Wednesday"; break; case 5: day = "Thursday"; break; case 6: day = "Friday"; break; case 7: day = "Saturday"; break;default:day="Enter valid number" } document.getElementById("demo").innerHTML =day;}</script></head><body>
<p>Enter any number (1 to 7):</p><input id="first"><button onclick="myFunction()">Try it</button><p id="demo"></p></body></html>
Result
Enter any number (1 to 7):
Try it
Function
An important part of JavaScript is the ability to create new functions within <script> and </script>
tag. Declare a function in JavaScript using function keyword. The keyword function precedes
the name of the function.Syntax
function functionName(parameter or not){..................}
Example of JavaScript using Function
Example
<html><head><script>function getname()
{name=prompt("Enter Your Name");alert("Welcome Mr/Mrs " + name);}</script></head><form><input type="button" value="Click" onclick="getname()"/></form></html>
Example
Array in JavaScript
Array are used to represents the group of elements into a single unit or consecutive memory
location. Each and every element what we are entering into the array is going to be stored in the
array with the unique index starting from zero. Through the indexes we can store the data or
elements into the array or we can get the elements from the array.
To declare an array in javascript we need new keyword. To create an array you use new Array(n)
where n was the number of slots in the array or new Array() omitting the size of an array.
Note: Whenever we create any array in javaScript without specifying the size then it well create
{alert("Alert function call");}</script></head><form><input type="button" value="Click Me" onclick="alertmsg()"/></form></html>
Result
prompt()
Prompt function of java script is used to get input from the user.
prompt() function example
Example
<!doctype html><html><head><script>function alertmsg(){a=prompt("Enter your name:");alert(a);}</script></head><form><input type="button" value="Click Me" onclick="alertmsg()"/></form></html>
Result
confirm()
confirm function of java script is used to get confirmation from user before executing some task.
confirm() function example
Example
<!doctype html><html><head><script>function alertmsg(){a=prompt("Enter your name:");confirm(a);}</script></head><form><input type="button" value="Click Me" onclick="alertmsg()"/></form></html>
Result
Window Object
The window object represents a window in browser. An object of window is created
automatically by the browser.
Window is the object of browser, it is not the object of javascript. The javascript objects are string,
array, date etc. It is used to display the popup dialog box such as alert dialog box, confirm dialog
box, input dialog box etc.
The window methods are mainly for opening and closing new windows. The following are the
main window methods. They are:
Methods of window object
Method Description
alert() displays the alert box containing message with ok button.
confirm() Displays the confirm dialog box containing message with ok and cancel button.
prompt() Displays a dialog box to get input from the user.
open() Opens the new window.
close() Closes the current window.
setTimeout() Performs action after specified time like calling function, evaluating expressions
etc.
Document Object
The document object represents the whole html document. When html document is loaded in
the browser, it becomes a document object. It is the root element that represents the html
document.
Methods of document object
Method Description
write("string") writes the given string on the document.
writeln("string") Same as write(), but adds a newline character after each statement.
getElementById() returns the element having the given id value.
getElementsByName() returns all the elements having the given name value.
getElementsByTagName() returns all the elements having the given tag name.
getElementsByClassName() returns all the elements having the given class name.
Event in JavaScript
All objects have properties and methods. In addition, some objects also have "events". Events
are things that happen, usually user actions, that are associated with an object. The "event
handler" is a command that is used to specify actions in response to an event. Below are some of
the most common events:
Event Discription
onLoad Occurs when a page loads in a browser
onUnload occurs just before the user exits a page
onMouseOver occurs when you point to an object
onMouseOut occurs when you point away from an object
onSubmit occurs when you submit a form
onClick occurs when an object is clicked
Events and Objects
Events are things that happen, actions, that are associated with an object. Below are some
common events and the object they are associaated with:
Event Object
onLoad Body
onUnload Body
onMouseOver Link, Button
onMouseOut Link, Button
onSubmit Form
onClick Button, Checkbox, Submit, Reset, Link
getElementById
The document.getElementById() method returns the element of specified id. In below example
we receive input from input field by using document.getElementById() method, here
document.getElementById() receive input value on the basis on input field id. In below example
"number" is the id of input field.Example
<html><body><head><script type="text/javascript"> function squre(){ var num=document.getElementById("number").value; alert(num*num); } </script> </head><form> Enter No:<input type="text" id="number" name="number"/><br/> <input type="button" value="squre" onclick="squre()"/> </form></body>
</html>
Result
Enter No:
Code Explanation
var num=document.getElementById("number").value; In this code getElementById received
value from input field which have id number.
Square of any number in javascript
Example
<html><body><head><script type="text/javascript"> function squre(){ var num=document.getElementById("number").value; var result=num*num; document.getElementById("answer").value=result;} </script> </head><form>Enter No:<input type="text" id="number" name="number"/><input type="button" value="squre" onclick="squre()"/><input id="answer"/></form></body></html>
Result
Enter No:
JavaScript Forms Validation
Forms validation is important things other wise user input wrong data, so we need to validate
given data by user before submit it on server.
The JavaScript provides the facility to validate the form on the client side so processing will be
fast than server-side validation. So, most of the web developers prefer client side form validation
using JavaScript.
Here i will show you how to validate any input field like user name can not be blank. In below
example input are can not be blank.
Example
<html><head><script> function form_validation(){ var name=document.myform.name.value;
//var x = document.forms["myform"]["name"].value;
if (name==null || name==""){ alert("Name can't be blank"); return false; } }</script> </head>
We can validate the email with the help of JavaScript. Here we check the condition related to any
email id, like email if must have "@" and "." sign and also email id must be at least 10 character.
There are many criteria that need to be follow to validate the email id such as:
email id must contain the @ and . character
There must be at least one character before and after the @.
There must be at least two characters after . (dot).Example
<html><head><script>function email_validation() { var x=document.myform.email.value; var atposition=x.indexOf("@"); var dotposition=x.lastIndexOf("."); if (atposition<1 || dotposition<atposition+2 || dotposition+2>=x.length){ alert("Please enter a valid e-mail address \n atpostion:"+atposition+"\n dotposition:"+dotposition); return false; } } </script>
Here i will show you how to validate any password field like password field can not be blank and
length of password is minimum 8 character.
Example
<html><head><script>function pass_validation(){ var password=document.myform.password.value;
if (password==null || password==""){ alert("password can't be blank"); return false; }else if(password.length<8){ alert("Password must be at least 8 characters long.");
JavaScript is a scripting language. It is object-based scripting language. It is light weighted. It is
different from Java language. It is widely used for client side validation.
JavaScript is which type of Language ?
JavaScript is a object-based scripting language. It is light weighted.
Why we use JavaScript ?
Using Html we can only design a web page. Using Html we can not run any logic on web browser
like addition of two numbers, check any condition, looping statements(for, while), decision making
Submit
statement(if-else) etc at client side. All these are not possible using Html so for perform all these
task at client side we use JavaScript.
Where JavaScript is used ?
It is used to create interactive websites. It is mainly used for:
Client-side validation
Dynamic drop-down menus
Displaying data and time
Build small but complete client side programs .
Displaying popup windows and dialog boxes (like alert dialog box, confirm
dialog box and prompt dialog box)
Displaying clocks etc.
What is the difference between == and ===
The 3 equal signs (===) mean "equality without type coercion". Using the triple equals, the values
must be equal in type as well. It checks for equality as well as the type.
== means simple equal to, it compare two values only. It checks equality only,
Example
== is equal to === is exactly equal to (value and type)0==false // true 0===false // false, because they are of a different type1=="1" // true, auto type coercion1==="1" // false, because they are of a different type
How to declare variable in JavaScript ?
Java script did not provide any data types for declaring variables and a variable in java script can
store any type of value. We can use a variable directly without declaring it. Only var keyword are
use before variable name to declare any variable.
Syntax
var x;
Difference between Window object and document object
Document object Window object
The document object represents the whole html document. When html document is loaded in the browser, it becomes a document object.
The window object represents a window in browser. An object of window is created automatically by the browser.
What would be the difference if we declare two variables inside a JavaScript, one with 'var' keyword and another without 'var' keyword ?
The variable with var keyword inside a function is treated as Local variable, and the variable
without var keyword inside a function is treated a global variable.
What is a closure in JavaScript ?
JavaScript allows you to declare a function within another function, and the local variables still
can be accessible even after returning from the function you called.
In other words, a closure is the local variables for a function which is kept alive after the function
has returned.
What is uses of Window Object ?
The window object represents a window in browser. An object of window is created automatically
by the browser. It is used to display the popup dialog box such as alert dialog box, confirm dialog
box, input dialog box etc.
What is Document Object
The document object represents the whole html document. When html document is loaded in the
browser, it becomes a document object. It is the root element that represents the html document.
Is JavaScript case sensitive ?
Yes!
A function getElementById is not the same as getElementbyID
What does "1"+2+3 evaluate to ?
After a string all the + will be treated as string concatenation operator (not binary +), so the result
is 123.
What does 1+2+"5" evaluate to ?
If there is numeric value before and after +, it is treated is binary + (arithmetic operator), so the
result is 35.
Difference between get and post method.
Http protocol mostly use either get() or post() methods to transfer the request.
Get method Post method
1 Request sends the request parameter as query string appended at the end of the request.
Post request send the request parameters as part of the http request body.
2 Get method is visible to every one (It will be displayed in the address bar of browser ).
Post method variables are not displayed in the URL.
3 Restriction on form data, only ASCII characters allowed.
No Restriction on form data, Binary data is also allowed.
4 Get methods have maximum size is 2000 character.
Post methods have maximum size is 8 mb.
5 Restriction on form length, So URL length is restricted No restriction on form data.
6 Remain in browser history. Never remain the browser history.
How to create function in JavaScript ?
Declare a function in JavaScript using function keyword. The keyword function precedes the
name of the function.
Syntax
function function_name(){ //function body }
Read more.......
How to write comment in JavaScript ?
There are two types of comment are available in JavaScript.
Single Line Comment: It is represented by // (double forward slash)
Multi Line Comment: It is represented by slash with asterisk symbol as /*
write comment here */
How do we add JavaScript onto a web page?
There are several way for adding javascript on a web page but there are two way with is
commonly used by developers
Between the <body> </body> tag of html (Inline JavaScript)
Between the <head> </head> tag of html (Internal JavaScript)
There are following way to access the value of the above textbox
Example
var name = document.getElementById('txtname').value;alert(name);or we can use the old waydocument.forms[0].mybutton.var name = document.forms[0].FirstName.value;
alert(name);
Note: This uses the "name" attribute of the element to locate it.
How you will get the CheckBox status whether it is checked or not ?
Example
var status = document.getElementById('checkbox1').checked; alert(status); //it will return true or false
How to create arrays in JavaScript ?
Example
var names = new Array();
// Add Elements in Arraynames[0] = "Hina";names[1] = "Niki";names[2] = "Ram";
// This is second wayvar names = new Array("Hina", "Niki", "Ram");
If an array with name as "marks" contain three elements then how you will print the third element of this array?
Example
Print third array element document.write(marks[2]);
Note: Array index start with 0
What does the isNaN() function ?
The isNan() function returns true if the variable value is not a number.
Variable of the boolean type is automatically initialized as ?
The default value of the boolean type is false.
Difference between static vs. dynamic class loading ?
static loading: Classes are statically loaded with Java new operator.
dynamic class loading: Dynamic loading is a technique for programmatically invoking the
functions of a class loader at run time.
Difference between composition and inheritance in Java ?
Composition Inheritance
has-a relationship between classes. is-a relationship between classes.
Used in Dependency Injection Used in Runtime Polymorphism
Single class objects can be composed within multiple classes.
Single class can only inherit 1 Class.
Its the relationship between objects. Its the relationship between classes.
What do you mean by "Java is a statically typed language" ?
It means that the type of variables are checked at compile time in Java.The main advantage here
is that all kinds of checking can be done by the compiler and hence will reduce bugs.
What are different ways of object creation in Java ?
.
Using new operator - new xyzClass()
Using factory methods - xyzFactory.getInstance( )
Using newInstance( ) method
By cloning an already available object - (xyzClass)obj1.clone( )
Explain Autoboxing ?
Autoboxing is the automatic conversion that the Java compiler makes between the primitive types
and their corresponding object wrapper classes.
What is an Enum type ?
An enum type is a special data type that enables for a variable to be a set of predefined
constants.
What are Wrapper Classes ?
A wrapper class is any class which "wraps" or "encapsulates" the functionality of another class or
component.
What are Primitive Wrapper Classes ?
A Wrapper Class that wraps or encapsulates the primitive data type is called Primitive Wrapper
Class..
Why use Scanner class ?
For reading Data Stream from the input device.
Difference between loadClass and Class.forName ?
loadClass only loads the class but doesn't initialize the object whereas Class.forName initialize
the object after loading it.
Should we override finalize method ?
Finalize is used by Java for Garbage collection. It should not be done as we should leave the
Garbage Collection to Java itself.
Why Java don't use pointers ?
Pointers are vulnerable and slight carelessness in their use may result in memory problems and
hence Java intrinsically manage their use.
Do we need to import java.lang.package ?
No, It is loaded by default by the JVM.
What is the difference between System.out ,System.err and System.in ?
System.out and System.err both represent the monitor by default and hence can be used to send
data or results to the monitor. But System.out is used to display normal messages and results
whereas System.err is used to display error messages and System.in represents InputStream
object, which by default represents standard input device, i.e., keyboard.
Is it possible to compile and run a Java program without writing main( ) method ?
Yes, it is possible by using a static block in the Java program.
Can we call the garbage collector explicitly ?
We can call garbage collector of JVM to delete any unused variables and unreferenced objects
from memory using gc( ) method. This gc( ) method appears in both Runtime and System classes
of java.lang package.
What are different oops concept in java ?
OOPs stands for Object Oriented Programming. The oops concepts are similar in any other
programming languages. Because it is not programming concept. All oops concept in java are;
Class
Object
Polymorphism
Inheritance
Abstraction
Encapsulation
Aggreagation
Composition
Association
What is class ?
A class is a specification or blue print or template of an object.
What is object ?
Object is instance of class. It is dynamic memory allocation of class.
What are the Characteristics of Object ?
Characteristics of Object are;State Behavior and Identity.
Can a class extend more than one class in Java ?
No, a class can only extend another class because Java doesn't support multiple inheritances but
yes, it can implement multiple interfaces.
What is the difference between abstraction and polymorphism in Java ?
Abstraction generalizes the concept and Polymorphism allow you to use different implementation
without changing your code.
What is an Abstraction ?
Abstraction is a process to show only usful data and remaining hide from user.
Real Life Example of Abstraction ?
When you log into your email, compose and send a mail. Again there is a whole lot of
background processing involved, verifying the recipient, sending request to the email server,
sending your email. Here you are only interested in composing and clicking on the send button.
What really happens when you click on the send button, is hidden from you.
Real life example of abstraction ?
Real life example of abstraction is ATM machine; here only show balance in your account but not
display ATM pin code.
What is Encapsulation ?
The process of binding data and methods into a single unit is known as Encapsulation. In other
word The process of binding the data with related methods known as encapsulation.
Real Life Example of Encapsulation ?
Encapsulation is like enclosing in a capsule.
Encapsulation is like your bag in which you can keep your pen, book etc.
What is inheritance ?
It is used in java for achieve concept of re-usability. As the name suggests , inheritance means to
take something that already made.
What is polymorphism ?
It is process to represent any things in multiple forms.
Real life example of Polymorphism ?
A Person who knows more than two languages he can speak in a language which he knows.
Here person is Object and speak is polymorphisam.
What is method overloading in Java ?
When same method is available in any class with same name and different signature is called
method overloading.
What is method overriding in Java ?
When same method available in base class and drive class with same name and same signature
it is called method overriding.
What is Aggregation ?
If a class have an entity reference, it is known as Aggregation. Aggregation represents HAS-A
relationship..
What is Composition ?
Composition is the design technique to implement has-a relationship in classes. Composition in
java is achieved by using instance variables that refers to other objects.
Can we declare abstract method as final ?
No. its not possible to declare abstract method with final keyword. Because abstract methods
should be override by its sub classes.
Is it possible to declare abstract method as private ?
No. its not possible to declare abstract method with private. Because abstract methods should be
override by its sub classes.
Differences between method Overloading and method Overriding ?
Overloaded Method Overridden Method
Arguments Must be Change Must not be change
Return Type Can change Can't change except for covariant
returns
Exceptions Can ChangeCan reduce or eliminate. Must not throw new or broader checked exceptions
Access Can change Must not make more restrictive (can be less restrictive)
InvocationReference type determines which overloaded version is selected. Happens at compile time.
Object type determines which method is selected. Happens at runtime.
Why use constructor ?
The main purpose of create a constructor is, for placing user defined values in place of default
values.
Why constructor not return any value ?
Constructor will never return any value even void, because the basic aim constructor is to place
value in the object
Why constructor definition should not be static ?
Constructor definition should not be static because constructor will be called each and every time
when object is created. If you made constructor is static then the constructor before object
creation same like main method.
Why constructor is not inherited ?
Constructor will not be inherited from one class to another class because every class constructor
is created for initialize its own data members.
What is purpose of default constructor ?
The purpose of default constructor is to create multiple object with respect to same class for
placing same value.
What is purpose of parameterized constructor ?
The purpose of parametrized constructor is to create multiple object with respect to same class
for placing different value of same type or different type or both.
Is constructor inherited?
No, constructor is not inherited.
Can you make a constructor final?
No, constructor can't be final.
What is the purpose of default constructor?
The default constructor provides the default values to the objects. The java compiler creates a
default constructor only if there is no constructor in the class.
Can we use both "this" and "super" in a constructor ?
No, because both this and super should be the first statement.
Does constructor return any value?
yes, that is current instance (You cannot use return type yet it returns a value).
What is flow of constructor in Java ?
Constructor are calling from bottom to top and executing from top to bottom.
Why overriding is not possible at constructor level. ?
The scope of constructor is within the class so that it is not possible to achieved overriding at
constructor level.
Difference between Method and Constructor
Method Constructor
1 Method can be any user defined name Constructor must be class name
2 Method should have return type It should not have any return type (even void)
3 Method should be called explicitly either with object reference or class reference
It will be called automatically whenever object is created
1 Method is not provided by compiler in any case.
The java compiler provides a default constructor if we do not have any constructor.
What is Abstraction ?
Abstraction is a process of hiding the implementation details and showing only functionality to the
user.
How achieve Abstraction in Java ?
There are two ways to achieve abstraction in java
Abstract class (0 to 100%)
Interface (100%)
Real life example of Abstraction ?
Mobile phone is one of example of abstraction. We only know about how to call and use mobile
but we can't know about internal functionally of mobile phone.
Real life example of Abstraction and Encapsulation ?
Outer Look of a Television, like it has a display screen and channel buttons to change channel it
explains Abstraction but Inner Implementation detail of a Television how CRT and Display Screen
are connect with each other using different circuits , it explains Encapsulation.
Which of the following Java feature show only important information ?
Inheritance
Encapsulation
Abstraction
Composition
Ans: Abstraction
What is Polymorphism ?
The ability to define a function in multiple forms is called Polymorphism.
What is Overloading ?
Whenever several methods have same names with;
Different method signature and different number or type of parameters.
Same method signature but different number of parameters.
Same method signature and same number of parameters but of different
type
It is determined at the compile time.
What is method overriding ?
If subclass (child class) has the same method as declared in the parent class, it is known as
method overriding in java. It is determined at the run time.
Difference between method overloading and mehtod Overloading ?
Method overloading is determined at the compile time and method overriding is determined at the
run time
How to achieve polymorphism in Java ?
How to achieve polymorphism in Java ?
In Java, static polymorphism is achieved through method overloading and method overriding.
Types of polymorphism in Java ?
In Java, there are two types of polymorphism.
Compile time polymorphism (static binding or method overloading)
Runtime polymorphism (dynamic binding or method overriding)
How to achieve static polymorphism in Java ?
In Java, static polymorphism is achieved through method overloading.
How to achieve dynamic polymorphism in Java ?
In Java, dynamic polymorphism is achieved through method overriding.
What is Compile time polymorphism ?
As the meaning is implicit, this is used to write the program in such a way, that flow of control is
decided in compile time itself. It is achieved using method overloading.
Example
public static int add(int a, int b){............}
public static double add(double a, double b){............}
public static float add(float a, float b){............}
What is Runtime polymorphism ?
Run time Polymorphism also known as method overriding and it is achieve at runtime.
Example
class Vehicle{ public void move() { System.out.println("Vehicles can move !!!!"); }}
class MotorBike extends Vehicle { public void move(){
System.out.println("MotorBike can move and accelerate too!!!");}}
class Demo {
public static void main(String[] args) { Vehicle obj=new MotorBike(); obj.move(); // prints message MotorBike can move and accelerate too!!! obj=new Vehicle(); obj.move(); // prints message Vehicles can move!! }}
What is Interface ?
An interface is a collection of abstract methods. A class implements an interface, thereby
inheriting the abstract methods of the interface..
Main features of Interface ?
Interface cannot be instantiated
An interface does not contain any constructors
All of the methods in an interface are abstract
Can an Interface be final ?
No, because its implementation is provided by another class.
What is marker interface ?
An interface that have no data member and method is known as a marker interface.For example
Serializable, Cloneable etc.
What is difference between abstract class and interface ?
An abstract class can have method body (non-abstract methods) but Interface have only abstract
methods.
How to implement Interface in Java ?
Syntax
interface A{........}interface B{........}class C implements A,B{........}
In Java Programming Inheritance is used for reuse features of one class into another class, Using
this concept enhance (improve or increase) performance of application.
What is Inheritance ?
Inheritance is one of the main features of any object oriented programming. Using inheritance
concept, a class (Sub Class) can inherit properties of another class (Super Class). So it is used
for reuse features.
Main advantage of using Inheritance ?
Using this feature you can reuse features, less memory wastage, less time required to develop
and application and improve performance of application.
Types of Inheritance supported by Java ?
Java support only four types of inheritance in java.
Single Inheritance
Multi level Inheritance
Hybrid Inheritance
Hierarchical Inheritance
Why use Inheritance ?
For Code Re usability.
For Method Overriding.
What is multilevel inheritance ?
Getting the properties from one class object to another class object level wise with different
priorities.
Which of these keyword must be used to inherit a class ?
a) super
b) this
c) extent
d) extends
d. extends
What is Multiple Inheritance ?
The concept of Getting the properties from multiple class objects to sub class object with same
priorities is known as multiple inheritance.
How Inheritance can be implemented in java ?
Inheritance can be implemented in Java using two keywords, they are;
extends
Implements
Which of these keywords is used to refer to member of base class from a sub class ?
a) upper
b) super
c) this
d) None of these
Answer: b
extends is used for developing inheritance between two classes and two interfaces.
Implements keyword is used to developed inheritance between interface and class.
What is syntax of inheritance ?
Syntax
public class subclass extends superclass{//all methods and variables declare here}
Which inheritance are not supported bb Java ?
Multi Inheritance is not supported by java.
How Inheritance can be implemented in java ?
Inheritance can be implemented in JAVA using these two keywords; extends and implements
How do you implement multiple inheritance in java ?
Using interfaces java can support multiple inheritance concept in java.
Syntax
interface A{........}interface B{........}class C implements A,B{........}
How do you implement multiple inheritance in java ?
Using interfaces java can support multiple inheritance concept in java. in java can not extend
more than one classes, but a class can implement more than one interfaces.
Why we need to use Inheritance ?
It is used for code re-usability and for Method Overriding.