Likes

Core Java MT Solved



1.Identify the features of New API (NIO).

Ans:
i)The new API works more consistently across platforms.
ii)It makes it easier to write programs that gracefully handle the failure of file system operations.
iii)It provides more efficient access to a larger set of file attributes.

2.Differentiate between checked and unchecked exceptions.

Ans:
Checked Exception:
i)Every class that is a subclass of Exception except RuntimeException and its subclasses falls into the category of checked exceptions.
ii)You must ?handle or declare? these exceptions with a try or throws statement.

Unchecked Exception:
i)java.lang.RuntimeException and java.lang.Error and their subclasses are categorized as unchecked exceptions.
ii)You may use a try-catch statement to help discover the source of these exceptions, but when an application is ready for production use, there should be little code remaining that deals with RuntimeException and its subclasses.

3.Explain public, static, and void keywords in the following statement: public static void main(String args[])

Ans:
i)public: The public keyword indicates that the method can be accessed from anyobject in a Java program.
ii)static: The static keyword is used with the main() method that associates the method with its class. You need not create an object of the class to call the main() method.
iii)void: The void keyword signifies that the main() method returns no value.

4.Identify the limitations of the java.io.File class.

Ans:
The java.io.File class has the following limitations:
i)Many methods did not throw exceptions when they failed, so it was impossible to obtain useful error messages.
ii)Several operations were missing (file copy, move, and so on).
iii)The rename method did not work consistently across platforms.
iv)There was no real support for symbolic links.
v)More support for metadata was desired, such as file permissions, file owner, and other security attributes.
vi)Accessing file metadata was inefficient?every call for metadata resulted in a system call, which made the operations very inefficient.
vii)Many of the File methods did not scale. Requesting a large directory listing on a server could result in a hang.
viii)It was not possible to write reliable code that could recursively walk a file tree and respond appropriately if there were circular symbolic links.

5.Identify the five classes of the java.util.concurrent package and explain any two classes.

Ans:
i)Semaphore: Is a classic concurrency tool.
ii)CountDownLatch: A very simple yet very common utility for blocking until a given number of signals, events, or conditions hold.
iii)CyclicBarrier: A resettable multiway synchronization point useful in some styles of parallel programming.
iv)Phaser: Provides a more flexible form of barrier that may be used to control phased computation among multiple threads.
v)Exchanger: Allows two threads to exchange objects at a rendezvous point, and is useful in several pipeline designs.


6.Steve has been asked to automate the Library Management System either in C++ or Java. Steve has chosen to develop the project in Java. Identify the reason.

Ans:
One of the major problem areas in most of the object-oriented languages, such as C++, is to handle memory allocation. Programmers need to explicitly handle memory in the program for its optimum utilization. To handle memory allocation, they use pointers that enable a program to refer to memory location of the computer. However, Java does not support pointers and consists of the built-in functionality to manage memory.


7.You have created a class with two instance variables.You need to initialize the variables automatically when a class is initialized. Identify the method that you will use you to achieve this. In addition, describe the characteristics of this method.

Ans:
You can initialize the variable by using the constructor. The characteristics of a constructor are:
-       A constructor has the same name as the class itself.
-       There is no return type for a constructor. A constructor returns the instance of the class instead of a value.
-        A constructor is used to assign values to the data members of each objectcreated from a class

8.Differentiate between interface and abstract class.

Ans:
1.The methods of a Java interface are implicitly abstract and cannot have implementations. A Java abstract class can have instance methods that implements a default behavior.
2.Variables declared in a Java interface are by default final. An abstract class may contain non-final variables.
3.Members of a Java interface are public by default. A Java abstract class can have the usual flavors of class members like private, protected, etc..
4.Java interface should be implemented using keyword, implements; A Java abstract class should be extended using keyword, extends.
5.An interface can extend another Java interface only, an abstract class can extend another Java class and implement multiple Java interfaces.
6.A Java class can implement multiple interfaces but it can extend only one abstract class.
7.Interface is absolutely abstract and cannot be instantiated; A Java abstract class also cannot be instantiated, but can be invoked if a main() exists.
8.In comparison with Java abstract classes, Java interfaces are slow as it requires extra indirection.



