Unit 5 Part1
Unit 5 Part1
2. Unchecked Exceptions:
• The unchecked exceptions are just opposite to the checked
exceptions. The compiler will not check these exceptions at compile
time.
• The classes that inherit the RuntimeException are known as
unchecked exceptions. For example, ArithmeticException,
NullPointerException
Exception Handling Mechanism:
1. Java try...catch block
• The try-catch block is used to handle exceptions in Java. Here's the
syntax of try...catch block:
Try block:
• Here, we have placed the code that might generate an exception inside
the try block.
• Now when an exception occurs, the rest of the code inside the try block
is skipped.
• Every try block is followed by a catch block.
Catch block:
• When an exception occurs, it is caught by the catch block.
The catch block cannot be used without the try block.
• If none of the statements in the try block generates an exception,
the catch block is skipped.
Exception handling:
Example: Exception handling using try...catch
Note:
• It is a good practice to use the finally block. It is because it can
include important cleanup codes
Example of Java finally block
Here finally block will get executed all of the following cases:
1. If no exception
2. If there is exception in try block and handled by catch block
3. If there is exception in try block and not handled by catch block
throw in java exception:
• The throw keyword in Java is used to explicitly throw an exception from
a method or any block of code.
• We can throw either checked or unchecked exception. The throw
keyword is mainly used to throw custom exceptions.
• Syntax:
<script>
// JavaScript Code
</script>
Javascript Operators
Mathematical operators.
• i. Arithmetic Operators
• ii. Comparison Operators
• iii. Logical (or Relational) Operators
• iv. Assignment Operators
• v. Conditional (or ternary) Operators
comparison operators :
• = = (Equal)
• != (Not Equal),
• > (Greater than),
• < (Less than),
• >= (Greater than or Equal to),
• <= (Less than or Equal to)
Logical operator:
• AND, OR, NOT
Javascript Operators
Bitwise operator:
• = (Simple Assignment )
– Ex: C = A + B will assign the value of A + B into C
• += (Add and Assignment)
– Ex: C += A is equivalent to C = C + A
• −= (Subtract and Assignment)
– Ex: C -= A is equivalent to C = C - A
• *= (Multiply and Assignment)
– Ex: C *= A is equivalent to C = C * A
• /= (Divide and Assignment)
– Ex: C /= A is equivalent to C = C / A
• %= (Modules and Assignment)
– Ex: C %= A is equivalent to C = C % A
Javascript Operators example
JavaScript for loop
• The syntax of the for loop is:
Here,
• The initialExpression initializes and/or declares variables and executes only
once.
• The condition is evaluated.
– If the condition is false, the for loop is terminated.
– If the condition is true, the block of code inside of the for loop is
executed.
• The updateExpression updates the value of initialExpression when the
condition is true.
• The condition is evaluated again. This process continues until the condition
is false.
• Example:
loop statement in JS:
While loop:
• The syntax of the while loop is:
Here,
• A while loop evaluates the condition inside the parenthesis ().
• If the condition evaluates to true, the code inside the while loop is
executed.
• The condition is evaluated again.
• This process continues until the condition is false.
• When the condition evaluates to false, the loop stops.
Example:
loop statement in JS:
do while loop:
• The syntax of do...while loop is:
Here,
• The body of the loop is executed at first. Then the condition is
evaluated.
• If the condition evaluates to true, the body of the loop inside the do
statement is executed again.
• The condition is evaluated once again.
• If the condition evaluates to true, the body of the loop inside the do
statement is executed again.
• This process continues until the condition evaluates to false. Then the
loop stops
• Example
Eventsin JS:
• HTML events are "things" that happen to HTML elements.
• When JavaScript is used in HTML pages, JavaScript can "react" on these
events
• Here are some examples of HTML events:
– An HTML web page has finished loading
– An HTML input field was changed
– An HTML button was clicked
• Syntax :
• <element event="some JavaScript">
• Example :
• <button onclick="document.getElementById('demo').innerHTML =
Date()">The time is?</button>
• In the example above, the JavaScript code changes the content of the
element with id="demo".
Eventsin JS:
JavaScript Event Handlers
• Event handlers can be used to handle and verify user input, user actions,
and browser actions:
– Things that should be done every time a page loads
– Things that should be done when the page is closed
– Action that should be performed when a user clicks a button
– Content that should be verified when a user inputs data
Eventsin JS:
Objects and user defined functions
JavaScript Objects
• JS objects is again a variable which can contain many values.
• Suppose object car is having three features with values (Fiat, 500,
white), then such object will be created as follows:
const car = {type:"Fiat", model:"500", color:"white"};
Object Definition
1. You define (and create) a JavaScript object with an object literal
• Example :
• const person = {firstName:"John", lastName:"Doe", age:50,
eyeColor:"blue"};
2. Accessing Object Properties
• You can access object properties in two ways:
• i) objectName.propertyName;
• Ii) objectName["propertyName"];
Objects and user defined functions
Object Methods
• Objects can also have methods.
• Methods are actions that can be performed on objects.
• Methods are stored in properties as function definitions.
• Syntax:
• Accessspecifier objectname={
• methodname: function(){
• statement;
• }
• };
Objects and user defined functions
Object method example:
• In a function definition, this refers to the "owner" of the function.
• Example:
• const person = {
• firstName: "John",
• lastName : "Doe",
• fullName : function() {
• return this.firstName + " " + this.lastName;
• }
• };
Accessing Object Methods
• You access an object method with the following syntax:
• objectName.methodName();
• Example:
• name = person.fullName();
User defined function in JS:
User Defined functions
• A function is a set of statements that take inputs, do some specific
computation, and produces output. Basically, a function is a set of
statements that performs some tasks or does some computation and
then return the result to the user.
• Syntax:
– function functionName(Parameter1, Parameter2, ..)
– {
• Function body
– }
• Below are the rules for creating a function in JavaScript:
• Every function should begin with the keyword function followed by,
• A user defined function name which should be unique,
• A list of parameters enclosed within parenthesis and separated by
commas,
• A list of statement composing the body of the function enclosed within
curly braces {}.
User defined function in JS:
• Example:
• function calcAddition()
• {
• number1=3;
• number2=7;
• return number1 + number2;
• }
•
Function Parameters
• Parameters are additional information passed to a function.
• The parameters are passed to the function within parentheses after the
function name and separated by commas.
• A function in JavaScript can have any number of parameters and also at
the same time a function in JavaScript can not have a single parameter.
User defined function in JS:
Example:
• Function add(int a, int b){
• Sum=a+b;
• return sum;
• }
Return Statement:
• There are some situations when we want to return some values from a
function after performing some operations.
• In such cases, we can make use of the return statement in JavaScript.
This is an optional statement and most of the times the last statement in
a JavaScript function.
• Like in above example we have used return statement to return the
value of sum variable to calling statement.
Validation using Regular expression:
validation
• Form validation normally used to occur at the server, after the client had
entered all the necessary data and then pressed the Submit button. If
the data entered by a client was incorrect or was simply missing, the
server would have to send all the data back to the client and request
that the form be resubmitted with correct information. This was really a
lengthy process which used to put a lot of burden on the server.
• JavaScript provides a way to validate form's data on the client's
computer before sending it to the web server. Form validation generally
performs two functions.
• Basic Validation − First of all, the form must be checked to make sure all
the mandatory fields are filled in. It would require just a loop through
each field in the form and check for data.
• Data Format Validation − Secondly, the data that is entered must be
checked for correct form and value. Your code must include appropriate
logic to test correctness of data.
Validation using Regular expression:
• JavaScript is a scripting programming language that also helps in
validating the user’s information
• Form validation is validating the values which are entered by the end-
user during a form submission. For validating a form, Regular Expression
plays a vital role
• Assume a registration form that contains the basic details of the end-
users like Name, Phone number, Email id, and Address. When the user
enters the email id without the domain name and “@” symbol the form
turns out an error that says “domain name not included”.
• How this happens? This happens due to the Regular Expressions in
JavaScript.
Validation using Regular expression:
• To validate the emilid field following function need to consider regular
expression as shown in the code
Browser Object Method:
• The Browser Object Model (BOM) is used to interact with the browser.
• The browser object model (BOM) is a hierarchy of browser objects.
• All these objects are used to manipulate methods and properties associated
with the Web browser itself.
• window object
• screen object
• history object
• navigator object
• document object
Window Object:
• Window object support following methods:
• 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.
• All these method we can call with or without accessing an object also
• Means calling window.alert() is always equal to calling alert()
Window Object:
• Alert:
– It displays alert dialog box. It has message and ok button.
– It shows a message and waits for the user to press “OK”.
– Example: alert("Logged in successfully....");
• Prompt:
– A prompt box is often used if you want the user to input a value before
entering a page.
– User will have to click either "OK" or "Cancel" to proceed after entering an
input value.
– If the user clicks "OK" the box returns the input value. If the user clicks
"Cancel" the box returns null.
– Example: var a = prompt("Enter first name:");
• Conform: (mail sending comformation)
– This also provides two buttons "OK“ and "Cancel" to proceed.
– If the user clicks "OK", the box returns true. If the user clicks "Cancel", the
box returns false.
– Example: result = confirm(question);
document.write() in js
• The document.write() function is used to display dynamic content through
JavaScript.
• Syntax:
– document.write(exp1, exp2, exp3, ...)
• Example:
– document.write(“Hello students……");
– document.write(var);
– document.write("<h1>Hello students!!!</h1><p>Have a nice day!</p>");
– document.write(Date());
• Combination of text to be display and HTML element / expression:
– document.write(“text to be display”+</br>);
– document.write(“Addition=”+(5+6));
• document.write() with function:
– Using document.write() after an HTML document is fully loaded, will delete all
existinAll HTML elements will be overwritten and replaced with
the new, specified text
JavaScript screen object :
• holds information of browser screen.
• It can be used to display screen width, height, colorDepth, pixelDepth etc.
JavaScript history object:
• represents an array of URLs visited by the user. By using this object, you can load
previous, forward or any particular page.
• hisory object supports one property i.e. length and three method forword(), back(),
go().
JavaScript navigator object:
• is used for browser detection.
• It can be used to get browser information such as appName, appCodeName,
userAgent etc.
Popovers:
• The popover attribute defines an element as a popover element, meaning
that when it is invoked, it will be placed on top of the content, not interfere
with the position of other HTML elements.
• A popover element will be invisible until it is invoked by another element.
The other element must have a popovertarget attribute where the value
refers to the popover element's id.
• The popover element will be placed on top of all other content, and by
clicking the popovertarget element, the popover element will toggle
between showing and hiding:
Applies to
• The popover attribute is a Global Attribute, and can be used on any HTML
element, but the element must be editable.
Popovers example:
• Suppose you have following html element on webpage. Popover effects as follows;
• When you click on button that hello word box will displayed on screen. On second
click the same block will get disappear
The Window Object
The Window Object
• The window object is supported by all browsers. It represents the
browser's window.
• All global JavaScript objects, functions, and variables automatically
become members of the window object.
• Global variables are properties of the window object.
• Global functions are methods of the window object.
• Even the document object (of the HTML DOM) is a property of the
window object:
• window.document.getElementById("header");
• is the same as:
• document.getElementById("header");
The Window Object
Windows size:
• Two properties can be used to determine the size of the browser
window.
• Both properties return the sizes in pixels:
• window.innerHeight - the inner height of the browser window (in pixels)
• window.innerWidth - the inner width of the browser window (in pixels)
• Example:
• let w = window.innerWidth;
• let h = window.innerHeight;
• Other Window Methods
• window.open() - open a new window
• window.close() - close the current window
• window.moveTo() - move the current window
• window.resizeTo() - resize the current window
Window Object:
• Window object support following methods:
• 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.
• All these method we can call with or without accessing an object also
• Means calling window.alert() is always equal to calling alert()
Window Object:
• Alert:
– It displays alert dialog box. It has message and ok button.
– It shows a message and waits for the user to press “OK”.
– Example: alert("Logged in successfully....");
• Prompt:
– A prompt box is often used if you want the user to input a value before
entering a page.
– User will have to click either "OK" or "Cancel" to proceed after entering an
input value.
– If the user clicks "OK" the box returns the input value. If the user clicks
"Cancel" the box returns null.
– Example: var a = prompt("Enter first name:");
• Conform: (mail sending comformation)
– This also provides two buttons "OK“ and "Cancel" to proceed.
– If the user clicks "OK", the box returns true. If the user clicks "Cancel", the
box returns false.
– Example: result = confirm(question);
Java Applet:
Introduction:
• An applet is a Java program that can be embedded into a web page. It
runs inside the web browser and works at client side.
• An applet is embedded in an HTML page using the APPLET or OBJECT tag
and hosted on a web server.
• Applets are used to make the website more dynamic and entertaining.
Important points :
• All applets are sub-classes (either directly or indirectly) of
java.applet.Applet class.
• Applets are not stand-alone programs. Instead, they run within either a
web browser or an applet viewer. JDK provides a standard applet viewer
tool called applet viewer.
• In general, execution of an applet does not begin at main() method.
• Output of an applet window is not performed by System.out.println().
Rather it is handled with various AWT methods, such as drawString().
Java Applet contin…
Life style of applet:
• public void init(): is used to initialized the Applet.
It is invoked only once.
• public void start(): is invoked after the init()
method or browser is maximized. It is used to start the
Applet.
• public void stop(): is used to stop the Applet.
It is invoked when Applet is stop or browser is minimized.
• public void destroy(): is used to destroy the Applet.
It is invoked only once.
• public void paint(Graphics g): is used to paint the Applet. It provides
Graphics class object that can be used for drawing oval, rectangle, arc
etc.
Java Applet contin…
Applet program:
Code: output:
There are two standard ways in which you can run an applet :
• Executing the applet within a Java-compatible web browser.
• Using an applet viewer, such as the standard tool, applet-viewer.
Java Applet contin…
1. Executing the applet within a Java-compatible web browser.
• To execute an applet in a web browser we have to write a short HTML
text file that contains a tag that loads the applet.
• We can use APPLET or OBJECT tag for this purpose. Using APPLET, here is
the HTML file that executes HelloWorld :
When you will execute this html file output in browser will get displayed
Java Applet contin…
2. Using an applet viewer, such as the standard tool, applet-viewer.
• This is the easiest way to run an applet. To execute HelloWorld with an
applet viewer, you may also execute the HTML file shown earlier. For
example, if the preceding HTML file is saved with
• RunHelloWorld.html, then the following command line will run
HelloWorld :
appletviewer RunHelloWorld.html
• As sson as this command get executed you will get output as follows.