Web Programming (QB)
Web Programming (QB)
list of common string manipulation functions from the Java String class:
1. charAt(int index)
2. concat(String str)
3. contains(CharSequence s)
4. equals(Object obj)
5. indexOf(String str)
Returns the index within this string of the first occurrence of the specified substring.
Example: "Hello".indexOf("l") returns 2.
6. length()
Replaces each substring of this string that matches the given regular expression with the
given replacement.
Example: "Hello123".replaceAll("[0-9]", "") returns "Hello".
9. substring(int beginIndex)
Returns a new string that is a substring starting from the specified index.
Example: "Hello".substring(2) returns "llo".
10. toLowerCase()
11. toUpperCase()
12. isEmpty()
2. Does Java support multi way selection statement? Justify your answer.
Yes, Java supports multi-way selection statements through the switch statement.
The switch statement is designed to handle multiple possible execution paths based on
the value of an expression. It provides a more concise and readable alternative to using a
series of if-else statements when dealing with multiple conditions.
the basic syntax of a switch statement in Java:
switch (expression) {
case value1:
// code to be executed if expression is equal to value1
break;
case value2:
// code to be executed if expression is equal to value2
break;
// additional cases as needed
default:
// code to be executed if none of the cases match the expression
}
switch (dayOfWeek) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("Invalid day");
}
}
}
In this example, the switch statement is used to determine the day of the week based on
the value of the dayOfWeek variable. The program prints the corresponding day to the
console. The default case is optional and is executed if none of the other cases match the
value of the expression.
The switch statement is particularly useful when there are multiple possible values for a
variable, and you want to execute different code based on those values. It enhances code
readability and can be more efficient than a series of nested if-else statements in certain
situations.
The switch statement in Java is designed for scenarios where there are multiple possible
execution paths based on the value of a single expression. It provides a clean and
structured way to handle such situations, making the code more readable and easier to
maintain.
One notable feature of the switch statement is its ability to handle different cases
efficiently. When the expression’s value matches a case, the corresponding block of code
is executed, and control exits the switch statement. The break statement is crucial for
preventing “fall-through” behavior, where subsequent cases would be executed even if
their conditions don’t match.
________________________________________________________________________
3. What is an exception? How are exceptions handled in Java programming? Explain with
suitable program.
An exception is an error that occurs during a program's execution, disrupting its normal
flow. Java's exception handling mechanism allows programs to respond to these errors
without crashing.
An exception in Java is an unexpected event or error that occurs during the execution of
a program, disrupting the normal flow of instructions. Exceptions are typically caused by
errors like invalid user input, resource access issues (e.g., files not found), or logical
errors (e.g., division by zero).
Java provides a robust mechanism for handling such exceptions, preventing the program
from terminating unexpectedly. Exceptions can be checked, unchecked, or errors, and
they are represented as objects of the Throwable class or its subclasses like Exception and
RuntimeException.
try block: The statement int result = a / b; is placed inside the try block because division
by zero may occur, which triggers an ArithmeticException.
catch block: The catch block catches the ArithmeticException when the division by zero
happens and prints an appropriate message ("Exception caught: Division by zero is not
allowed.").
finally block: Regardless of whether an exception occurs, the finally block is executed,
ensuring that any necessary cleanup code (like closing resources) is performed. In this
case, it prints "Execution completed, resources closed.".
Normal Program Flow: After handling the exception, the program continues with its
normal flow and prints "Program continues...".
Output
Exception caught: Division by zero is not allowed.
Execution completed, resources closed.
Program continues...
________________________________________________________________________
4. Explain various operators and data types available in java script with examples
JavaScript operators are symbols that are used to perform operations on operands.
For example:
var sum=10+20;
Arithmetic Operators
Comparison (Relational) Operators
Bitwise Operators
Logical Operators
Assignment Operators
Special Operators
Arithmetic Operators
These are used for basic mathematical operations.
let a = 5 + 3; // 8 addition
let b = 10 - 2; // 8 subtraction
let c = 4 * 2; // 8 multiplication
let d = 16 / 2; // 8 division
let e = 10 % 3; // 1 modulus
let f = 5; increment
f++; // 6
let g = 5; decrement
g--; // 4
Assignment Operators
These are used to assign values to variables.
= : Assigns the right-hand value to the left-hand variable
let x = 10;
x += 5; // x = x + 5; x is now 15
Comparison Operators
These compare two values and return true or false.
== : Equal to
5 == '5'; // true (type coercion happens)
Logical Operators
|| : Logical OR
(5 > 2) || (6 < 3); // true (one condition is true)
! : Logical NOT
!(5 > 2); // false (negates the result)
Bitwise Operators
These perform operations on the binary representations of numbers.
& : Bitwise AND
| : Bitwise OR
^ : Bitwise XOR
~ : Bitwise NOT
<< : Left shift
>> : Right shift
JavaScript provides different data types to hold different types of values. There are two
types of data types in JavaScript.
let person = {
firstName: "John",
lastName: "Doe",
age: 30
};
Array: Special kind of object used to store multiple values in a single variable.
let colors = ["red", "green", "blue"];
Function: JavaScript functions are objects that can be assigned to variables or passed as
arguments.
function greet() {
return "Hello!";
}
Example
let num = 10; // Number
let name = "Alice"; // String
let isActive = true; // Boolean
let colors = ["red", "green", "blue"]; // Array
let person = { name: "Bob", age: 25 }; // Object
______________________________________________________________________
5. JavaScript is referred to as Object based programming language’. Justify with an example
Object Literal: The student object is created directly using object literals. It contains
properties like name, age, and major, as well as a method getDetails() that provides
details about the student.
Dynamic Nature: JavaScript objects can have properties and methods dynamically
added, modified, or deleted during runtime, which demonstrates its object-based
flexibility.
________________________________________________________________________
JDBC Driver is a software component that enables java application to interact with the
database.
There are 4 types of JDBC drivers:
Native-API driver
The Native API driver uses the client-side libraries of the database. The driver converts
JDBC method calls into native calls of the database API. It is not written entirely in java.
Advantage:
performance upgraded than JDBC-ODBC bridge driver.
Disadvantage:
The Native driver needs to be installed on the each client machine.
The Vendor client library needs to be installed on client machine.
Thin driver
The thin driver converts JDBC calls directly into the vendor-specific database protocol.
That is why it is known as thin driver. It is fully written in Java language.
Advantage:
Better performance than all other drivers.
No software is required at client side or server side.
Disadvantage:
Drivers depend on the Database.
________________________________________________________________________
7. Discuss in detail about java file handling with an example.
In Java, a File is an abstract data type. A named location used to store related information
is known as a File. There are several File Operations like creating a new File, getting
information about File, writing into a File, reading from a File and deleting a File.
Stream
A series of data is referred to as a stream. In Java, Stream is classified into two types,
i.e., Byte Stream and Character Stream
Byte Stream
Byte Stream is mainly involved with byte data. A file handling process with a byte
stream is a process in which an input is provided and executed with the byte data.
Character Stream
Character Stream is mainly involved with character data. A file handling process with a
character stream is a process in which an input is provided and executed with the
character data.
File Operations
We can perform the following operation on a file:
Create a File
Get File Information
Write to a File
Read from a File
Delete a File
Example Program:
To create a file, we use the File class. The method createNewFile() creates a new file if it
doesn't already exist.
import java.io.File;
import java.io.IOException;
An HTML webpage consists of several elements that form the structure and content of a
website. HTML (HyperText Markup Language) uses tags to structure text, images, and
other multimedia components. The basic structure of an HTML webpage includes the
following main sections:
<!DOCTYPE html>: Declaration that defines the document type and version of
HTML.
<html>: The root element that wraps all the content on the page.
<head>: Contains meta-information about the document, like its title, linked CSS
files, JavaScript files, and metadata.
<title>: Defines the title of the webpage, shown in the browser tab.
<body>: Contains the visible content of the webpage, including headings,
paragraphs, images, links, etc.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>My Webpage</title>
<link rel="stylesheet" href="styles.css"> <!-- Link to external CSS file -->
</head>
<body>
<!-- Header section -->
<header>
<h1>Welcome to My Webpage</h1>
</header>
<section>
<h2>Our Services</h2>
<p>We offer web development, design, and SEO services.</p>
</section>
</main>
!DOCTYPE html>:
This is the document type declaration that tells the browser the version of HTML (HTML5 in
this case).
<html lang="en">:
The <html> element is the root of the HTML document. It wraps all the content. The lang
attribute defines the language of the document as English.
<head>:
The <head> element contains metadata about the webpage, such as the title (<title>) of the
webpage, meta tags for character encoding and responsiveness, and links to external resources
like CSS files or JavaScript files
.
<title>:
This defines the title of the webpage, which appears in the browser’s tab.<body>: Contains
visible elements like headings, paragraphs, and links.
<body>:
This element contains the main content of the webpage that users see, including text, images,
headings, links, and more.
<header>:
The header section typically contains the main title or logo of the page, like the page heading
(<h1>).
<meta charset="UTF-8">:
Specifies the character encoding of the webpage, ensuring that it supports most languages and
characters.
<meta name="viewport" content="width=device-width, initial-scale=1.0">:
Ensures the webpage is responsive and scales correctly on different devices, like mobile phones
and tablets.
___________________________________________________________________________
The process of creating and embedding scripts in a web page is known as web-
scripting.
A script or a computer-script is a list of commands that are embedded in a web-page
normally and are interpreted and executed by a certain program or scripting engine.
Scripts may be written for a variety of purposes such as for automating processes on
a local-computer or to generate web pages.
The programming languages in which scripts are written are called scripting
language, there are many scripting languages available today.
Common scripting languages are VBScript, JavaScript, ASP, PHP, PERL, JSP etc.
Types of Script :
Scripts are broadly of following two type :
Client-Side Scripts :
1. Client-side scripting is responsible for interaction within a web page. The client-
side scripts are firstly downloaded at the client-end and then interpreted and
executed by the browser (default browser of the system).
2. The client-side scripting is browser-dependent. i.e., the client-side browser must be
scripting enables in order to run scripts
3. Client-side scripting is used when the client-side interaction is used. Some example
uses of client-side scripting may be :
To get the data from user’s screen or browser.
For playing online games.
Customizing the display of page in browser without reloading or
reopening the page.
4. Here are some popular client-side scripting languages VBScript, JavaScript,
Hypertext Processor(PHP).
Server-Side Scripts :
1. Server-side scripting is responsible for the completion or carrying out a task at the
server-end and then sending the result to the client-end.
2. In server-side script, it doesn’t matter which browser is being used at client-end,
because the server does all the work.
3. Server-side scripting is mainly used when the information is sent to a server and to
be processed at the server-end. Some sample uses of server-scripting can be :
Password Protection.
Browser Customization (sending information as per the requirements of
client-end browser)
Form Processing
Building/Creating and displaying pages created from a database.
Dynamically editing changing or adding content to a web-page.
4. Here are some popular server-side scripting languages PHP, Perl, ASP (Active
Server Pages), JSP ( Java Server Pages).
10. List and explain the benefits of OOPS and Describe the features of Java with an example
code
Encapsulation:
Definition: Bundling the data (attributes) and methods (functions) that operate on the data
into a single unit, or class.
Benefit: Protects the internal state of the object from unintended interference and misuse,
providing a controlled interface.
Abstraction:
Definition: Hiding the complex implementation details and showing only the essential
features of the object.
Benefit: Simplifies code usage and understanding by focusing on what an object does
instead of how it does it.
Inheritance:
Definition: The mechanism by which one class (subclass) can inherit properties and
behaviors (methods) from another class (superclass).
Benefit: Promotes code reusability and establishes a hierarchical relationship between
classes.
Polymorphism:
Definition: The ability of different classes to be treated as instances of the same class
through a common interface; methods can perform different tasks based on the object that
invokes them.
Benefit: Increases flexibility and allows for easier maintenance and expansion of code.
Reusability:
Definition: Classes and objects can be reused in different programs or in multiple
instances of a program.
Benefit: Reduces redundancy and promotes the development of more modular and
maintainable code.
Features of Java
Java is a popular object-oriented programming language with several key features:
Simple: Java is easy to learn and use due to its clear syntax, which is similar to C and C+
+.
Object-Oriented: Java follows the OOP paradigm, enabling modular and reusable code
through encapsulation, inheritance, and polymorphism.
Secure: Java provides a secure environment for developing and running applications
through its runtime environment and various security features.
Rich Standard Library: Java has a comprehensive set of standard libraries (APIs) for
networking, I/O operations, data structures, and GUI development.
Example code:
// Base class
class Car {
// Encapsulation: private fields
private String model;
private String color;
// Constructor
public Car(String model, String color) {
this.model = model;
this.color = color;
}
// Constructor
public ElectricCar(String model, String color, int batteryCapacity) {
super(model, color); // Call the constructor of the superclass
this.batteryCapacity = batteryCapacity;
}
// Constructor
public SportsCar(String model, String color, int topSpeed) {
super(model, color); // Call the constructor of the superclass
this.topSpeed = topSpeed;
}
Output:
11. How does Java’s multithreading capability enable you to write more efficient programs?
Explain.
Java's multithreading capability allows developers to create applications that can perform
multiple tasks concurrently. This leads to more efficient programs in several ways:
Output:
Counting: 1
Letter: A
Counting: 2
Letter: B
Counting: 3
Counting: 4
Letter: C
Counting: 5
Letter: D
Letter: E
________________________________________________________________________
12. Explain how basic tables and nested tables are created using HTML
HTML table tag is used to display data in tabular form (row * column). There can be
many columns in a row.
We can create a table to display data in tabular form, using <table> element, with the help
of <tr> , <td>, and <th> elements.
In Each table, table row is defined by <tr> tag, table header is defined by <th>, and table
data is defined by <td> tags.
A basic table consists of rows and columns to display data in a grid format. The main
elements used to create a basic table include:
Nested Tables
A nested table is a table that is placed within another table. This allows for more complex
data representation.
Example code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Nested Table Example</title>
<style>
table {
width: 50%;
border-collapse: collapse;
margin: 20px 0;
}
th, td {
border: 1px solid black;
padding: 10px;
text-align: left;
}
th {
background-color: #f2f2f2;
}
</style>
</head>
<body>
</body>
</html>
Output
1. Global Scope
Variables declared outside of any function or block are said to have global scope.
These variables can be accessed from anywhere in the code, including inside functions.
function showGlobalVar() {
console.log(globalVar); // Accessible here
}
2. Function Scope
Variables declared inside a function are said to have function scope.
These variables are only accessible within that function and cannot be accessed from
outside.
Example:
function myFunction() {
let functionScopedVar = "I am a function-scoped variable";
console.log(functionScopedVar); // Accessible here
}
3. Block Scope
Variables declared with let and const within a block (denoted by curly braces {}) have
block scope.
These variables can only be accessed within that specific block and are not visible outside
of it.
if (true) {
let blockScopedVar = "I am a block-scoped variable";
console.log(blockScopedVar); // Accessible here
}
4.Lexical Scope
JavaScript also has lexical scoping, meaning that a function's scope is determined by its
location within the nested function blocks.
Inner functions have access to variables declared in their outer (enclosing) functions.
function outerFunction() {
let outerVar = "I am an outer variable";
function innerFunction() {
console.log(outerVar); // Accessible here
}
outerFunction();
________________________________________________________________________
14. Can inheritance be applied between interfaces? Justify your answer.
Yes, inheritance can be applied between interfaces in Java. This is achieved through a
mechanism called interface inheritance, which allows one interface to inherit the
abstract methods of another interface.
Interface Inheritance
Definition:
An interface in Java is a reference type that can contain only constants, method
signatures, default methods, static methods, and nested types. It cannot contain instance
fields or constructors.
When one interface inherits another, it can extend the behavior of the existing interface
by adding more abstract methods.
Syntax:
An interface can extend one or more other interfaces using the extends keyword.
Example:
// Parent interface
interface Animal {
void eat(); // Abstract method
}
@Override
public void play() {
System.out.println("Dog is playing.");
}
}
Output:
Dog is eating.
Dog is playing.
15. Write a JDBC program to update the amount balance in an account after every
withdrawal. Assume the necessary database table.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;
Output:
Enter account ID: 1
Enter amount to withdraw: 150.00
Withdrawal successful. New balance: 350.00
________________________________________________________________________
16. Discuss the use of frames in creation of HTML document
Frames in JavaScript typically refer to the concept of using HTML framesets to divide a
web page into multiple frames, each containing a separate HTML document. However,
it's essential to note that the use of framesets has become outdated, and the modern
approach is to use alternative techniques such as iframes or to design single-page
applications using JavaScript frameworks.
1. HTML Framesets:
In the traditional approach, you could use HTML framesets to create a page with multiple
frames. Framesets have been deprecated in HTML5, and their use is generally
discouraged due to various usability and accessibility issues. However, for historical
context, here's a simple example:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Frameset Example</title>
</head>
<frameset cols="50%,50%">
<frame src="frame1.html" name="frame1">
<frame src="frame2.html" name="frame2">
</frameset>
</html>
Using iframes:
Instead of framesets, you can use inline frames (<iframe>) to embed documents within a
page. iframes are more flexible and offer better control over content isolation.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Iframe Example</title>
</head>
<body>
</body>
</html>
Remember, manipulating frames directly using JavaScript might lead to security issues,
and it's often better to design your application using modern techniques like AJAX,
single-page applications (SPAs), or other frameworks/libraries for a more seamless user
experience.
_______________________________________________________________________
When html document is loaded in the browser, it becomes a document object. It is the
root element that represents the html document. It has properties and methods. By the
help of document object, we can add dynamic content to our web page.
window.document
or
document
Method Description
In this example, we are going to get the value of input text by user. Here, we are using
document.form1.name.value to get the value of name field.
Here, document is the root element that represents the html document.
value is the property, that returns the value of the input text.
Example:
<script type="text/javascript">
function printvalue(){
var name=document.form1.name.value;
alert("Welcome: "+name);
}
</script>
<form name="form1">
Enter Name:<input type="text" name="name"/>
<input type="button" onclick="printvalue()" value="print name"/>
</form>
Output:
________________________________________________________________________
18. How to insert a java script code while deploying a web application? Explain.
nserting JavaScript code into a web application can be done in several ways depending on
your project structure and requirements. Below are the common methods for including
JavaScript code in a web application during deployment:
1. Inline JavaScript
You can directly include JavaScript code within your HTML files using the <script> tag.
This method is often used for small scripts.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Inline JavaScript Example</title>
</head>
<body>
<h1>Hello World</h1>
<script>
alert('This is an inline JavaScript alert!');
</script>
</body>
</html>
Example:
JavaScript File (script.js):
// script.js
function showAlert() {
alert('This alert is from an external JavaScript file!');
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>External JavaScript Example</title>
<script src="script.js" defer></script>
</head>
<body>
<h1>Hello World</h1>
<button onclick="showAlert()">Show Alert</button>
</body>
</html>