PSEUDOCODE

PSEUDOCODE STANDARD

Pseudocode is a kind of structured english for describing algorithms. It allows the designer to focus on the logic of the algorithm without being distracted by details of language syntax.  At the same time, the pseudocode needs to be complete.  It describe the entire logic of the algorithm so that implementation becomes a rote mechanical task of translating line by line into source code.
In general the vocabulary used in the pseudocode should be the vocabulary of the problem domain, not of the implementation domain.  The pseudocode is a narrative for someone who knows the requirements (problem domain) and is trying to learn how the solution is organized.  E.g.,
Extract the next word from the line (good)
set word to get next token (poor)Append the file extension to the name (good)
name = name + extension (poor)
FOR all the characters in the name (good)
FOR character = first to last (ok)
Note that the logic must be decomposed to the level of a single loop or decision. Thus "Search the list and find the customer with highest balance" is too vague because it takes a loop AND a nested decision to implement it. It's okay to use "Find" or "Lookup" if there's a predefined function for it such asString.indexOf().
Each textbook and each individual designer may have their own personal style of pseudocode. Pseudocode is not a rigorous notation, since it is read by other people, not by the computer. There is no universal "standard" for the industry, but for instructional purposes it is helpful if we all follow a similar style. The format below is recommended for expressing your solutions in our class.
The "structured" part of pseudocode is a notation for representing six specific structured programming constructs: SEQUENCE, WHILE, IF-THEN-ELSE, REPEAT-UNTIL, FOR, and CASE. Each of these constructs can be embedded inside any other construct. These constructs represent the logic, or flow of control in an algorithm.
It has been proven that three basic constructs for flow of control are sufficient to implement any "proper" algorithm.
SEQUENCE is a linear progression where one task is performed sequentially after another.
WHILE is a loop (repetition) with a simple conditional test at its beginning.
IF-THEN-ELSE is a decision (selection) in which a choice is made between two alternative courses of action.

Although these constructs are sufficient, it is often useful to include three more constructs:
REPEAT-UNTIL is a loop with a simple conditional test at the bottom.
CASE is a multiway branch (decision) based on the value of an expression. CASE is a generalization of IF-THEN-ELSE.
FOR is a "counting" loop.
SEQUENCE
Sequential control is indicated by writing one action after another, each action on a line by itself, and all actions aligned with the same indent. The actions are performed in the sequence (top to bottom) that they are written.
Example (non-computer)
Brush teeth
Wash face
Comb hair
Smile in mirror
Example
READ height of rectangle
READ width of rectangle
COMPUTE area as height times width
Common Action Keywords
Several keywords are often used to indicate common input, output, and processing operations.
Input: READ, OBTAIN, GET
Output: PRINT, DISPLAY, SHOW
Compute: COMPUTE, CALCULATE, DETERMINE
Initialize: SET, INIT
Add one: INCREMENT, BUMP
IF-THEN-ELSE
Binary choice on a given Boolean condition is indicated by the use of four keywords: IF, THEN, ELSE, and ENDIF. The general form is:
IF condition THEN
sequence 1
ELSE
sequence 2
ENDIF
The ELSE keyword and "sequence 2" are optional. If the condition is true, sequence 1 is performed, otherwise sequence 2 is performed.
Example
IF HoursWorked > NormalMax THEN
Display overtime message
ELSE
Display regular time message
ENDIF
WHILE
The WHILE construct is used to specify a loop with a test at the top. The beginning and ending of the loop are indicated by two keywords WHILE and ENDWHILE. The general form is:
WHILE condition
sequence
ENDWHILE
The loop is entered only if the condition is true. The "sequence" is performed for each iteration. At the conclusion of each iteration, the condition is evaluated and the loop continues as long as the condition is true.
Example
WHILE Population < Limit
Compute Population as Population + Births - Deaths
ENDWHILE
Example
WHILE employee.type NOT EQUAL manager AND personCount < numEmployees
INCREMENT personCount
CALL employeeList.getPerson with personCount RETURNING employee
ENDWHILE
CASE
A CASE construct indicates a multiway branch based on conditions that are mutually exclusive. Four keywords, CASE, OF, OTHERS, and ENDCASE, and conditions are used to indicate the various alternatives. The general form is:
CASE expression OF
condition 1 : sequence 1
condition 2 : sequence 2
...
condition n : sequence n
OTHERS:
default sequence
ENDCASEThe OTHERS clause with its default sequence is optional. Conditions are normally numbers or characters
indicating the value of "expression", but they can be English statements or some other notation that specifies the condition under which the given sequence is to be performed. A certain sequence may be associated with more than one condition.
Example 
        CASE  Title  OF
                Mr      : Print "Mister"
                Mrs     : Print "Missus"
                Miss    : Print "Miss"
                Ms      : Print "Mizz"
                Dr      : Print "Doctor"
        ENDCASE
Example 
        CASE  grade  OF
                A       : points = 4
                B       : points = 3
                C       : points = 2
                D       : points = 1
                F       : points = 0
        ENDCASE
REPEAT-UNTIL
This loop is similar to the WHILE loop except that the test is performed at the bottom of the loop instead of at the top. Two keywords, REPEAT and UNTIL are used. The general form is:
REPEAT
sequence
UNTIL condition
The "sequence" in this type of loop is always performed at least once, because the test is peformed after the sequence is executed. At the conclusion of each iteration, the condition is evaluated, and the loop repeats if the condition is false. The loop terminates when the condition becomes true. 

FOR
This loop is a specialized construct for iterating a specific number of times, often called a "counting" loop.  Two keywords, FOR and ENDFOR are used. The general form is:
FOR iteration bounds
sequence
ENDFOR
In cases where the loop constraints can be obviously inferred it is best to describe the loop using problem domain vocabulary.
Example
FOR each month of the year (good)
FOR month = 1 to 12 (ok)FOR each employee in the list (good)
FOR empno = 1 to listsize (ok)

NESTED CONSTRUCTS
The constructs can be embedded within each other, and this is made clear by use of indenting. Nested constructs should be clearly indented from their surrounding constructs.
Example
SET total to zero
REPEAT
READ Temperature
IF Temperature > Freezing THEN
    INCREMENT total
END IF
UNTIL Temperature < zero
Print total
In the above example, the IF construct is nested within the REPEAT construct, and therefore is indented. 
  

INVOKING SUBPROCEDURES
Use the CALL keyword. For example:
CALL AvgAge with StudentAges
CALL Swap with CurrentItem and TargetItem
CALL Account.debit with CheckAmount
CALL getBalance RETURNING aBalance
CALL SquareRoot with orbitHeight RETURNING nominalOrbit


EXCEPTION HANDLING

    BEGIN 
        statements 
    EXCEPTION 
        WHEN exception type 
            statements to handle exception
        WHEN another exception type 
            statements to handle exception
    END 



Sample Pseudocode

"Adequate"

FOR X = 1 to 10 

    FOR Y = 1 to 10 
        IF gameBoard[X][Y] = 0 
            Do nothing 
        ELSE 
            CALL theCall(X, Y) (recursive method) 
            increment counter                  
        END IF
    END FOR
END FOR

"Better"
Set moveCount to 1
FOR each row on the board 
    FOR each column on the board 
        IF gameBoard position (row, column) is occupied THEN 
            CALL findAdjacentTiles with row, column
            INCREMENT moveCount 
        END IF 
    END FOR
END FOR

(Note: the logic is restructured to omit the "do nothing" clause) 


"Not So Good"
FOR all the number at the back of the array
    SET Temp equal the addition of each number
    IF > 9 THEN
        get the remainder of the number divided by 10 to that index
        and carry the "1"
    Decrement one
Do it again for numbers before the decimal
"Good Enough (not perfect)"
SET Carry to 0
FOR each DigitPosition in Number from least significant to most significant
    COMPUTE Total as sum of FirstNum[DigitPosition] and SecondNum[DigitPosition] and Carry  
    IF Total > 10 THEN
        SET Carry to 1
        SUBTRACT 10 from Total
    ELSE
        SET Carry to 0
    END IF
    STORE Total in Result[DigitPosition]
END LOOP  
IF Carry = 1 THEN
    RAISE Overflow exception
END IF




"Pretty Good"  This example shows how pseudocode is written as comments in the source file. Note that the double slashes are indented.
public boolean moveRobot (Robot aRobot)
{
    //IF robot has no obstacle in front THEN
        // Call Move robot
        // Add the move command to the command history
        // RETURN true
    //ELSE
        // RETURN false without moving the robot
    //END IF
}
Example Java Implementation
  • source code statements are interleaved with pseudocode.
  • comments that correspond exactly to source code are removed during coding.

public boolean moveRobot (Robot aRobot)
{
    //IF robot has no obstacle in front THEN
    if (aRobot.isFrontClear())
    {
        // Call Move robot
        aRobot.move();
        // Add the move command to the command history
        cmdHistory.add(RobotAction.MOVE);
        return true;
    }
    else // don't move the robot
    {
        return false;
    }//END IF
}
  



Document History
DateAuthorChange
12/2/03JDAdded Exception Handling and more examples
2/21/03JDAdded "problem domain vocabulary" paragraph.
Modified FOR loop explanation.



Loop: if we want to print all result then insert o/p box in loop…
           if aggregate want to print then put o/p box out of the loop…

Pseudo code:
  1.  "//" is used to represent the Comment.
  2. "begin ...end" use to start and end the Pseudo code.
  3. "accept"  use to accept Input.
  4. "display" print Output.
  5. "if…. else" use to make decision.
  6. "repeat… un-till"




Pseudo code coding: Example

begin
numeric ' n num1, n num2, n sum'. (Variable)
Display 'enter first number'
Accept 'n num1'
Display 'second number'
Accept 'n num2'
n sum=n num1+n num2
Display' the sum is '+n sum..(+ concatenate operrator)
End


Q.1: Write  Pseudo code that accept temperature in Celsius. Convert it into Fahrenheit and then displays the result ?

c/5=(f-32)/9

begin
numeric ntemp,nres
display 'enter temp in celsius'
accept 'ntemp'
nres=(9/5*ntemp)+32
display 'the temp in Fahrenheit is'+nres'.
end


Pseudo code: Product of two numbers…...

begin
numeric 'nnum1,nnum2,nproduct'(variable)
display 'enter first number'
accept 'nnum1'
display 'enter second number'
accept 'nnum2'
nproduct= nnum1*nnum2
display 'the product ' *nproduct'
end



Begin
Character cname
Display'enter name'
Accept cname
Display'Hello+cname'
end


Which  on is largest?
begin
nummeric nnum1,nnum2,nnum3,nnum4,nnum5,ntemp
display 'enter five number'
accept nnum1,nnum2,nnum3,nnum4,nnum5
If nnum1>nnum2
begin
ntemp=nnum1
end
begin
ntemp=nnum2
end
if nnum3>ntemp
begin
ntemp=nnum3
end
else
begin
if ntemp<nnum4
begin
ntemp= nnum4
end
end
if nnum5>ntemp
begin
nnum5=ntemp
end
display'the largest number'+ntemp
end


Write a pseudocode to find out the percentage of a student in five subject and give him grade according to the following norms…
If %>= 90 Grade A
      >= 75              B
      >= 60              C
      =< 60              D

Begin
Numeric nnum1, nnum2, nnum3, nnum4,nnum5,nsum,npercentage,ntotal
Character, cname
Display'name of the student'
Accept'cname'
Display'enter number of five subject'
Accept 'nnum1,nnum2,nnum3,nnum4,nnum5.'
nsum=nnum1+nnum2+nnum3+nnum4+nnum5
npercentage=(nsum/ntotal)*100
IfNpercentage >=90
begin
Display cGarde_A
end
Else
begin
If Npercentage>= 75
end
Begin
Display cgrade_B
End
Else
begin
ifNpercentage>= 60
end
Begin
Display cgrade_c
end
Else
Begin
Npercentage=<60
Begin
Display cgrade_d
End
End


Begin
Numeric nmarks,ntotal,navg,nctr
Nmarks=0
Ntotal=0
Navg=0
Nctr=0
Repeat
Begin
Enter'display the number of a student'
Accept nmarks
Ntotal=ntotal+nmarks
Nctr=nctr+1
End
Untill(nctr==30)
Navg=ntotal/30
Display the the avg marks of student'+navg'
end

Developing Windows Azure and Web Services Lab @ 8 Ans 2

Luxury Drive is using an XML Web service that provides the details about the various models of the cars manufactured by the company. The Web service is used by the company's call center and the distributors. The call center employees use a client application developed in .NET to access the Web service. However, the distributors use various applications having different platfonns to access the Web service. The management at Luxury Drive wants their Web service to be such that it can accommodate features such as reliable messaging, transactions, and security in future. The management has conveyed the same to the developers. The developers know that they can implement all these features in the existing XML Web service. However, it would be difficult because each of these features is provided by different technologies and merging all these technologies is a time-consuming and complex task. Therefore, the developers decided to create the Web service by using WCF because WCF is the unification of all these technologies and provides all the required features. You. as a distributed application developer, have to create a WCF service that provides the details about the various models of the cars manufactured by the company.
Solution



To create the required WCF service, you need to perform the following tasks:
1. Attach the database in the Microsoft SQL Server Management Studio window.
2. Create a WCF service.
3. Verify the WCF service.
Task 1: Attaching the Database in the Microsoft SQL Server Management Studio Window
To attach the database in the Microsoft SQL Server Management Studio window, you need to perform the following steps:
1. Browse to the location where the Exercise 03.zip file is saved.
2. Extract the files.
3. Open SQL Server Management Studio as administrator. The Connect to Server dialog box is displayed.
4. Type .\sqlexpress in the Server name text box.
5. Select Windows Authentication in the Authentication drop-down list.
6. Click the Connect button. The Microsoft SQL Server Management Studio window is displayed.
7. Right-click the Databases node in the Object Explorer window, and then select the Attach option from the context menu. The Attach Databases dialog box is displayed.
8. Click the Add button.
9. Browse to the location where the Exercise 03.zip file is extracted.
10. Expand the Exercise 03 folder.
11. Expand the Database folder.
12. Select the LuxuryDrive.mdf file.
13. Click the OK button.
14. Click the OK button. The LuxuryDrive database is added in the Databases folder.

Task 2: Creating a WCF Service
To create a WCF Service, you need to perform the following steps:
1. Open Microsoft Visual Studio 2012.
2. Select File—New—Web Site. The New Web Site dialog box is displayed.
3. Ensure that the Installed—Templates nodes are expanded in the left pane.
4. Select the Visual C# node under the Templates node.
5. Select WCF Service from the list of templates displayed in the middle pane.
6. Select the File System option from the Web location drop-down list.
7. Select and replace the text in the text box next to the Web location drop-down list with D:\Exercises\Module 06\Exercise 03\CarDetailsWCF Service.
8. Click the OK button. The Service.cs file is displayed.
9. Type the highlighted portions of the following code snippet in the Service.cs file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Data;
using System.Data.SqlClient;
10. Remove the following code snippet from the Service class:
public string GetOata(int value)
{
return string.Format("You entered: (0)", value);
>
public CompositeType GetDataUsingOataContract(CompositeType composite)
{
if (composite «■ null)
{
throw new ArgumentNullException("composite");
}
if (composite.BoolValue)
{
composite.StringValue +- "Suffix";
>
return composite;
>
11. Type the highlighted portions of the following code snippet in the Service class:
public class Service : IService
{
public DataSet QueryCarModel(string model)
{ SqlConnection conObj = new SqlConnection(@"Data
Source:.\sqlexpress;database=LuxuryDrive;Integrated Securityrtrue;");
SqlDataAdapter daObj = new SqlDataAdapter("SELECT * FROM ModelNo = ," + model + ..., conObj)j
DataSet dsObj = new DataSetQ;
daObj.Fill(dsObj, "CarDetails");
return dsObj;
>
}
12. Ensure that the Solution Explorer window is opened.
13. Expand the App_Code node.
14. Double-click the I Service.cs file. The I Service.cs file is displayed.
15. Type the highlighted portion of the following code snippet in the IService.cs file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Data;
...................
...................
16. Remove the following code snippet from the iservice interface:
[OperationContract]
string GetData(int value);
[OperationContract]
CompositeType GetDatal)singDataContract(CompositeType composite);
// TODO: Add your service operations here
}
// Use a data contract as illustrated in the sample below to add composite types to service operations.
[OataContract]
public class CompositeType
{
bool boolValue = true; string stringValue = "Hello ";
[DataMember]
public bool BoolValue
{
get { return boolValue; } set { boolValue ■ value; }
}
[DataMember]
public string StringValue
{
get { return stringValue; } set { stringValue = value; >
>
17. Type the highlighted portions of the following code snippet in the iservice interface:
public interface IService
{
[OperationContract]
DataSet QueryCarModel(string model);
>
18. Select FILE— Save All to save the changes.
19. Press the F6 key.
Task 3: Verifying the WCF Service
To verify the WCF service, you need to perform the following steps:
1. Open a new window of Microsoft Visual Studio 2012.
2. Select FILE—Open—Web Site. The Open Web Site dialog box is displayed.
3. Ensure that File System is selected in the left pane of the Open Web Site dialog box.
4. Browse to the location where the Exercise 03.zip file is extracted.
5. Expand the Exercise 03 folder.
6. Select the QueryCarDetailsClientApp folder, which is provided to you by the faculty, from the Select the folder you want to open list box.
7. Click the Open button. The QueryCarDetailsClientApp.sin (2) - Microsoft Visual Studio window is displayed.
8. Switch to the CarDetailsWCF Service (1) - Microsoft Visual Studio window.
9. Ensure that the Solution Explorer window is opened.
10. Ensure that the CarDetailsWCF Service(1) node is expanded.
11. Right-click the Service.svc file, and then select Set As Start Page.
12. Press the F5 key. The Debugging Not Enabled dialog box is displayed.
13. Click the OK button. The WCF Test Client window is displayed.
14. Close the WCF Test Client window.
16.Copy the URL from the address bar. and then close the Internet Explorer window.
17.Switch to the QueryCarDetailsClientApp.sIn (2) - Microsoft Visual Studio window.
18.Select Website—Add Service Reference. The Add Service Reference dialog box is displayed. Paste the copied URL in the Address combo box, and then click the OK button.
19.Click the Make Writeable button, if the Edit of Read-Only File dialog box is displayed.
20.Ensure that the Solution Explorer window is opened.
21.Right-click the QueryCarDetailsPage.aspx file, and then select Set As Start Page.
22.Select FILE—Save All to save the changes. The Save File As dialog box is displayed.
23.Browse to the location where Exercise 03.zip file is extracted.
24.Double-click the Exercise 03 folder.
25.Click the Save button.
26.Press the F5 key.
27.Type M002 in the Enter a Model No text box. and then click the Show Details button. The details of the model M002 appear.
29. Close the Internet Explorer window.
30. Close the Microsoft Visual Studio 2012 windows.

HTML MT Solved


Explain the usage of the <IFRAME> tag in HTML. Also, discuss the various attributes of the <IFRAME> tag.

Ans .The HTML <IFRAME> tag is used to specify an inline frame. It allows you to divide a Web page into sections or frames. Each section can be used to display an individual Web page. Therefore, the <IFRAME> tag is used to embed an HTML Web page within another Web page. The embedded Web page is said to be contained within the other Web page, which is known as the containing page. The following attributes can be used with the <IFRAME> tag:

src: Is used to specify the location or the URL of the Web page to be embedded inside the frame.

name: Is used to assign a name to the frame.

seamless: Is a boolean attribute, which instructs the browser to display the frame as a part of the containing Web page. If this attribute is used, the frame is displayed without scroll bars and border.

srcdoc: Is used to specify an HTML code that defines the content to be displayed inside the frame.

height: Is used to set the height of the frame.

width: Is used to set the width of the frame.


What do you mean by loop constructs? Discuss the various loop constructs in JavaScript.Ans. Loop constructs are used to repeatedly execute one or more lines of code. In JavaScript, the following loop constructs can be used:


while 
do...while
for
The while  loop is used to repeatedly execute a block of statements till a condition evaluates to true. The while statement always checks the condition before executing the statements in the loop. The syntax for the while loop is:

while (expression)
{
statements;
}

The do...while loop construct is similar to the while loop construct. However, the statements within the do...while loop are executed before the condition is checked as compared to the while loop, where the statements within the block are executed after the condition is checked. Therefore, the statements within the do...while loop are executed at least once, in comparison to the while loop, where the statements in the block are not executed when the condition evaluates to false for the very first time. It has the following syntax:

do
{ Statements;
}
while(condition)

The for  loop allows the execution of a block of code depending on the result of the evaluation of the test condition. It has the following syntax:

for (initialize variable; test condition; step value)
{// code block
}


Write the code to retrieve the users' location on the click event of a button by using the getCurrentPosition() method. The location coordinates that are retrieved need to be displayed inside the <P></P> tag. 

Ans. <!DOCTYPE HTML>
<HTML>
<BODY>
<P ID="disp_location">Click here to know your location coordinates:</P>
<BUTTON onclick="getLocation()">Get Location</Button>
<SCRIPT>
var geo=document.getElementById("disp_location");
function getLocation()
  {
  if (navigator.geolocation)
    {
    navigator.geolocation.getCurrentPosition(getPosition);
    }
  else{geo.innerHTML="Geolocation is not supported by this browser.";}
  }
function getPosition(position)
  {
  geo.innerHTML="Latitude: " + position.coords.latitude +
  "<BR>Longitude: " + position.coords.longitude;
  }
</SCRIPT>
</BODY>
</HTML>

What is a function? How can you create a function in JavaScript?

Ans. A function is a self-contained block of statements that has a name and is defined to perform a specific task. A function can be defined once but can be executed repeatedly. Functions can either be built-in or user-defined.

In JavaScript, functions can be created by using the keyword, function, followed by the function name and the parentheses, ().A function can optionally accept a list of parameters. The parameters that a function accepts are provided in parentheses and separated by commas. The function can use the values passed in these parameters to perform certain operations. The following syntax is used to create functions:

function [functionName] (Variable1, Variable2)
{
//function statements
}

Write the JavaScript code to create a clock that updates every one second to display the current time inside a <DIV> element on the Web page.

Ans. <!DOCTYPE HTML>
<HTML>
<HEAD>
<SCxRIPT type="text/javascript">
function clockTime()
{
var todayDate=new Date();
var hrs=todayDate.getHours();
var mns=todayDate.getMinutes();
var scs=todayDate.getSeconds();
mns=check(mns);
scs=check(scs);
document.getElementById('displayTime').innerHTML=hrs+":"+mns+":"+scs;
t=setTimeout('clockTime()',1000);
}

function check(t)
{
if (t<10)
 {
 t="0" + t;
 }
return t;
}
</SCRIPT>
</HEAD>
<BODY onload="clockTime()">
<DIV ID="displayTime"></DIV>
</BODY>
</HTML>

Define canvas. Also, discuss how can you create a canvas and use it for drawing graphic objects in HTML.Ans. A canvas is an area on a Web page that acts as a container for embedding graphic objects. It allows dynamic rendering of bitmap images and 2D shapes by using JavaScript. To create a canvas and use it for drawing, you need to perform the following tasks:


1. Define the canvas
2. Access the canvas

A canvas is defined by using the <CANVAS> tag in the body section of the HTML document. Its important attributes are height, width, style, and ID. You can define a canvas by using the following code within the <BODY> tag:

<CANVAS ID="myCanvas" width="300" height="300" style="border:1px solid black">
</CANVAS>

To actually draw graphic objects on the canvas, you need to access the canvas in the JavaScript code. You can write the following code in the <BODY> tag to access the canvas that you have defined earlier:

<SCRIPT>
var c=document.getElementByID("myCanvas");
var ctx=c.getContext("2d");
</SCRIPT>

Write a code to create a table in HTML, as shown in the following figure.

Ans. <!DOCTYPE HTML><HTML>
<BODY>
<TABLE border = "1">
<THEAD>
<TR><TH colspan= "4">Sales Record</TH></TR>
<TR> <TH> Product ID </TH> <TH> Description</TH> <TH> Quantity</TH><TH> Price</TH></TR>
</THEAD>
<TFOOT>
<TR><TD colspan= "3"> Total price </TD> <TD>$12</TD></TR>
</TFOOT>
<TBODY>
<TR><TD>101</TD><TD>Notebook</TD><TD>50</TD><TD>$5</TD></TR>
<TR><TD>121</TD><TD>Pen</TD><TD>100</TD><TD>$7</TD></TR>
</TBODY>
</TABLE>
</BODY>
</HTML>

What do you understand by preloading the images associated with a Web page? How is preloading of images implemented in JavaScript?

Ans. Preloading images is a technique to load images in the browser cache before the script on the Web page is executed and the Web page is rendered in the browser window. This helps to avoid any delay in loading images from their respective locations, and then displaying these images on the Web page.

The Image object can be used to preload images in an application. To use the Image object, an instance of the Image object needs to be created and the actual images need to be attached to the Image object in the head section. It ensures that the images are loaded in memory before the body of the page gets loaded. The following syntax is used to create an instance of the Image object:

var Imagename= new Image([Width], [Height]);

After instantiating an image object, you need to associate the image with the Image object. For this, the src attribute of the Image object is used as shown in the following code:
  
   Imagename.src="ImageURL",

where, ImageURL is the URL of the image.

What is the use of the <FIELDSET> tag in HTML? Also, briefly discuss the tags and attributes associated with the <FIELDSET> tag.

Ans. The <FIELDSET> tag is used to combine and group related fields in a form. It creates a box around the selected fields.

The <LEGEND> tag is used along with the <FIELDSET> tag to define a caption for the fieldset. It is the simplest way of organizing form elements along with their description in such a way that it is easier for a user to understand.

The <FIELDSET> tag can have the following attributes:

disabled: The disabled attribute is used to indicate that a group of fields should be shown disabled when the page loads.
form: The form attribute is used to specify the name of one or more forms to which the <FIELDSET> tag belongs.
name: The name attribute is used to specify the name for the fieldset.

 Write the code to create a canvas of desired dimension on a Web page and then draw a circle inside it. In addition, you need to apply a radial gradient comprising any four colors on the circle drawn on the canvas.

Ans. <!DOCTYPE HTML>
<HTML>   <BODY>
<CANVAS ID="myCanvas" width="300" height="300" style="border:1px solid black">
</CANVAS>
<SCRIPT>
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var grad=ctx.createRadialGradient(75,50,5,90,60,100);
grad.addColorStop(0.2,"orange");
grad.addColorStop(0.4,"green");
grad.addColorStop(0.6,"yellow");
grad.addColorStop(0.8,"red");
ctx.fillStyle=grad;
ctx.beginPath();
ctx.arc(80, 90, 50, 0, Math.PI*2, false);
ctx.fill();
ctx.closePath();
</SCRIPT>
</BODY>
</HTML>