Servlet example eclipse – How to Create Hello World Servlet Example using Eclipse IDE with Tomcat 7? | Servlet Hello World Example in Eclipse IDE with Tomcat

How to Create Hello World Servlet Example using Eclipse IDE with Tomcat 7

Servlet example eclipse: This tutorial will give you insight into how to run a servlet class that prints the “Hello World” String in the Browser. Here we are going to use the Eclipse IDE to develop code and will run the code in Tomcat Webserver. Creating Servlet in IDE Environment will save you from doing a lot of work. We have outlined the steps to be done in order to create a Hello World Servlet Example using Eclipse IDE in detail.

Tomcat Servlet using Eclipse IDE

For creating a Hello World Servlet Example using eclipse IDE with tomcat 7, you just need two things:

i) Download and install Eclipse IDE for Java EE developers.

Download Eclipse IDE: eclipse ide for java ee developer

ii) Download and install the Apache Tomcat server

Download Tomcat Server:
After download and install Eclipse IDE for Java EE developer and Tomcat Server, you will be able to create a Hello World Servlet Example using Eclipse IDE.

Do Refer:

1. Create a Dynamic Web Project

To create a Dynamic web project open eclipse ide → Go to menu → New → Dynamic web project.

How to create Hello World Servlet example using eclipse IDE with Tomcat 7 1

Write your project name and click on next.

How to create Hello World Servlet example using eclipse IDE with Tomcat 7 2

Click on the next button

How to create Hello World Servlet example using eclipse IDE with Tomcat 7 3

check on generate web.xml and click on the finish button.

How to create Hello World Servlet example using eclipse IDE with Tomcat 7 4

Once you click on the finish button, your Eclipse IDE will automatically create a dynamic web project as follows

How to create Hello World Servlet example using eclipse IDE with Tomcat 7 5

2. Create a Servlet Class

After creating a dynamic web project the next step is to create a servlet class. right-click on your project → New → Servlet

How to create Hello World Servlet example using eclipse IDE with Tomcat 7 6

Write the package name in the java package field and class name in the class name field and then click on next.

How to create Hello World Servlet example using eclipse IDE with Tomcat 7 7

You can mention the URL mapping in the following screen(web.xml) and click on next.

How to create Hello World Servlet example using eclipse IDE with Tomcat 7 8

Click on the finish button.

How to create Hello World Servlet example using eclipse IDE with Tomcat 7 9

On Clicking the finish button, your Eclipse IDE will generate a servlet class depending on the configuration provided in earlier steps as under.

How to create Hello World Servlet example using eclipse IDE with Tomcat 7 10

3. Write your Custom Code

Write down your code in doGet() method and call to setContentType() establishes the MIME types of the HTTP response. In this program,the MIME type is text/html.Next the getWriter() method obtains a PrintWriter. Later use println() to write some HTML code as HTTP response.

How to create Hello World Servlet example using eclipse IDE with Tomcat 7 11

4. Run your Servlet Code

In Order to run your Servlet code right-click on your project → Run As → 1 Run on Server.

How to create Hello World Servlet example using eclipse IDE with Tomcat 7 12

Choose the existing Tomcat Server and then Click on the finish button.

How to create Hello World Servlet example using eclipse IDE with Tomcat 7 13

5. The Output on Browser

Your Eclipse IDE will generate output on your own browser and print “HELLO WORLD” on the browser.

How to create Hello World Servlet example using eclipse IDE with Tomcat 7 14

Time complexity interview questions – Python Interview Questions on Algorithm Analysis and Big-O

Time complexity interview questions: We have compiled most frequently asked Python Interview Questions which will help you with different expertise levels.

Python Interview Questions on Algorithm Analysis and Big-O

Algorithm

Big o python: An algorithm is a procedure or set of instructions that are carried out in order to solve a problem. Coding demands procedural knowledge which is expressed in the form of algorithms. An algorithm provides a recipe or a roadmap or a simple sequence of instructions that are required to accomplish a particular programming task. So, for things as simple as adding two numbers or as complex as designing a banking program, everything requires a systematic approach. It is important to create a roadmap that makes sense before going ahead with the coding part. For simple programs, it is easy to create algorithms through logical thinking. There are also some famous algorithms that can be used for complex problem solving and hence are frequently used for coding.

Question 1.
What are the steps involved in writing an algorithm?
Answer:
There are three main steps involved in writing an algorithm:

1. Data Input

  • Formulate the problem and decide what data types will be the input.

2. Data Processing

  • Decide what computation will be carried off to get the desired result.
  • Also identify the decision points, conditions under which various functions will operate.

3. Results Output

  • One should know the expected results so that they can be verified by the actual results.

Question 2.
What are the characteristics of the Algorithm?
Answer:
An algorithm has the following five characteristics:

  1. Precision: It clearly defines one single starting point and one or more well-defined ending points.
  2. Effectiveness: It is composed of effective primitives that are understood by the person or machine using it.
  3. Input/Output Specified: The algorithm must receive input and it must also produce an output.
  4. Finiteness: An algorithm stops after the execution of a finite number of steps.
  5. Uniqueness: In an algorithm, the result of every step is uniquely defined and its value depends only on the input provided and the output generated by the previous steps.

Question 3.
What is the meaning of Problem solving?
Answer:
Problem-solving is a logical process in which a problem is first broken down into smaller parts that can be solved step by step to get the desired solution.

Question 4.
What would you call an algorithm that puts element lists in a certain order?
Answer:
An algorithm that puts elements of a list in a certain order is called a sorting algorithm. It uncovers a structure by sorting the input. Sorting is often required for optimizing the efficiency of other algorithms. The output of a sorting algorithm is in non-decreasing order where no element is smaller than the original element of the input and the output reorders but retains all the elements of the input which is generally in array form.
Some very commonly known sorting algorithms are as follows:

1. Simple sorts:
a. Insertion sort
b. Selection sort

2. Efficient Sorts:
a. Merge sort
b. Heap sort
c. Quick sort
d. Shell sort

3. Bubble sort

4. Distribution sort
a. Counting sort
b. Bucket sort
c. Radix sort

Question 5.
What type of algorithm calls itself with smaller or simpler input values?
Answer:
A recursive algorithm calls itself with smaller input values. It is used if a problem can be solved by using its own smaller versions.

Question 6.
What is the purpose of the divide and conquer algorithm? Where is it used?
Answer:
As the name suggests the divide and conquers algorithm divides the problem into smaller parts. These smaller parts are solved and the solutions obtained are used to solve the original problem. It is used in Binary search, Merge sort, quick sort to name a few.

Question 7.
What is dynamic programming?
Answer:
In a dynamic problem, an optimization problem is broken down into much simpler sub-problems, each sub-problem is solved only once and the result is stored. For example, Fibonacci Sequence (Explained in Chapter on Recursion).

Big-O Notation

Big-0 notation helps you analyze how an algorithm would perform if the data involved in the process increases or in simple words it is a simplified analysis of how efficient an algorithm can be.

Since algorithms are an essential part of software programming it is important for us to have some idea about how long an algorithm would take to run, only then can we compare two algorithms and a good developer would always consider time complexity while planning the coding process.

It helps in identifying how long an algorithm takes to run.

Big-O

(1) Gives us the algorithm complexity in terms of input size n.
(2) It considers only the steps involved in the algorithm.
(3) Big-O analysis can be used to analyze both time and space.

An algorithm’s efficiency can be measured in terms of the best-average or worst case but Big-O notation goes with the worst case scenario.
It is possible to perform a task in different ways which means that there can be different algorithms for the same task having different complexity and scalability.
Now, suppose there are two functions:

Constant Complexity [0(1)]

A task that is constant will never experience variation during runtime, irrespective of the input value. For Example:
>>> x = 5 + 7
>>> x
12
>>>
The statement x = 5+7 does not depend on the input size of data in any way. This is known as 0(l)(big oh of 1).
Example:
Suppose, there are sequence of steps all of constant time as shown in the following code:
>>> a= (4-6) + 9
>>> b = (5 * 8) +8
>>> print (a * b)
336
>>>
Now let’s compute the Big-0 for these steps:
Total time = O(1)+O(1)+O(1)
= 3O(1)
While computing Big – O we ignore constants because once the data size increases, the value of constant does not matter.
Hence the Big-0 would be 0(1).

Linear complexity: [O(n)]

In the case of linear complexity, the time taken depends on the value of the input provided.
Suppose you want to print a table of 5. Have a look at the following code:
>>> for i in range(0,n):
print (“\n 5 x “,i,”=”,5*i)
The number of lines to be printed depends on ‘n’. For n =10, only ten lines will be printed but for n= 1000, the for loop will take more time to execute.
The print statement is O(1).
So, the block of code is n*O(l) which is 0(n).
Consider following lines of code:
>>>j = 0                               ————(1)
>>> for i in range(0,n) :        ————(2)
print(“\n 5 x “,i,”=”,5*i)
(1) is O(1)
(2) block is O(n)
Total time = O(l)+O(n)

We can drop O(1) because it is a lower order term and as the value of n becomes large (1) will not matter and the runtime actually depends on the for a loop.
Hence the Big-0 for the code mentioned above is O(n).

Quadratic Complexity: [O(n2)]

As the name indicates quadratic complexity, the time taken depends on the square of the input value. This can be the case with nested loops. Look at the following code:

>>> for i in range (0,n):
for j in range(0,n):
print(“I am in “, j,” loop of i = “, i,”.”)

In this piece of code, the print statement is executed n2 times.

Logarithmic Complexity

Logarithmic complexity indicates that in the worst case the algorithm will have to perform log(n) steps. To understand this, let’s first understand the concept of the logarithm.

Logarithms are nothing but the inverse of exponentiation.

Now let’s take term 23. Here 2 is the base and 3 is the exponent. We, therefore, say that base 2 logs of 8 (log2 8) = 3. Same way if then base 105 = 100000 then base 10 log of 100000 (log10 of 100000) = 5.

Since the computer works with binary numbers, therefore in programming and Big O we generally work with base 2 logs.

Have a look at the following observation:

1. 20 = 1, log2 1 = 0
2. 21 = 2, log2 2 = 1,
3. 22 = 4, log2 4 = 2,
4. 23 = 8, log2 8 = 3,
5. 24 = 16,log2 16 = 4,
This means that if n =1, the number of steps = 1.
If n = 4, the number of steps will be 2.
If n = 8, then the number of steps will be 3.
So, as data doubles the number of steps increases by one.
The number of steps grows slowly in comparison to the growth in data size.
The best example of logarithmic complexity in software programming is the Binary Search tree. You will learn more about it in the chapter based on Trees.

Question 8.
What is worst-case time complexity of an algorithm?
Answer.
The worst-case time complexity in computer science means worst-case in terms of time consumed while execution of a program. It is the longest-running time that an algorithm can take. The efficiency of algorithms can be compared by looking at the order of growth of the worst-case complexity.

Question 9.
What is the importance of Big-O notation?
Answer:
Big-0 notation describes how fast the runtime of an algorithm will increase with respect to the size of the input. It would give you a fair idea about how your algorithm would scale and also give you an idea about the worst-case complexity of the algorithms that you might be considering for your project. You would be able to compare two algorithms and decide which would be a better option for you.

Question 10.
What is the need for run-time analysis for an algorithm when you can find the exact runtime for a piece of code?
Answer:
The exact runtime is not. considered because the results can vary depending on the hardware of the machine, the speed of the processor, and the other processors that are running in the background. What is more important to understand is that how the performance of the algorithm gets affected with an increase in input data.

Question 11.
The big-O analysis is also known as.
Answer:
Asymptotic analysis

Question 12.
What do you understand by asymptotic notation?
Answer:
It is very important to know how fast a program would run and as mentioned earlier we do not want to consider the exact ran time because different computers have different hardware capabilities and we may not get the correct information in this manner.
In order to resolve this issue, the concept of asymptotic notation was developed. It provides a universal approach for measuring the speed and efficiency of an algorithm. For applications dealing with large inputs we are more interested in behaviour of an algorithm as the input size increases. Big O notation is one of the most important asymptotic notations.

Question 13.
Why is Big O notation expressed as O(n)?
Answer:
Big-0 notation compares the runtime for various types of input sizes. The focus is only on the impact of input size on the runtime which is why we use the n notation. As the value of n increases, our only concern is to see how it affects the runtime. If we had been measuring the runtime directly then the unit of measurement would have been time units like second, micro-second, and so on. However, in this case, ‘n’ represents the size of the input, and ‘O’ stands for ‘Order’. Hence, 0(1) stands for the order of 1, 0(n) stands for the order of n, and 0(n2) stands for the order of the square of the size of the input.
Big-0 notations and names:

  1. Constant – 0(1)
  2. Logarithmic – 0(log(n))
  3. Linear -0(n)
  4. Log Linear – 0(nlog(n))
  5. Quadratic – 0(«2)
  6. Cubic – 0(«3)
  7. Exponential – 0(2″)

Question 14.
Write a code in python that takes a list of alphabets such as [‘a’ , ‘b’ , ‘c’, ‘d’ , ‘e’ , ’f’ , ’g’] and returns a list of combination such as [‘bcdefg’, ‘acdefg’, ‘abdefg’, ‘abcefg’, ‘abcdfg’, ‘abcdeg’, ‘abcdef’]. Find the time complexity for the code.
Answer:
Code

input_value = input("enter the list of alphabets separate by comma : ")
alphabets = input_value.split(' , ')
final = [ ]
str = ' '
for element in range(0,len(alphabets)):
for index, item in alphabets:
if(item != alphabets[element]):
str = str+item
final. append (str)
str=' '

Execution

print (final)

Output

enter the list of alphabets seperate by comma : a,b,c,d,e,f,g
[‘bcdefg’, ‘acdefg’, ‘abdefg’, ‘abcefg’, ‘abcdfg’, ‘abcdeg’, ‘abcdef’]
>>>

Conclusion:

The code has a runtime of O(n<sup>2</sup>).

Question 15.
The following code finds the sum of all elements in a list. What is its time complexity?

def sum(input_list):
total = 0
for i in input_list:
total = total + i
print(total)

Answer:

def sum(input_list):
total = 0                              -----------(1)
for i in input list:                   -----------(2)
total = total + i
         print(total)                  -----------  (3)
time for block (1) = O(1)
time for block (2) = O(n)
time for block (3) = O(1)
Total time = O(1) + O(n) + O(1)
Dropping constants
Total time = O(n)

Question 16.
What are the pros and cons of time complexity?
Answer:
Pros:
It is a good way of getting an idea about the efficiency of the algorithm.
Cons:
It can be difficult to assess complexity for complicated functions.

Question 17.
What is the difference between time and space complexity?
Answer:
Time complexity gives an idea about the number of steps that would be involved in order to solve a problem. The general order of complexity in ascending order is as follows:

O(1) < O(log n) < O(n) < O(n log n) <O(n<sup>2</sup>)

Unlike time, memory can be reused and people are more interested in how fast the calculations can be done. This is one main reason why time complexity is often discussed more than space complexity. However, space complexity is never ignored. Space complexity decides how much memory will be required to run a program completely. Memory is required for:

  1. Instruction space
  2. Knowledge space for constants, variables, structured variables, dynamically altered areas, etc
  3. Execution

Question 18.
What is the difference between auxiliary space and space complexity?
Answer:
Auxiliary space is the extra space that is required while executing an algorithm and it is temporary space.
Space complexity on the other hand is the sum of auxiliary space and input space:

Space complexity = Auxiliary space + Input space

Question 19.
What is the memory usage while executing the algorithm?
Answer:
Memory is used for:

  1. Saving the compiled version of instructions.
  2. In the case of nested functions or one algorithm, calling another algorithm, the variables are pushed to a system stack and made to wait till the internal algorithm has finished executing.
  3. To store data and variables.

Space Complexity

You have learned about time complexity. Now, let’s move on to space complexity. As the name suggests space complexity describes how much memory space would be required if the size of input n increases. Here too we consider the worst-case scenario.

Now have a look at the following code:
>>> X = 23                                                                               (1)
>>> y = 34                                                                               (2)
>>> sum = x + y                                                                      (3)
>>> sum
57
>>>

In this example, we need space to store three variables: x in (1), y in (2), and sum in (3). However, this scenario will not change, and the requirement for 3 variables is constant and hence the space complexity is 0(1).

Now, have a look at the following code:

word = input(“enter a word : “)
word_list = [ ]
for element in word:
print(element)
word_list.append(element)
print(word_list)

The size of the word_list object increase with n. Hence, in this case, the space complexity is 0(n).

If there is a function 1 which has to suppose three variables and this functional calls another function named function2 that has 6 variables then the overall requirement for temporary workspace is 9 units. Even if functional calls function2 ten times the workspace requirement will remain the same.

Question 20.
What would be the space complexity for the following piece of code? Explain.

n = int(input("provide a number : "))
statement = "Happy birthday"
for i in range(0,n):
print(i+1,". ”, statement)

Answer:
The space complexity for the above code will be 0(1) because the space requirement is only for storing value of integer variable n and string statement. Even if the size of n increases the space requirement remains constant. Hence, 0(1).

Question 21.
What is the time and space complexity for the following:

a = b = 0
for i in range(n):
a = a + i
for j in range(m):
b = b + j

Answer:
Timecomplexity
Time for first loop = O(n)
Time for second loop = O(m)
Total time = O(n) + O(m) = O(n + m)
Space complexity
O(1)

Question 22.
Find the time complexity for the following code:

a = 0
for i in range(n):
a = a + i
for j in range(m):
a = a + i + j

Answer:
Time complexity: O(n2)

Question 23.
What will be the time complexity for the following code?

i = j = k =0
for i in range(n/2,n):
for j in range(2,n):
k = k+n/2
j = j*2

Answer:
The time complexity for the first for loop O(n/2).
The time complexity for second for loop: O(logn) because j is doubling itself till it is less than n.
Total time = O(n/2)*O(logn)
= O(nlogn)

Question 24.
What is the time complexity for the following code:

i = a = 0
while i>0:
a = a+i
i = i/2

Answer:
Time complexity will be O(logn).

Big O for Python Data Structures

Python language comprises mutable and immutable objects. Numbers, strings, and tuple come in the latter category whereas lists, sets, and dictionary data types are mutable objects. The reason why lists and dictionaries are called mutable is that they can be easily altered at any time. They are like arrays because the data elements can be inserted or deleted easily by providing an index value and since the values can be easily added or removed from any point, the lists are considered to be dynamic. Hence, lists are known to be dynamic arrays. You can also say that lists are called dynamic array because:

  1. Its size can be dynamically modified at run time.
  2. You need not define the size of the list when you create it.
  3. They allow you to store more than one variable.
  4. Dynamic arrays once filled allocate a bigger chunk of memory, and elements of the original array are copied to this section of the memory as a result it can continue to fill available slots.

The most important operations that are performed on a list are as follows:

  1. Indexing
  2. Assigning value to an index value

Both the methods mentioned above are designed to run at constant time 0(1). The Big-0 for common list operations are given as follows:

  1. index[ ] : O(1)
  2. index assignment: O(1)
  3. append: O(1)
    1. pop( ): O(1)
  4. pop(i): O(n)
  5. insert(i, item): O(n)
  6. delete operator: O(n)
  7. contains(in): O(n)
  8. get slice[x:y]: O(k)
  9. del slice: O(n)
  10. set slice : O(n+k)
  11. reverse: O(n)
  12. concatenate: O(k)
  13. sort: O(nlog n)
  14. multiply O(nk)

Dictionaries

Dictionaries are implementation of hashtables and can be operated with keys and values.

Big-O efficiencies for common dictionary objects are given as follows:

  1. copy : 0(n)
  2. get item : 0(1)
  3. set item: 0(1)
  4. delete item : 0(1)
  5. contains(in): 0(1)
  6. iteration: 0(n)

Java continue outer loop – Java Continue Statement with Example | Continue Statement in Java with Nested Loop, For Loop, While Loop, Do-while Loop Programs

Java Continue Statement with Example

Java continue outer loop: A programming language uses control statements to control the flow of execution of a program. In Java programming, we can control the flow of execution of a program based on some conditions. Java control statements can be put into the following three categories: selection, iteration, and jump. In this tutorial, we will learn about the Java continue statement with example programs and workings. The jump statement can be used to transfer the control to other parts of the program. The java continues statement is one of the jump statements.

Java Continue Statement

The Java Continue Statement skips the current iteration of a for loop, while loop, and do-while loop. We can use a continue statement with all types of loops such as: for loop, while loop, and do-while loop. In the while and do-while loops, a continue statement causes control to be transferred directly to the conditional expression that controls the loop. In for loop, the control goes first to the iteration portion of the for statement and then to the conditional expression.

Syntax of Java Continue

continue;

Do Check:

Flow Diagram of Continue Statement

Java Continue Statement with Example 1

Working of Java continue statement

working of continue statement in java

Continue Statement Example

class ContinueStatement{
public static void main(String args[]){
for(int i = 1; i<=10; i++){
if(i%2 == 0)
continue;
//print odd values.
System.out.print(i+ " ");
}
}
}

Output:

1 3 5 7 9

Java Continue Statement with Nested Loop

In terms of java nested loops, the continue statement jumps the current iteration of the innermost loop.

Working of Java Continue Statement with Nested Loops:

working of java continue statement with nested loop

Example of Continue with Nested Loop:

class Main {
public static void main(String[] args) {

int i = 1, j = 1;

// outer loop
while (i <= 3) {

System.out.println("Outer Loop: " + i);

// inner loop
while(j <= 3) {

if(j == 2) {
j++;
continue;
}

System.out.println("Inner Loop: " + j);
j++;
}
i++;
}
}
}

Output:

Outer Loop: 1
Inner Loop: 1
Inner Loop: 3
Outer Loop: 2
Outer Loop: 3

Java Continue Statement with Labeled for Loop

As with the break statement, the continue may also specify a label to describe which enclosing loop to continue. Here is an example that demonstrates the use of a continue statement with a label inside an inner for loop.

Example of Labeled Continue Statement:

class LabelContinue{
public static void main(String args[]){
aa:
for(int i = 1; i<=3; i++){
bb:
for(int j = 1; j<=3; j++){
if(i==2 && j==2){
continue aa;
}
System.out.println(i+ " " +j);
}
}
}
}

Output:

1 1
1 2
1 3
2 1
3 1
3 2
3 3

Java Continue Statement with Inner Loop

In case, we use the continue statement inside the inner loop, then it continues the inner loop only. Let’s see the example program and understand the concept carefully:

Example on Continue with Inner Loop:

//Java Program to illustrate the use of continue statement
//inside an inner loop
public class ContinueExample2 {
public static void main(String[] args) {
//outer loop
for(int i=1;i<=3;i++){
//inner loop
for(int j=1;j<=3;j++){
if(i==2&&j==2){
//using continue statement inside inner loop
continue;
}
System.out.println(i+" "+j);
}
}
}
}

Output:

1 1
1 2
1 3
2 1
2 3
3 1
3 2
3 3

Java Continue Statement in while loop

We use the while loop when the number of iteration is not fixed. So, check out the example on java continue with while loop and grasp thoroughly.

Example on Java Continue statement inside While loop:

// Java Program to illustrate the use of continue statement
// inside the While loop
public class GFG {

// Main driver method
public static void main(String args[])
{
// Initializing a variable say it count to a value
// greater than the value greater among the loop
// values
int count = 20;

// While loop for iteration
while (count >= 0) {
if (count == 7 || count == 15) {
count--;
// Decrementing variable initialized above

// Showing continue execution inside loop
// skipping when count==7 or count==15
continue;
}

// Printing values after continue statement
System.out.print(count + " ");

// Decrementing the count variable
count--;
}
}
}

Output:

20 19 18 17 16 14 13 12 11 10 9 8 6 5 4 3 2 1 0

Java Continue Statement in do-while loop

A do-while loop is as same as the while loop, but it holds one dissimilarity. In a while loop, the condition is estimated before the execution of the loop’s body however in a do-while loop, the condition is assessed after the execution of the loop’s body. Check the sample program from the below section:

Continue Statement in Java Example in Do-While loop

public class ContinueExample{
public static void main(String args[]){
int i=1;
do
{
if (i==5)
{
i++;
continue;
}
System.out.print(i+ " ");
i++;
}while(i<10);

}
}

Output:

1 2 3 4 6 7 8 9

ASP.NET interview question pdf – ASP.NET Interview Questions and Answers for Freshers

ASP.NET interview question pdf: We have compiled most frequently asked .NET Interview Questions which will help you with different expertise levels.

C#.NET Interview Questions and Answers for Freshers Pdf Free Download

Question 1.
What is ASP.Net?
Answer:
It is a framework developed by Microsoft on which we can develop new generation websites using web forms(aspx), MVC, HTML, Javascript, CSS, etc. Its successor of Microsoft Active Server Pages(ASP). Currently, there is ASP.NET 4.0, which is used to develop websites. There are various page extensions provided by Microsoft that are being used for website development. Eg: aspx, asmx, ascx, ashx, cs, vb, HTML, XML etc.

Question 2.
What are the advantages of ASP.NET?
Answer:
ASP.Net is the next generation of ASP technology platform. It is superior to ASP in the following ways:

  • Highly Scalable
  • Compiled Code
  • User Authentication
  • Language Support
  • Third-party control
  • Configuration and Deployment are easy,
  • Object and Page caching
  • Strict coding requirements

Question 3.
What’s the use of Response.Output.Write( )?
Answer:
We can write formatted output using Response.Output.Write( ).

Question 4.
In which event of page cycle is the ViewState available?
Answer:
After the lnit( ) and before the Page_Load().

Question 5.
What is the difference between Server. Transfer and Response. Redirect?
Answer:
In Server. Transfer page processing transfers from one page to the other page without making a round-trip back to the client’s browser. This provides a faster response with a little less overhead on the server. The client url history list or current url Server does not update in the case of the Server. Transfer.

Response. Redirect is used to redirect the user’s browser to another page or site. It performs a trip back to the client where the client’s browser is redirected to the new page. The user’s browser history list is updated to reflect the new address.

Question 6.
From which base class all Web Forms are inherited?
Answer:
Page class.

Question 7.
What are the different validators in ASP.NET?
Answer:

  1. Required Field Validator
  2. Range Validator
  3. Compare Validator
  4. Custom Validator
  5. Regular expression Validator
  6. Summary Validator

Question 8.
Which validator control do you use if you need to make sure the values in two different controls matched?
Answer:
Compare Validator control.

Question 9.
What is the concept of Postback in ASP.NET?
Answer:
Postback is a request which is sent from a client to the server from the same page user is working with. There is an HTTP POST request mechanism in ASP.NET. It posts a complete page back to the server to refresh the whole page.

Question 10.
What is the use of “isPostBack” property?
Answer:
The “IsPostBack” property of the page object is used to check that the page is posted back or not.

Question 11.
How do you identify that the Page is PostBack?
Answer:
There is a property named “IsPostBack” property in Post object, which can be checked to know that the page is posted back.

Question 12.
What is ViewState?
Answer:
ViewState is used to retain the state of server-side objects between page post-backs.

Question 13.
Where the ViewState is stored after the page postback?
Answer:
ViewState is stored in a hidden field on the page on the client-side. ViewState is transported to the client and back to the server and is not stored on the server or any other external source.

Question 14.
How long the items in ViewState exists?
Answer:
They exist for the life of the current page.

Question 15.
What are the different Session state management options available in ASP.NET?
Answer:

  1. In-Process
  2. Out-of-Process.

In-Process stores the session in memory on the web server.
Out-of-Process Session state management stores data in an external server. The external server may be either a SQL Server or a State Server. All objects stored in session are required to be serializable for Out-of-Process state management.

Question 16.
How you can add an event handler?
Answer:
Using the Attributes property of server side control, e.g.
btnSubmit.Attributes.Add(“onMouseOver,,;,,JavascriptCode( );”)

Question 17.
What is caching?

Caching is a technique used to increase performance by keeping frequently accessed data or files in memory. The request for a cached file/data will be accessed from cache instead of actual location of that file.

Question 18.
what are the main requirements for caching?
Answer:

  • By caching the response, your request is served by the response already stored in memory.
  • You must be very careful while choosing the items to cache because Caching incurs overhead.
  • A frequently used web form which data doesn’t frequently change is good for caching.
  • A cached web form freezes form?s server-side content, and changes to that content do not appear until the cache is refreshed.

Question 19.
What are the different types of caching?ASP.NET has 3 kinds of caching :
Answer:

  1. Output Caching,
  2. Fragment Caching,
  3. Data Caching.

Question 20.
Which type if caching will be used if we want to cache the portion of a page instead of whole page?
Answer:
Fragment Caching: It caches the portion of the page generated by the request. For that, we can create user controls with the below code:
<%@ OutputCache Duration=”120″ VaryByParam=”CategorylD;SelectedlD”%>

Question 21.
List the events in page life cycle.
Answer:

  1. Page_Prelnit
  2. Page_lnit
  3. Page_lnitComplete
  4. Page_PreLoad
  5. Page_Load
  6. Page_LoadComplete
  7. Page_PreRender
  8. Render

Question 22.
Can we have a web application running without web.Config file?
Answer:
Yes

Question 23.
What is the difference between ASP.NET Webforms and ASP.NET MVC?
Answer:
ASP.NET Webforms uses the page controller approach for rendering layout. In this approach, every page has its controller.
On the other hand, ASP.NET MVC uses the Front Controller approach. In this approach, there is a common controller for all pages.

Question 24.
Is it possible to create a web application with both webforms and MVC?
Answer:
Yes. We have to include the below MVC assembly references in the web forms application to create a hybrid application.

System.Web.Mvc 

System.Web.Razor


System. ComponentModel.DataAnnotations

Question 25.
Can we add code files of different languages in the App_Code folder?
Answer:
No. The code files must be in the same language to be kept in the App_code folder.

Question 26.
What is Protected Configuration?
Answer:
It is a feature used to secure connection string information.

Question 27.
Write code to send e-mail from an ASP.NET application?
Answer:

MailMessage mailMess = new MailMessage ( );
mailMess.From = "abc@gmail.com
             ";
mailMess.To = "xyz@gmail.com";
mailMess.Subject = "Test email";
mailMess.Body = "Hi This is a test mail.";
SmtpMail.SmtpServer = "localhost";
SmtpMail.Send (mailMess);

MailMessage and SmtpMail are classes defined System.Web.Mail namespace.

Question 28.
How can we prevent browser from caching an ASPX page?
Answer:
We can SetNoStore on HttpCachePolicy object exposed by the Response object’s Cache property:

Response.Cache.SetNoStore ( );
Response.Write (DateTime.Now.ToLongTimeString ());

Question 29.
What is the good practice to implement validations in aspx page?
Answer:
Client-side validation is the best way to validate data of a web page. It reduces the network traffic and saves server resources.

Question 30.
What is the use of Global.asax file?
Answer:
The Global.asax file is used to execute the application-level events and sets application- level variables.

Question 31.
What is event bubbling?
Answer:
When child control sends events to parent, it is termed as event bubbling. Server controls like Data Grid, Data List, and Repeater can have other child controls inside them.

Question 32.
What are the event handlers that we can have in Global.asax file?
Answer:
Application Events: Application_Start, Application_End, Application_AcquireRequestState, Application_AuthenticateRequest, Application_AuthorizeRequest, Application_BeginRequest, Application_Disposed, Application_EndRequest, Application_Error, Application_PostRequestHandlerExecute, Application_PreRequestHandlerExecute,Application_PreSendRequestContent, Application_PreSendRequestHeaders, Application_ReleaseRequestState, Application_ResolveRequestCache, Application_UpdateRequestCache

Session Events: Session_Start,Session_End

Question 33.
Which protocol is used to call a Web service?
Answer:
HTTP Protocol

Question 34.
Can we have multiple web config files for an asp.net application?
Answer:
Yes.

Question 35.
What is the difference between web config and machine config?
Answer:
Web config file is specific to a web application where as machine config is specific to a machine or server. There can be multiple web config files into an application where as we can have only one machine config file on a server.

Question 36.
Explain role based security ?
Answer:
Role-based security is used in almost all organization, and the Role-based security assigns certain privileges to each role.

  • Each user is assigned a particular role from the list.
  • Privileges as per role restrict the user’s actions on the system and ensure that a user can do only what he is permitted to do on the system.
<AUTHORIZATION>< authorization >
< allow roles="Domain_Name\Administrators" / > < !-- Allow Administrators in domain. 
 — >
< deny users-'*" />                             < !-- Deny anyone else. -- >
< /authorization >

Question 37.
What is Cross Page Posting?
Answer:
When we click submit button on a web page, the page post the data to the same page. The technique in which we post the data to different pages is called Cross Page posting. This can be achieved by setting POSTBACKURL property of the button that causes the postback. Findcontrol method of PreviousPage can be used to get the posted values on the page to which the page has been posted.

Question 38.
How can we apply Themes to an asp.net application?
Answer:
We can specify the theme in web.config file. Below is the code example to apply the theme:

<configuration> 

<system.web> 

<pages theme="Windows7" />

 </system.web> 

</configuration>

Question 39.
What is RedirectPermanent in ASP.Net?
Answer:
RedirectPermanent Performs a permanent redirection from the requested URL to the specified URL. Once the redirection is done, it also returns 301 Moved Permanently responses.

Question 40.
What is MVC?
Answer:
MVC is a framework used to create web applications. The web application base builds on Model-View-Controller pattern which separates the application logic from Ul, and the input and events from the user will be controlled by the Controller.

Question 41.
Explain the working of passport authentication.
Answer:
First of all it checks passport authentication cookie. If the cookie is not available then the application redirects the user to Passport Sign on page. Passport service authenticates the user details on sign on page and if valid then stores the authenticated cookie on client machine and then redirect the user to requested page

Question 42.
What are the advantages of Passport authentication?
Answer:
All the websites can be accessed using single login credentials. So no need to remember login credentials for each web site.

Users can maintain his/ her information in a single location.

Question 43.
What are the asp.net Security Controls?
Answer:

  • <asp:Login>: Provides a standard login capability that allows the users to enter their credentials
  • <asp:Loginl\lame>: Allows you to display the name of the logged-in user
  • <asp:LoginStatus>: Displays whether the user is authenticated or not
  • <asp:LoginView>: Provides various login views depending on the selected template
  • <asp:PasswordRecovery>: email the users their lost password

Question 44.
How do you register JavaScript for webcontrols ?
Answer:
We can register javascript for controls using <CONTROL -name>Attribtues.Add(scriptname,scripttext) method.

Question 45.
In which event are the controls fully loaded?
Answer:
Page load event.

Question 46.
what is boxing and unboxing?
Answer:
Boxing is assigning a value type to reference type variable. Unboxing is reverse of boxing ie. Assigning reference type variable to value type variable.

Question 47.
Differentiate strong typing and weak typing
Answer:
In strong typing, the data types of variable are checked at compile time. On the other hand, in case of weak typing the variable data types are checked at runtime. In case of strong typing, there is no chance of compilation error. Scripts use weak typing and hence issues arises at runtime.

Question 48.
How we can force all the validation controls to run?
Answer:
The Page.Validate( ) method is used to force all the validation controls to run and to perform validation.

Question 49.
List all templates of the Repeater control.
Answer:

  • ItemTemplate
  • AlternatingltemTemplate
  • SeparatorTemplate
  • HeaderTemplate
  • FooterTemplate

Question 50.
List the major built-in objects in ASP.NET?
Answer:

  • Application
  • Request
  • Response
  • Server
  • Session
  • Context

Question 51.
What is the appSettings Section in the web.config file?
Answer:
The appSettings block in the web config file sets the user-defined values for the whole application.
For example, in the following code snippet, the specified Connectionstring section is used throughout the project for database connection:

<emxconfiguration>
<appSettings>
<add key-'ConnectionString" value="server=local; pwd=password; database=default" /> 
</appSettings></em>

Question 52.
Which data type does the RangeValidator control support?
Answer:
The data types supported by the RangeValidator control are Integer, Double, String, Currency, and Date.

Question 53.
What is the difference between an HtmllnputCheckBox control and an HtmllnputRadioButton control?
Answer:
In HtmllnputCheckBoxcontrol, multiple item selection is possible whereas in HtmllnputRadioButton controls, we can select only single item from the group of items.

Question 54.
Which namespaces are necessary to create a localized application?
Answer:
System.Globalization
System.Resources

Question 55.
What is a cookie?
Answer:
A Cookie is a small piece of information which is stored at the client side. There are two types of cookie:

  • Session/Temporary Cookie: valid for a single session
  • Persistent Cookie: valid for multiple session

Question 56.
What is the default timeout for a cookie?
Answer:
30 minutes.

Question 57.
How would you turn off cookies on a page of a website?
Answer:
You have to follow the procedures given below:

  • Use the “Cookie.Discard” property,
  • It gets or sets the discard flag set by the server.
  • When set to true, this property instructs the client application not to save the Cookie on the hard disk of the user at the end of the session.

Question 58.
What are the different types of cookies in ASP.NET?
Answer:
Session Cookie – Resides on the client machine for a single session until the user does not log out.
Persistent Cookie – Resides on a user’s machine for a period specified for its expiry, such as 10 days, one month, and never.

Question 59.
What is the file extension of web service?
Answer:
Web services have file extension .asmx..

Question 60.
What are the components of ADO.NET?
Answer:
The components of ADO.Net are Dataset, Data Reader, Data Adaptor, Command, connection.

Question 61.
What is the difference between ExecuteScalar and ExecuteNonQuery?
Answer:
ExecuteScalar returns output value where as ExecuteNonQuery ctoes not return any value but the number of rows affected by the query. ExecuteScalar used for fetching a single value and ExecuteNonQuery used to execute Insert and Update statements.

Question 62.
What is IIS?
Answer:
IIS stands for Internet Information Services. It is created by Microsoft to provide Internet-based services to ASP.NET Web applications.

Question 63.
What is the usage of IIS?
Answer:
Following are the main usage of IIS:

  • IIS is used to make your computer to work as a Web server and provides the functionality to develop and deploy Web applications on the server,
  • IIS handles the request and response cycle on the Web server,
  • IIS also offers the services of SMTP and Frontpage server extensions.
  • The SMTP is used to send emails and use Frontpage server extensions to get the dynamic features of IIS, such as form handler.

Question 64.
What is a multilingual website?
Answer:
If a website provides content in many languages, it is known as a multilingual website. It contains multiple copies of its content and other resources, such as date and time, in different languages.

Question 65.
What is the parent class of all web server control?
Answer:
System. Web. Ul.Control class

Question 66.
What is the difference between the GET method () and POST method ()?
Answer:
GetMethod

Data is affixed to the URL.
Data is not secured.
Data transmission is faster in this method.
It is a single call system.
Only a limited amount of data can be sent.
It is a default method for many browsers.

PostMethod

Data is not affixed to the URL Data is secured.
Data transmission is comparatively slow
It is a two call system
A large amount of data can be sent
It is not set as default. It should be explicitly specified

Question 67.
What is the difference between session object and application object?
Answer:
The session object is used to maintain the session of each user. A session id is generated if a user enters in the application and when the user leaves the application, the session id is automatically deleted.
On the other hand, the application object is used to store the information and access variables from any page in the application.
Debug class is used to debug builds. Trace class is used for both debug and release builds.

Question 68.
What is the difference between trace and debug?
Answer:
Debug class is used to debug builds. Trace class is used for both debug and release builds.

Question 69.
What is the difference between client-side and server-side validations in WebPages?
Answer:
The client-side validation happens at the client’s side with the help of JavaScript and VBScript. This validation has occurred before the Web page is sent to the server. The server-side validation happens at the server side.

Question 70.
What is the difference between file-based dependency and key-based dependency?
Answer:
File-based dependency: File-based dependency facilitates you to save the dependency on a file in a disk.
Key-based dependency: In key-based dependency, you depend on another cached item.

Question 71.
What is the difference between globalization and localization?
Answer:
Globalization: Globalization is a technique to identify the part of a Web application that is different for different languages and separate it out from the web application.

Localization: In localization, you try to configure a Web application so that it can be supported for a specific language or locale.

Question 72.
What is the difference between a page theme and a global theme?
Answer:
Page Theme: The page theme is applied to particular web pages of the project. It is stored inside a subfolder of the App_Themes folder.
Global Theme: The Global theme is applied to all the web applications on the web server. It is stored inside the Themes folder on a Web server.

Question 73.
What is the difference between early binding and late binding?
Answer:
Early Binding: In early binding, a non-virtual method is called which is decided at a compile time.
Late Binding: In late binding, a virtual method is called which is decided at runtime.

Question 74.
What is the difference between server-side scripting and client-side scripting?
Answer:
Server-side scripting: In server-side scripting, all the script are executed by the server and interpreted as needed.

Client-side scripting: In client-side scripting, the script will be executed immediately in the browser such as form field validation, email validation, etc. The client-side scripting is usually carried out in VBScript or JavaScript.

Question 75.
How to sign out from forms authentication?
Answer:
FormsAuthentication.Signout() method is used to sign out from forms authentication.

Question 76.
How to display validation messages in one control?
Answer:
By the help of ValidationSummary control, we can display all validation messages in one control.

Question 77.
What is the difference between authentication and authorization?
Answer:
Authentication is a process of identifying user whereas authorization is used to check the access rights of an identified user.

Question 78.
Which object encapsulates state or data of a user?
Answer:
Session object.

Question 79.
What are the differences between the Response.Write() and Response.Output.Write()?
Answer:
Response.Write( ) is used for normal output whereas Response.Output.Write() is used for formatted output.

Question 80.
Define the types of configuration files.
Answer:
There are two types of configuration files:

  • Application Level config = Web.config.
  • Machine Level config = Machine.config.

Question 81.
What is the difference between Web config and Machine config files?
Answer:
Web config file is specific to web application whereas Machine config file is specific to machine or server.
There can be multiple web config files in an application but only one machine config file.

Question 82.
What are the HTML server controls in ASP.NET?
Answer:

  • HTML server controls are just like HTML elements that we use on HTML pages.
  • HTML server controls are used to expose properties and events for use.
  • To make these controls programmatically accessible, we specify that the HTML controls act as a server control by adding the runat=Mserver” attribute.

Java swing interview questions – Abstract Windows Toolkit (AWT) Interview Questions in Java

Java swing interview questions: List of topic-wise frequently asked java interview questions with the best possible answers for job interviews.

Abstract Windows Toolkit (AWT) Interview Questions in Java

Question 1.
What is meant by controls and what are the different types of controls in AWT?
Answer:
Controls are components that allow a user to interact with your application and the AWT supports the following types of controls:
Labels, Push Buttons, Check Boxes, Choice Lists, Lists, Scrollbars, Text Components. These controls are subclasses of Component.

Question 2.
What is the difference between choice and list?
Answer:
A Choice is displayed in a compact form that requires you to pull it down to see the list of available choices and only one item may be selected from a choice. A-List may be displayed in such a way that several List items are visible and it supports the selection of one or more list items.

Question 3.
What is the difference between scrollbar and scrollpane?
Answer:
A Scrollbar is a Component, but not a Container whereas Scrollpane is a Container and handles its own events and performs its own scrolling.

Question 4.
What is a layout manager and what are the different types of layout managers available in java.awt?
Answer:
A layout manager is an object that is used to organize components in a container. The different layouts are available are FlowLayout, BorderLayout, CardLayout, GridLayout, and GridBagLayout.

Question 5.
How are the elements of different layouts organized?
Answer:
FlowLayout: The elements of a FlowLayout are organized in a top to bottom, left to right fashion.
BorderLayout: The elements of a BorderLayout are organized at the borders (North, South, East, and West)and the center of a container.
CardLayout: The elements of a CardLayout are stacked, on top of the other, like a deck of cards.
GridLayout: The elements of a GridLayout are of equal size and are laid out using the square of a grid.
GridBagLayout: The elements of a GridBagLayout are organized according to a grid.
However, the elements are of different sizes and may occupy more than one row or column of the grid. In addition, the rows and columns may have different sizes.

Question 6.
Which containers use a Border layout as their default layout?
Answer:
Window, Frame, and Dialog classes use a BorderLayout as their layout.

Question 7.
Which containers use a Flow layout as, their default layout?
Answer:
Panel and Applet classes use the FlowLayout as their default layout.

Question 8.
Why the container does not support multiple layout managers?
Answer:
because when u r using a particular layout manager it useful frame for work you can use a grid bag layout for this purpose.

Question 9.
What is clipping?
Answer:
Clipping is the process of confining paint operations to a limited area or shape.

Question 10.
What is meant by controls and what are the different types of controls in AWT?
Answer:
Controls are components that allow a user to interact with your application and the AWT supports the following types of controls:
Labels, Push Buttons, Check Boxes, Choice Lists, Lists, Scrollbars, Text Components. These controls are subclasses of Component.

Question 11.
What is the difference between choice and list?
Answer:
A Choice is displayed in a compact form that requires you to pull it down to see the list of available choices and only one item may be selected from a choice. A-List may be displayed in such a way that several List items are visible and it supports the selection of one or more list items.

Question 12.
What is the difference between scrollbar and scrollpane?
Answer:
A Scrollbar is a Component, but not a Container whereas Scrollpane is a Container and handles its own events and performs its own scrolling.

Question 13.
What is a layout manager and what are the different types of layout managers available in java.awt?
Answer:
A layout manager is an object that is used to organize components in a container. The different layouts are available are FlowLayout, BorderLayout, CardLayout, GridLayout, and GridBagLayout.

Question 14.
What is a Layout Manager and what are the different Layout Managers available in java.awt and what is the default layout manager for the panel and the panel subclasses?
Answer:
A layout manager is an object that is used to organize components in a container. The different layouts are available in java.awt is:

• FlowLayout: The elements of a FlowLayout are organized in a top to bottom, left to right fashion.

• BorderLayout: The elements of a BorderLayout are organized at the borders (North, South, East, and West) and the center of a container.

• CardLayout: The elements of a CardLayout are stacked, one on top of the other, like a deck of cards.

• GridLayout: The elements of a GridLayout are of equal size and are laid out using the square of a grid.

• GridBagLayout: The elements of a GridBagLayout are organized according to a grid. However, the elements are of different sizes and may occupy more than one row or column of the grid. In addition, the rows and columns may have different sizes.
The default Layout Manager of Panel and Panel sub-classes is FlowLayout.

Question 15.
Which containers use a Border layout as their default layout?
Answer:
Window, Frame, and Dialog classes use a BorderLayout as their layout.

Question 16.
Which containers use a Flow layout as their default layout?
Answer:
Panel and Applet classes use the FlowLayout as their default layout.

Question 17.
Assume that g is an object belonging to the Graphics class. What image would be produced by the following commands? Draw a picture as part of your answer.
g;setColor(Color.gray);
g.fiIlRect(0,0,40,40);
g.fillRect(50,50,0,0);
g.setColor(Color.black);
g.fill0val(50,0,40,40);
g.fill0val(0,50,40,40);
Answer:
The method “g.fillRect(x,y,w,h)” draw a solid rectangle with its upper left corner at the point (x,y). The other two parameters, w, and h, give the width and height of the rectangle. In the second line “g.fillRect(50,50,0,0)” doesn’t produce any image at all, since the width and height are specified as zero. The method “g.fillOval(x,y,w,h)” draw a solid oval that just fits inside the rectangle with upper. left corner at (x,y) and with width w and height h. So, the picture produced contains one gray square and two black circles, arranged like this:
(Note: I actually meant the second fine to be “g.fillRect(50,50,40,40).” Without this typo, the picture would have another gray square.)

Question 18.
What is the use of the window class?
Answer:
The window class can be used to create a plain, bare-bones window that does not have a border or menu. The Window class can also be used to display introduction or welcome screens.

Question 19.
What are the benefits of Swing over AWT?
Answer:
Swing components are lightweight. We can have a pluggable look & feel feature that shows us how they appear on other platforms. We can add images to Swing components. We have toolbars and tooltips in Swing.

Question 20.
Where the CardLayout is used?
Answer:
Card Layout is used where we need to have a bunch of panels or frames one laying over another. It is replaced by TabbedPane in Swing.

Question 21.
What is the difference between Grid and GridbagLayout?
Answer:
In Grid layout, the size of each grid is constant whereas in GridbagLayout grid size can Vareid.

Question 22.
How will you add a panel to a Frame?
Answer:
Frame.add(panel,BorderLayout.NORTH) or Frame.add(panel,’’North”).

Question 23.
What is the use of the window class?
Answer:
The window class can be used to create a plain, bare-bones window that does not have a border or menu. The Window class can also be used to display introduction or welcome screens.

Question 24.
What is the difference between a Window and a Frame?
Answer:
The Frame class extends Window to define the main application window that can have a menu bar.

Question 25.
What is the difference between the Font and FontMetrics classes?
Answer:
The FontMetrics class is used to define implementation-specific properties, such as ascent and descent, of a Font object.

Question 26.
For which statements does it make sense to use a label?
Answer:
The only statements for which it makes sense to use a label are those statements that can enclose a break or continue statement.

Question 27.
Which TextComponent method is used to set a TextComponent to the read-only state?
Answer:
setEditable( )

Question 28.
How are the elements of a CardLayout organized?
Answer:
The elements of a CardLayout are stacked, one on top of the other, like a deck of cards.

Question 29.
What advantage do Java’s layout managers provide over traditional windowing systems?
Answer:
Java uses layout managers to layout components in a consistent manner across all windowing platforms. Since Java’s layout managers aren’t tied to absolute sizing and positioning, they are able to accommodate platform-specific differences among windowing systems.

Question 30.
What is the difference between the paint( ) and repaint( ) methods?
Answer:
The paint( ) method supports painting via a Graphics object. The repaint( ) method is used to cause paint( ) to be invoked by the AWT painting thread.

Question 31.
Which class is the immediate superclass of the Container class?
Answer:
Component

Question 32.
How can the Checkbox class be used to create a radio button?
Answer:
By associating Checkbox objects with a CheckboxGroup.

Question 33.
Name four Container classes.
Answer:
Window, Frame, Dialog, FileDialog, Panel, Applet, or ScrollPane

Question 34.
What Checkbox method allows you to tell if a Checkbox is checked?
Answer:
getState( )

Question 35.
How are the elements of a GridLayout organized?
Answer:
The elements of a GridBad layout are of equal size and are laid out using the squares of a grid.

Question 36.
Which Component subclass is used for drawing and painting?
Answer:
Canvas

Question 37.
What are the problems faced by Java programmers who don’t use layout managers?
Answer:
Without layout managers, Java programmers are faced with determining how their GUI will be displayed across multiple windowing systems and finding a common sizing and positioning that will work within the constraints imposed by each windowing system.

Question 38.
What is Double Buffering?
Answer:
Double Buffering is a technique used to achieve smooth animations in Canvases or Panels. It is memory and CPU-consuming but is unavoidable as soon as you want to animate something. This technique is not applicable for native components like Buttons, Lists, etc… Since the redisplay is handled by the underlying toolkits (Motif or MsWin).

To handle double buffering, one must first draw the widget’s contents in an off¬screen image and then transfer the contents of the image to the visible window.

class DoubleBufferedcanvas extends Canvas {

    public void update(Graphics g) {
    Graphics offgc;
    Image offscreen = null;
    Dimension d = size( );

    // create the offscreen buffer and associated Graphics
    offscreen = createimage(d.width, d.height);
    offgc = off screen. getGraphics( );
    //clear the exposed area
    offgc.setColor(getBackground( ));
    offgc.fillRect(0, 0, d.width, d.height);
    offgc.setColor(getForeground( ));
    // do normal redraw
    paint(offgc);
    // transfer offscreen to window
    g.drawimage(offscreen, 0, 0, this);
   }
}

This method has one major drawback: it copies the whole buffer each time an update is required. This may consume a lot of time and CPU for a large window Hopefully, graphics contains a definition of the area that has to be redrawn: it is called clip region. The region, in Java Graphics, has two meanings:

  1. It tells which part needs to be drawn
  2. It clips drawing orders inside this area that means if you draw outside the clip region, nothing will appear.

Using clip regions, we can define an optimized version of the DoubleBufferedCanvas:

class OptimizedDoubleBufferedCanvas extends canvas {

   public void update(Graphics g) {
   Graphics offgc;
   Image offscreen = null;
   Rectangle box = g.getclipRect( );

   // create the offscreen buffer and associated Graphics
   offscreen = createimagefbox.width, box.height);
   offgc = offscreen.getGraphics( ));
   // clear the exposed area
   offgc.setcolor(getBackg round( ));
   offgc.fillRect(0, 0, box.width, box.height);
   offgc.setcolor(getForeground( ));
   // do normal redraw
   offgc.translateC-box.x, -box.y);
   paint(offgc);
   // transfer offscreen to window
   g.drawlmage(offscreen, box.x, box.y, this);
   }
}

Question 39.
What is the preferred size of a component?
Answer:
The preferred size of a component is the minimum component size that will allow the component to display normally.

Question 40.
What method is used to specify a container’s layout?
Answer:
The setLayout( ) method is used to specify a container’s layout.

Question 41.
Which containers use a FlowLayout as their default layout?
Answer:
The Panel and Applet classes use the FlowLayout as their default layout.

Question 42.
Name Component subclasses that support painting.
Answer:
The Canvas, Frame, Panel, and Applet classes support painting.

Question 43.
Can an anonymous class be declared as implementing an interface and extending a class?
Answer:
An anonymous class may implement an interface or extend a superclass, but may not be declared to do both.

Question 44.
Which Container method is used to cause a container to be laid out and redisplayed?
Answer:
validate( )

Question 45.
What is the difference between a Window and a Frame?
Answer:
The Frame class extends Window to define the main application window that can have a menu bar.

Question 46.
What do heavy-weight components mean?
Answer:
Heavyweight components like Abstract Window Toolkit (AWT), depending on the local windowing toolkit. For example, java.awt.The button is a heavy-weight component, when it is running on the Java platform for Unix platform, it maps to a real Motif button. In this relationship, the Motif button is called the peer to the java.awt.Button. If you create two Buttons, two peers and hence two Motif Buttons are also created. The Java platform communicates with the Motif Buttons using the Java Native Interface. For each and every component added to the application, there is an additional overhead tied to the local windowing system, which is why these components are called heavyweight.

Question 47.
How are the elements of a GridBagLayout organized?
Answer:
The elements of a GridBagLayout are organized according to a grid. However, the elements are of different sizes and may occupy more than one row or column of the grid. In addition, the rows and columns may have different sizes.

Question 48.
What advantage do Java’s layout managers provide over traditional windowing systems?
Answer:
Java uses layout managers to layout components in a consistent manner across all windowing platforms. Since Java’s layout managers aren’t tied to absolute sizing and positioning, they are able to accommodate platform-specific differences among windowing systems

Question 49.
What is the difference between the paint( ) and repaint( ) methods?
Answer:
The paint( ) method supports painting via a Graphics object. The repaint( ) method is used to cause paint( ) to be invoked by the AWT painting thread.

Question 50.
Name Container classes.
Answer:
Window, Frame, Dialog, FileDialog, Panel, Applet, or ScrollPane

Question 51.
What is the difference between a Scrollbar and a ScrollPane?
Answer:
A Scrollbar is a Component, but not a Container. A ScrollPane is a Container. A ScrollPane handles its own events and performs its own scrolling.

Question 52.
What is a Container in a GUI?
Answer:
A Container contains and arranges other components (including other containers) through the use of layout managers, which use specific layout policies to determine where components should go as a function of the size of the container.

Question 53.
How to add a menu shortcut to menu items?
Answer:
If you have a button instance called the about the button, you may add a menu shortcut by calling the about button.setMnemonic(A.’), so the user may be able to use Alt+A to click the button.

Question 54.
What is the difference between Swing and AWT components?
Answer:
AWT components are heavy-weight, whereas Swing components are lightweight. Heavyweight components depend on the local windowing toolkit. For example, java.awt.The button is a heavy-weight component, when it is running on the Java platform for Unix platform, it maps to a real Motif button.

Question 55.
What is meant by controls and what are the different types of controls?
Answer:
Controls are components that allow a user to interact with your application. The AWT supports the following types of controls:
Labels, Pushbuttons, Checkboxes, Choice lists, Lists, Scroll bars, Text components These controls are subclasses of Component.

Question 56.
How can we get all public methods of an object dynamically?
Answer:
By using
get methods( ): It returns an array of method objects corresponding to the methods of this class.
getFields( ): It returns an array of Filed objects corresponding to the Fields(variables) of this class.
getConstructors( ): It returns an array of constructor objects corresponding to public constructors of this class.

Question 57.
What is the SubClass of Text component Class?
Answer:
TextField and TextArea

Question 58.
Which method of the Component class is used to set the position and the size of a component?
Answer:
setBounds( )

Question 59.
Which TextComponent method is used to set A TextComponent to the read¬only state?
Answer:
setEditable( )

Question 60.
How can the Checkbox class be used to create a radio button?
Answer:
By associating Checkbox objects with a CheckboxGroup.

Question 61.
What Checkbox method allows you to tell if a Checkbox is checked?
Answer:
getState( )

Question 62.
Which Component method is used to access a component’s immediate Container?
Answer:
getParent( )

Question 63.
What methods are used to get and set the text label displayed by a Button object?
Answer:
getLabel( ) and setLabel( )

Question 64.
What is the difference between a Choice and a List?
Answer:
A Choice is displayed in a compact form that requires you to pull it down to see the list of available choices. Only one item may be selected from a Choice.
A-List may be displayed in such a way that several List items are visible. A-List supports the selection of one or more List items.

Question 65.
Which Container method is used to cause a container to be laid out and redisplayed?
Answer:
validate( )

Question 66.
What is the difference between a Scrollbar and a Scrollpane?
Answer:
A Scrollbar is a Component, but not a Container. A Scrollpane is a Container and handles its own events and performs its own scrolling.

Question 67.
Which Component subclass is used for drawing and painting?
Answer:
Canvas.

Question 68.
Which method is used to set the text of a Label object?
Answer:
setText( )

Question 69.
Which method will cause a Frame to be displayed?
Answer:

a) . show( )
b) . setVisible( )

Question 70.
All the component classes and container classes are derived from
class.
Answer:
Object.

Question 71.
Which method of the container class can be used to add components to a Panel?
Answer:
add ( ) method.

Question 72.
What are the subclasses of the Container class?
Answer:
The Container class has three major subclasses. They are:
Window, Panel, ScrollPane

Question 73.
Can the Choice component allow multiple selections?
Answer:
No

Question 74.
Which components are used to get text input from the user?
Answer:
TextField and TextArea.

Question 75.
Which object is needed to group Checkboxes to make them exclusive?
Answer:
CheckboxGroup.

Question 76.
What are the types of Checkboxes and what is the difference between them?
Answer:
Java supports two types of Checkboxes. They are:
Exclusive and Non-exclusive.
In the case of exclusive Checkboxes, only one among a group of items can be selected at a time. If an item from the group is selected, the checkbox currently checked is deselected and the new selection is highlighted. The exclusive Checkboxes are also called Radio buttons.
The non-exclusive checkboxes are not grouped together and each one can be selected independent of the other.

Question 77.
What is a Layout Manager and what are the different Layout Managers available in java.awt and what is the default layout manager for the panel and the panel subclasses?
Answer:
A layout manager is an object that is used to organize components in a container.

Question 78.
What are the different layouts available in java.awt :
Answer:
FlowLayout, BorderLayout, CardLayout, GridLayout, GridBag Layout. The default Layout Manager of Panel and Panel sub classes is FlowLayout”.

Question 79.
Can I exert control over the size and placement of components in my interface?
Answer:
Yes.

Question 80.
Can I add the same component to more than one container?
Answer:
No. Adding a component to a container automatically removes it from any previous parent (container).

Question 81.
How do I specify where a window is to be placed?
Answer:
Use setBounds, setSize, or setLocation methods to implement this.
setBounds(int x, int y, int width, int height)
setBounds(Rectangle r)
setSize(int width, int height)
setSize(Dimension d)
setLocation(int x, int y)
setLocation(Point p)

Question 82.
How can we create a borderless window?
Answer:
Create an instance of the Window class, give it a size, and show it on the screen.
Ex. Frame obj =…………………..
Window WA = new Window(obj);
WA.setLayout(new FlowLayoutO);
WA.add(new Button(“OK”));
WA.getBounds(50,50,200,200);
WA.show( );

Question 83.
Can I create a non-resizable window? If so, how?
Answer:
Yes. By using setResizable( ) method in class Frame.

Question 84.
What is the default Layout Manager for the Window and Window subclasses (Frame, Dialog)?
Answer:
BorderLayout( )

Question 85.
Which containers use a BorderLayout as their default layout?
Answer:
The Window, Frame, and Dialog classes use a BorderLayout as their default layout.

Question 86.
Which containers use a FlowLayout as their default layout?
Answer:
The Panel and the Applet classes use the FlowLayout as their default layout.

Question 87.
What is the preferred size of a component?
Answer:
The preferred size of a component size will allow the component to display normally.

Question 88.
Which method is a method to set the layout of a container?
Answer:
setLayout( )

Question 89.
Which method returns the preferred size of a component?
Answer:
getPreferredSize( )

Question 90.
Which layout should you use to organize the components of a container in a tabular form?
Answer:
GridLayout

Question 91.
What are the default layouts for an applet, a frame, and a panel?
Answer:
For an applet and a panel, Flow layout is the default layout, whereas Border layout is the default layout for a frame.

Question 92.
How can you change the current layout manager for a container?
Answer:
By using setLayout( ) method.

Question 93.
Which is the default layout for Applet?
Answer:
The default layout manager for an Applet is FlowLayout, and The FlowLayout manager attempts to honor the preferred size of any components.

Question 94.
Which method does display the messages whenever there is an item selection or deselection of the CheckboxMenuItem menu?
Answer:
itemStateChanged method.

Question 95.
Which is a dual state menu item?
Answer:
CheckboxMenuItem.

Question 96.
Which container may contain a menu bar?
Answer:
Frame

Question 97.
What is the difference between a Menultem and a CheckboxMenuItem?
Answer:
The CheckboxMenuItem class extends the Menultem class to support a menu item that may be checked or unchecked.

Question 98.
What is the correct ordering for the import, class, and package declarations when found in a single file?
Answer:
package, import, class

Question 99.
What is the parameter specification for the public static void main method?
Answer:

  1. String args [ ]
  2. String [ ] args

Question 100.
What is the sweep and paint algorithm?
Answer:
The painting algorithm takes as input a source image and a list of brush sizes, sweep algo is that it computes the arrangement of n lines in the plane … a correct algorithm,

Question 101.
What are the component and container classes?
Answer:
A component is a graphical object. A few examples of components are Button, Canvas, Checkbox, Choice, etc.

Question 102.
Explain the purpose of invalidating and validate methods.
Answer:
The invalidate method is called a side effect of adding or deleting some component. Calling invalidates ( ) is however the first step of processing a COMPONENTJtESIZED event.

Question 103.
What are AWT peers? When are peers created and destroyed?
Answer:
A Component is associated with a standard AWT button object, a peer object (hidden button object internal to the native GUI), and an interfacing button object constructed per the native GUI.

Question 104.
Show with an example the usage of the FileDialog object.
Answer:
class FileDialog extends from Dialog class. It is used to display a dialog window from which the user can select a file.

Question 105.
Explain the purposes of the component’s request focus method.
Answer:
The purpose of the request focus( ) is to get the focus on the particular component and also on the window that contains the component.

Question 106.
Which method of the Component class is used to set the position and size of a component?
Answer:
The methods are: set maximum size(Dimension maximum size) Sets the maximum size of this component to a constant value.

Question 107.
What interface is extended by AWT event listeners?
Answer:
The java. util.EventListener interface is extended by all the AWT event listeners.

Question 108.
What is the paint method? What should we put in the paint method? When is it invoked?
Answer:
The AWT uses a Callback mechanism for painting which is the same for heavyweight and lightweight components.

Question 109.
What is the purpose of the repaint method? When should we use the repaint method?
Answer:
repaint( ) requests can erase and redraw (update) after a small time delay. When you invoke repaint( )

Question 110.
Explain the use of the update method. When is it invoked?
Answer:
An update method is called on calling the repaint method. The default implementation of the update( ) method clears the screen and calls the paint( ) method.

Question 111.
How does the XOR drawing mode work? What are the properties of XOR j drawing?
Answer:
setXORMode(Color cl) sets the paint mode of this graphics context to alternate between a graphics context’s current color and the new specified color.

Question 112.
Explain how to load an image from the net into my applet.
Answer:
private Imagelcon image;
inside the init method
image = new ImageIcon(new URL(http://www.xyz.gif));

Question 113.
Explain how to load an image from a file in a java application.
Answer:
Imagelcon icon = createImageIcon(“images/xyz.gif’, “text string”);

Question 114.
What is the difference between a Window and a Frame?
Answer:
A frame is a resizable, movable window with a title bar and a close button. Usually, it contains Panels. It’s derived from a window and has a BorderLayout by default.

Question 115.
Explain how to draw text over a background image.
Answer:
Bufferedlmage img = ImageIO.read(new File(“xxx”)); // xxx is the path TextOnBackground test = new TextOnBackground(img);

Question 116.
Define canvas?
Answer:
It is a simple drawing surface that is used for painting images or to perform other graphical operations.

 

Basics of Python – Regular Expression Module

In this Page, We are Providing Basics of Python – Regular Expression Module. Students can visit for more Detail and Explanation of Python Handwritten Notes Pdf.

Basics of Python – Regular Expression Module

Regular expression module

re module in python: A regular expression (also called RE, or regex, or regex pattern) is a specialized approach in Python, using which programmers can specify rules for the set of possible strings that need to be matched; this set might contain English sentences, e-mail addresses, or anything. REs can also be used to modify a string or to split it apart in various ways.

Meta characters

Most letters and characters will simply match themselves. For example, the regular expression test will match the string test exactly. There are exceptions to this rule; some characters are special “meta characters”, and do not match themselves. Instead, they signal that some out-of-the-ordinary thing should be matched, or they affect other portions of the RE by repeating them or changing their meaning. Some of the meta characters are discussed below:

Meta character

Description

Example

[ ]

Used to match a set of characters.

[time]

The regular expression would match any of the characters t, i, m, or e.

[a-z]

The regular expression would match only lowercase characters.

Used to complement a set of characters. [time]

The regular expression would match any other characters than t, i, m or e.

$

Used to match the end of string only. time$

The regular expression would match time in ontime, but will not match time in timetable.

*

Used to specify that the previous character can be matched zero or more times. tim*e

The regular expression would match strings like timme, tie and so on.

+

Used to specify that the previous character can be matched one or more times. tim+e

The regular expression would match strings like timme, timmme, time and so on.

?

Used to specify that the previous character can be matched either once or zero times. tim ?e

The regular expression would only match strings like time or tie.

{ }

The curly brackets accept two integer values. The first value specifies the minimum number of occurrences and the second value specifies the maximum of occurrences. tim{1,4}e

The regular expression would match only strings time, timme, timmme or timmmme.

Regular expression module functions

Some of the methods of re module as discussed below:

re. compile ( pattern )
The function compile a regular expression pattern into a regular expression object, which can be used for matching using its match ( ) and search ( ) methods, discussed below.

>>> import re
>>> p=re.compile ( ' tim*e ' )

re. match ( pattern, string )
If zero or more characters at the beginning of the string match the regular expression pattern, match-( ) return a corresponding match object instance. The function returns None if the string does not match the pattern.

re. group ( )
The function return the string matched by the RE.

>>> m=re .match ( ' tim*e' , ' timme pass time ' )
>>> m. group ( )
' timme '

The above patch of code can also be written as:

>>> p=re. compile ( ' tim*e ' )
>>> m=p.match ( ' timme pass timme ' )
>>> m.group ( )
'timme'

re. search ( pattern, string )
The function scans through string looking for a location where the regular expression pattern produces a match, and returns a corresponding match object instance. The function returns None if no position in the string matches the pattern.

>>> m=re.search( ' tim*e ' ' no passtimmmeee ' )
>>> m.group ( )
' timmme '

The above patch of code can also be written as:

>>> p=re.compile ( ' tim*e ' )
>>> m=p.search ( ' no passtimmmeee ' )
>>> m.group ( )
' timmme '

re.start ( )
The function returns the starting position of the match.

re.end ( )
The function returns the end position of the match.

re.span ( )
The function returns a tuple containing the ( start, end ) indexes of the match.

>>> m=re.search ( ' tim*eno passtimmmeee ' )
>>> m.start ( )
7
>>> m.end ( )
13
>>> m.span ( )
( 7 , 13 )

The above patch of code can also be written as:

>>> p=re.compile ( ' tim*e ' )
>>> m=p.search ( ' no passtimmmeee ' )
>>> m.start ( )
7 
>>> m.end ( )
13
>>> m.span ( )
( 7 , 13 )

re. findall ( pattern, string )
The function returns all non-overlapping matches of pattern in string, as a list of strings. The string is scanned left-to-right, and matches are returned in the order found.

>>> m=re.findall ( ' tim*e ' , ' timeee break no pass timmmeee ' )
>>> m 
[ ' time ' , ' timmme ' ]

The above patch of code can also be written as:

>>> p=re . compile ( ' tim*e ' )
>>> m=p.findall ( ' timeee break no pass timmmeee ' )
>>> m
[ ' time ', ' timmme ' ]

re. finditer ( pattern, string )
The function returns an iterator yielding MatchObject instances over all non-overlapping matches for the RE pattern in a string. The string is scanned left-to-right, and matches are returned in the order found.

>>> m=re.finditer ( ' tim*e ', ' timeee break no pass timmmeee ' )
>>> for match in m :
. . .           print match.group ( )
. . .           print match.span ( )
time 
( 0 , 4 ) 
timmme 
( 21 , 27 )

The above patch of code can also be written as:

>>> p=re.compile( ' tim*e ' )
>>> m=p.finditer ( ' timeee break no pass timmmeee ' )
>>> for match in m :
. . .         print match.group ( )
. . .         print match.span ( )
time 
( 0 , 4 ) 
timmme
( 21 , 27 )

Python data manipulation interview questions – Python Interview Questions on File Manipulation

Python data manipulation interview questions: We have compiled most frequently asked Python Interview Questions which will help you with different expertise levels.

Python Interview Questions on File Manipulation

Till now you have learned how to implement logic in Python to write blocks of code that can help you accomplish certain tasks. In this section, we will learn about how to use Python to work with files. You can read data from files and you can also write data to the files. You can not only access the internet but also check your emails and social media accounts using the Python programming language.

Files

A file has a permanent location. It exists somewhere on the computer disk and can be referred to anytime. It is stored on the hard disk in non-volatile memory which means the information in the file remains even if the computer is switched off. In this section, we will learn how to deal with files in Python.

Open a File

If you want to work on an existing file, then you will have to first open the file. In this section, we will learn how to open a file.
In order to open a file, we will make use of the open( ) function which is an inbuilt function. When we use the open( ) function, a file object is returned which can be used to read or modify the file. If the file exists in the same directory where python is installed then you need not give the entire pathname. However, if the location is different then you will have to mention the entire path.

For this example, I have created a file by the name: learning_files.txt in the current directory of python /home/pi.

The content of the file is as follows:

I am great a learning files

See how Good I am at opening Files

Thank you Python

Look at the following piece of code:

>>> f_handle = open ("learning_files . txt")
>>> print (f_handle . read ( ) )

In case the file is not available, the error message will be displayed as follows:

>>> f_handle = open ("llllearning_files . txt")
Traceback (most recent call last):
   File "<pyshell#0>", line 1, in <module>
      f_handle = open ("llllearning_files . txt")
FileNotFoundError: [Errno 2] No such file or
directory: ' llllearning_files.txt'
>>>

Output

I am great a learning files
See how Good I am at opening Files
Thank you Python

Python File Modes

Python has defined file modes that can be implemented when a file is opened. These modes define what can be done with the file once it is opened. If you do not mention the mode then “read” is considered the default mode. The list of various modes is given as follows:

‘r’ is also the default mode, it means that the file has been opened for reading purposes. You have already seen the usage of reading mode. To explain this a file by the name “test.txt” has been created. The content of the file is as follows:

“I am excited about writing on the file using Python for the first time. Hope You feel the same. ”

We will now give the following commands.:

>>> f_handle = open("test.txt" , 'r')
>>> f_handle . read (4)

The output for the above code is :
‘I am’

f_handle.read(4) retrieves the first four characters from the file and displays it.

‘w’ stands for writing. It means that you want to open a file and write in it. In case the file that you have mentioned does not exist then a new file will be created.

>>> f_handle = open("test .txt",'w')
>>> f_handle.write("I am excited about writing on the file using Python for the first time.")
71
>>> f_handle.write("Hope you feel the same.")
22
>>> f_handle.close( )
>>>

So, if you open the file now this is how the contents would look like:

The original content of the file before passing the write instructions was:
“I am excited about writing on the file using Python for the first time. Hope you feel the same.”
If you open the file after passing “write” instructions now the contents of the file will be as follows:
“Hi I have opened this file again and I feel great again. ”

As you can see that the previous lines (/ am excited about writing on the file using Python for the first time. Hope you feel the same.) have been erased from the file.

Now, we close the file and try to write something again in it.

>>> f_handle = open (test. txt", ' w' )
>>> f_handle.write ("\n Hi I have opened this file again and I feel great again.")
58
>>> f_handle.close ( )
>>>

‘x’ stands for exclusive creation. An error will be displayed if the file already exists. Let’s see what happens when we try to use ‘x’ mode with an already existing test.txt file.

>>> f_handle = open("F:/test.txt"x')
Traceback (most recent call last):
    File "<pyshell#l>", line 1, in <module>
f_handle = open("F:/test.txt"x')
FileExistsError: [Errno 17] File exists: 'F:/test.txt'

‘a’ is used to append an existing file. If a file does not exist then a new file will be created.

So, now we try to add new text to an already existing file.

The contest of test.txt file is as follows:

“I am excited about writing on the file using Python for the first time.
Hope You feel the same. ”

We will try to add the following line to it:

“Hi I have opened this file again and I feel great again. ”

In order to append, we follow the following steps:

>>> f_handle = open("test.txt",'a')
>>> f_handle.write("Hi I have opened this file again and I feel great again.")
56
>>> f_handle.close()
>>>

Output

I am excited about writing on the file using Python for the first time.
Hope You feel the same.


Hi, I have opened this file again and I feel great again.

‘t’ is used to open a file in text mode and ‘b’ is used to open the file in binary mode.

In the above examples, you must have noticed f_handle.close( ) command. It is important to use the close( ) command after you have stopped working with a file in order to free up operating system resources. If you leave the file open, you may encounter problems.

A better way of dealing with files is to keep the code related to file reading in a try block as shown in the following code:

>>> try:
       f_handle = open ("llllearning_files . txt")
       content = f_handle.read()
       f_handle.close()
except for IOError:
       print (''Could not find the file. Please check again")
       exit( )

Output

Could not find the file. Please check again

In the above piece of code, the file name given does not exist in the given location. Hence, the remaining code of the try block is ignored and the code written in the except block is applied. In the except block, we have provided a simpler and user-friendly message which is easier for the user to understand. Without the try expect to block the following message will be displayed:

Traceback (most recent call last):
   File "<pyshell#10>", line 1, in <module>
      f_handle = open ("llllearning_files .txt")
FileNotFoundError: [Errno 2] No such file or
directory: 'llllearning_files . txt'

Which can be difficult to decipher.

File-system-type commands:

Now we will have a look at some very common file-system-type operations such as move, copy, and so on.
We now try to copy the contents of this file to another file. For this we require to import shutil as shown in the following code:

>>> import shutil
>>> shutil. copy("F:/test.txt","F:/testl.txt")
'F:/testl.txt'

Output

Content of testl.txt file:

You can move the file or change the name of the file using the move command as shown in the following code:

>>> import shutil
>>> shutil.move("test.txt","test2.txt")
'test2.txt'
>>>

The above set of instructions changes the name of the file test.txt to test2. txt.

Another important package available with Python is glob.

The glob package allows you to create a list of a particular type of files by using the star * operator.

>>> import glob
>>> glob.glob("*.txt")
['important.txt', 'learning_files.txt', ' test1. txt', 'test2.txt']
>>>

Question 1.
How is a file opened for reading? Provide an example.
Answer:
Using the open function, and the ‘r’ mode.
myFile = openCpathToFile’,’r’)

Question 2.
What is the appropriate method to call when a file is no longer being used?
Answer:
file.close( )

Question 3.
What are the modes that a file can be opened in? Answer:

  • ‘r’ – reading,
  • ‘w’ – writing,
  • ‘a’ – append,
  • ‘r+’ reading and writing, contents intact,
  • ‘w+’ reading and writing, contents deleted,
  • ‘a+’ same as ‘r+’

Question 4.
What does the ‘b’ modifier do when appended to a file mode?
Answer:
It changes the handling of the file from text to binary mode.

Question 5.
What does the ‘U’ modifier do when appended to a file mode?
Answer:
It applies the universal new-line translator to the file when it is opened.

Question 6.
How is the buffer size specified in the file opening?
Answer:
It is an optional parameter to the open function. A 0 indicates the file is unbuffered, 1 indicates that line by line buffering. Any other positive number is the actual buffer size to be allocated.

Question 7.
How is an entire file read into a buffer and returned as a string? When is it a bad practice to do so?
Answer:
With the .read( ) method. When the file may be large, because the buffer may consume excessive memory.

Question 8.
How is a file read using a limited buffer size?
Answer:
By specifying how many bytes to read in the read method. file.read(20) would read the next 20 bytes from the file.

Question 9.
How can a single line be read from a text file? Provide an illustration.
Answer:
Using the linecache module.
import linecache
myFile = “’file.txt”
print linecache.getline(myFile, 1) # prints the first line
print linecache.getline(myFile,40) # prints the 40th line, etc.

Question 10.
What are two ways to write a line of text to a file?
Answer:
Using the .write method on an open file, or >>> redirection operator to use the print statement.

Question 11.
With a list of strings, how can they all be written out to a file in a single statement?
Answer:
Using the .writelines( ) method. Example:
myFile.writelinesdistName)

Question 12.
Illustrate how to determine the number of lines in a text file, using the readlines method. When would it be inappropriate to use this technique?
Answer:
myLineCount = len(open(myFilePath, Y).readlines())
It would be inappropriate to use if the file might be large, because the readlines method will generate a list of strings that includes the entire file’s contents. It would consume too much memory.

Question 13.
What module and method is used to traverse the file system directory tree?
Answer:
The os module. Specifically os.walk.

Question 14.
How are files deleted?
Answer:
Using the os.remove method. os.remove(‘myFile’)

Question 15.
How are files renamed?
Answer:
Using the os.rename method. os.renameColdFileName’, ‘newFileName’)

Question 16.
How are entire non-empty directory trees removed?
Answer:
Each directory must be walked using the os.walk method, then the files within must be deleted. Then and only then can the directory be removed using the os.rmdir method.

Question 17.
How is a tarfile created?
Answer:
Using the tarfile module.
import tarfile
my Tar = tarfile.open(“my Tarfile”, ‘w’)

Question 18.
How are files added to a tarfile or zipfile?
Answer:
Using the .add method to an open tar or zip file.

Question 19.
How are files extracted from a tar or zip file?
Answer:
Using the .extract method on an open tar or zip file, and specifying the file name and the extraction path.

Question 20.
Illustrate extracting all of the .txt files from a zip file.
Answer:
import os
import zipfile
myZip = zipfile.open(“myZip.zip “, Y)
for myFile in myZip.getnames( ):
if myFile.endswith(“txt”):
myZip.extract(myFile, “-/temp/”)
myZip.close( )

What is servlet – What is Servlet in Java with Example? | Servlet Architecture | What is the Use of Servlet in Java?

What is Servlet in Java

What is servlet: Java servlet is a key component of server-side Java development. A servlet is a small, pluggable extension to a server that enhances the server’s functionality.

A servlet is a server-side Java class that can be loaded dynamically to expand the functionality of a server.

  • Servlet is commonly used with a web server.
  • It is used to create a dynamic web page.
  • It is used to developing a dynamic web application.

What is Servlet in Java 1

While servlet can be used to extend web servers, providing a powerful, efficient replacement for the CGI script. To understand the power of Servlets, we need to step back and look at some of the other approaches that can be used to create web applications.

This tutorial on Servlet includes the following topics

Servlet Architecture

The following diagram describes the Servlet Architecture.

Servlet Architecture

Server Side Extensions are nothing but the technologies used to create dynamic web pages. In order to have the facility for dynamic web pages, web pages need a web server. In order to meet this requirement, the independent web server provides proprietary solutions in the form of APIs.

APIs help us to build programs that can run with a Web Server. Java Servlet is one of the components of APIs and sets standards for creating dynamic web applications in Java. Servlet Technology is not the only technology used for creating dynamic web pages. It is similar to other web extensions such as Common Gateway Interface(CGI) scripts and Hypertext Preprocessor (PHP). Java Servlets are most acceptable and serve the limitations of CGI.

Do Refer:

Common Gateway Interface

The Common Gateway Interface, normally referred to as CGI, was one of the first practical techniques for creating dynamic content. With CGI, a web server passes a certain request to an external program. The output of this program is then sent to the client in place of a static file.

CGI is not a programming language. It is an interface that allows input from a web browser(client) and produces an output in the form of an HTML page. A CGI script can be written in a variety of languages such as c,c++, PERL, FORTRAN, Visual Basic, and even java out of these PERL was most commonly used.

Advantages of CGI

1. CGI script works with any web browser as well as with most web servers running on Windows and Unix.

2. It is language-independent. It can be written in a variety of languages (C, C++, Perl, etc), so the developers don’t have to learn a new language.

Disadvantages of CGI

1. When a server receives a request that accesses a CGI program, It must create a new process to run the CGI program and then pass it to it. Creating a process for each such request requires time and significant server resources, which limits the number of requests a server can handle concurrently.

What is Servlet in Java 2

2. Even though a CGI program can be written in almost any language, the Perl programming language has become the predominant choice. writing a CGI script in Perl gives it a semblance of platform independence, but it also requires that each request start a separate Perl interpreter, which takes even more time and requires extra resources.

3. Another problem with CGI is that a CGI program cannot interact with the webserver, because it is running in a separate process.

Advantages of Servlet | What is the Use of Servlet in Java?

1. Servlets are highly portable across operating systems and across server implementation.

2. Servlets are also well suited for enabling client/server communications.

3. Servlets are platform-independent, the web application developed with servlet can be run on any web container such as Tomcat, Glassfish, JBoss server, etc.

4. Servlets provide better performance in terms of processing time, memory utilization because Servlets use the benefits of multithreading and for each request, a new thread is created.

What is Servlet in Java 3

5. Servlets invocation is highly efficient. Once a servlet is loaded, it remains in the server’s memory as a single object instance

6. Servlets are managed by JVM so no need to worry about memory leakage, garbage collection, etc.

7. Servlets are secure because it uses java language.

8. Servlets are protocol-independent they use any protocol like(FTP, HTTPS, NNTP, etc).

Difference Between Servlet and CGI

Servlet Common Gateway Interface(CGI)
It is portable and efficient It is not portable
Sharing of Data is Possible in Servlets. Sharing of Data is not possible.
These can directly communicate with the webserver. It can’t directly communicate with the webserver.
These are less expensive compared with CGIs CGIs are more expensive compared to Servlets.
Servlets can handle the Cookies. CGIs can’t handle the Cookies.

Servlet APIs

Servlets are build using two Packages.

javax.servlet(Basic)
javax.servlet.http(Advance)

Various Classes and Interfaces existing in these packages are as follows

Component Type Package
Servlet Interface javax.servlet.*
ServletRequest Interface javax.servlet.*
ServletResponse Interface javax.servlet.*
GenericServlet Class javax.servlet.*
HttpServlet Class javax.servlet.http.*
HttpServletRequest Interface javax.servlet.http.*
HttpServletResponse Interface javax.servlet.http.*
Filter Interface javax.servlet.*
ServletConfig Interface javax.servlet.*

What is Servlet Container in Java?

Servlet Container also known as Servlet Engine is an integrated set of objects and provides run time environment for JavaServlet Components. In Other Words, it is a system that manages the Java Servlet Components on top of Web Server to handle the Web Client Requests.

Services Provided by the Servlet Container

  • Network Services
  • Decode and Encode MIME based messages
  • Manage Servlet container
  • Resource management
  • Security Service
  • Session Management

Hashset initialization java – HashSet Class in Java with Example | Learn What is HashSet in Java & How to get started with it

HashSet Class in Java with Example

Hashset initialization java: The HashSet class in Java is the first implementation class of the Set interface. It is used to creates a collection that uses a hash table for storage. A hash table stores the information by using a mechanism called hashing. In the hashing technique, the informational content of the key is used to determine a unique value, called its hash code. The hash code is used as the index at which the data associated with the key is stored.

This Tutorial on Java HashSet Class Contains:

Creating a HashSet

For creating a HashSet Class in Java, firstly, we need to import the java.util.HashSet package.

After importing the package, take a look at the below & understand how we can create hash sets in Java.

// HashSet with 9 capacity and 0.75 load factor
HashSet<Integer> numerals= new HashSet<>(9, 0.75);

Here, we have built a hash set named numerals

See, the part new HashSet<>(9, 0.75). The first parameter is capacity, and the second parameter is load factor.

  • capacity: The capacity of this hash set is 9. Thus, it can store 9 elements.
  • loadFactor: The load factor of this hash set is 0.6. This means, whenever our hash set is filled by 60%, the elements are moved to a new hash table of double the size of the original hash table.

Default Capacity and Load factor

Probably to create a hash table without defining its capacity and load factor is possible. For example,

// HashSet with default capacity and load factor
HashSet<Integer> numbers1 = new HashSet<>();

By default,

  • the capacity of the hash set will be 16
  • the load factor will be 0.75

HashSet Hierarchy in Java

As you can observe in the below image of HashSet Java Hierarchy. The HashSet class performs the Set interface. Further, the Set interface inherits the Collection interface which ultimately extends the Iterable interface in a hierarchical order.

HashSet Class in Java with Example 1

Java HashSet vs HashMap

HashSet HashMap
Implements java.util.Set interface Implements java.util.Map
Allows a single null value Allows a single null key and any number of null values
HashSet use add() method for add or storing data HashMap use put() method for storing data
Doesn’t allow duplicate elements Doesn’t allow duplicate keys but you can store duplicate values
Stores data as objects Stores data in the form of key-value pair
HashSet needs just one parameter for its object initialization It needs two parameters (key, value) for its object initialization

Important Points about Java HashSet Class

  1. The underlying data structure for the hash set is the hash table.
  2. In HashSet, duplicates are not allowed.
  3. Insertion order is not preserved, elements are stored on the basis of their hash code.
  4. HashSet allows you to add heterogeneous elements.
  5. In HashSet, null insertion is possible.
  6. It implements a Serializable and Clonable interface but doesn’t implement a RandomAccess interface.
  7. HashSet is the best for search operations.

Difference between List and Set

A Set holds unique elements only whereas a List can hold duplicate elements.

Constructors of Java HashSet Class

There are 4 constructors are available in the Java HashSet class, which are described below:

1. HashSet(): This constructor creates a default hash set.

2. HashSet(int capacity): It is used to initialize the capacity of the hash set to the given capacity.

3. HashSet(int capacity, float load factor): This constructor is used to initialize the capacity of the hash table to the given capacity and the given load factor.

4. HashSet(Collection<? extends E> c): It is used to initializes the hash set by using the elements of collection c.

Methods of HashSet Class in Java

The HashSet Class offers different methods that permit us to perform several operations on the set.

1. boolean add(Element e): This method is used to add the element in the hash set.

2. void clear(): This method is used to remove all the elements from the hash set.

3. boolean contains(Element e): This method is used to check whether the specified element present in the hash set or not. If the element found in the hash set then it returns true otherwise it returns false.

4. boolean isEmpty(): This method is used to check the hash set is empty or not. If it is empty it returns true else returns false.

5. int size(): This method returns the number of elements from the hash set.

6. boolean remove(Element e): This method is used to remove the specified element from the hash set.

7. Object clone(): This method is used to returns a shallow copy of the hash set.

Insert Elements to HashSet Example

import java.util.*;
class hashSetExample
{
public static void main(String args[])
{
//creating a hash set
HashSet hset = new HashSet();

//adding elements in hash set
hset.add("Amit");
hset.add("Sumit");
hset.add("Rohit");
hset.add("Virat");
hset.add("Vijay");

//adding duplicate elements in hash set
hset.add("Amit");
hset.add("Virat");

//adding null value in hash set
hset.add(null);
hset.add(null);

//displaying hash set elements
System.out.println("Elements in the hash set are: " +hset);
}
}

Output:

Elements in the hash set are: [null, Rohit, Vijay, Amit, Sumit, Virat]

Access HashSet Elements

To access the elements of a hash set, we will make use of the iterator() method. To utilize this HashSet method, we must import the java.util.Iterator package. For illustration,

Access Java HashSet Example Program

Output:

HashSet: [2, 5, 6]
HashSet using Iterator: 2, 5, 6,

Remove Elements Java HashSet Example

import java.util.*;
class hashSetExample
{
public static void main(String args[])
{
//creating a hash set
HashSet hset = new HashSet();

//adding elements in hash set
hset.add("Amit");
hset.add("Sumit");
hset.add("Rohit");
hset.add("Virat");
hset.add("Vijay");
hset.add(null);
System.out.println("Hash Set elements are: " +hset);

//removing a specific element from hash set
hset.remove("Amit");
System.out.println("After removing(Amit) HashSet element is: " +hset);

//removing all elements from hash set
hset.clear();

//displaying hash set elements
System.out.println("Elements in the hash set are: " +hset);
}
}

Output:

Hash Set elements are: [null, Rohit, Vijay, Amit, Sumit, Virat]
After removing(Amit) Hash Set element is: [null, Rohit, Vijay, Sumit, Virat]
Elements in the hash set are: []

Finding Elements in Hash Set Java HashSet Example

import java.util.*;

class hashSetExample

{

public static void main(String args[])

{

//creating a hash set

HashSet hset = new HashSet();

//adding elements in hash set

hset.add("Amit");

hset.add("Sumit");

hset.add("Rohit");

hset.add("Virat");

hset.add("Vijay");

//find the number of elements in the hash set

int elements = hset.size();

System.out.println("The size of the hash set is: " +elements);

}

}

Output:

The size of the hash set is: 5

Java HashSet Example on Converting a Hash Set into a List/ArrayList

import java.util.*;
class hashSetExample
{
public static void main(String args[])
{
//creating a hash set
HashSet hset = new HashSet();

//adding elements in hash set
hset.add("Amit");
hset.add("Sumit");
hset.add("Rohit");
hset.add("Virat");
hset.add("Vijay");
System.out.println("Hash Set element is: " +hset);

//converting a hash set into an array list.
List alist = new ArrayList(hset);
System.out.println("ArrayList is: " +alist);
}
}

Output:

Hash Set elements are: [Rohit, Vijay, Amit, Sumit, Virat]
ArrayList is: [Rohit, Vijay, Amit, Sumit, Virat]

Selenium ide tutorials for beginners – Selenium IDE Tutorial For Beginners | What Is Selenium IDE

Selenium Python – Selenium IDE

Selenium ide tutorials for beginners: In this chapter, we will discuss the Selenium IDE component. This component allows us to record and playback our tests. It is an integral component of the Selenium project and has been recently upgraded and brought back into function with the help of the organization Appiitools.

Selenium IDE, also known as SIDE stands for Selenium Integrated Development Environment. It is one of the four projects of the Selenium ecosystem. The earlier version of Selenium IDE worked only on the Firefox browser. But the changes in the Firefox browser from version 55 didn’t allow Selenium IDE integration. At this juncture, Appiitools helped the Selenium community with a group of dedicated engineers (https://github.com/seleniumHQ/selenium-ide/graphs/ contributors) and brought back Selenium IDE. The current version supports both Firefox and Chrome browsers.

Structure

  • Installing Selenium IDE • Walkthrough of the demo application
  • Creating our first test
  • Selenium IDE commands

Objective

The Selenium IDE component is used to record and play backtests. The current version, which supports both Firefox and Chrome browsers, has a rich feature list. It now allows running tests in parallel, supports JavaScript execution, allows usage of if conditions, and many such cool things. To know more about it, read the article available here:

https://applitools.com/blog/why-Selenium-ide-20197utm_referrer=https://www.google.com/

Installation of Selenium IDE

To install Selenium IDE, we have to follow the below-mentioned instructions:
1. Open the Chrome browser and follow this link:
https://www.seleniumhq.org/selenium-ide/
2. Here, we need to select the choice, Chrome or Firefox download.
3. It will open a new browser window, with the option asking Add to Chrome as shown in the following screenshot:

Selenium Python - Selenium IDE chapter 2 img 1

4. You need to select it.
5. It will launch a popup, asking permission. Select Add extension as shown in the following screenshot:

Selenium Python - Selenium IDE chapter 2 img 2

6. You will now be able to see the Selenium IDE icon in your browser menu bar. N

After installing the Selenium IDE, we need to have a look at a demo web application. We will need this application to understand a few concepts of test automation using Selenium. So let us get introduced to it.

Introduction to demo web application

We will consider a demo web application, which is an e-commerce website. As we learn the concepts of test automation with Selenium using Python as a programming language, we will use functional flows from the web application. We will also look at a few other web applications as we learn to handle some specific Html elements and deal with some specific scenarios.

The URL of the demo application is http://practice.bpbonline.com/ catalog/index.php
As you follow the URL, you will see the following screen:

Selenium Python - Selenium IDE chapter 2 img 3

Following are some of the specific functional flows in the application:

  • Register the user
  • Login and logout of the user
  • Change profile of the user
  • Change the password of the user
  • Buy product
  • Search product

From the previous list of application business scenarios, we will take the login-logout business scenario as a sample one for our first record and playback script in Selenium IDE. Record script basically means with the help of Selenium IDE, we will capture the user actions as we perform the steps to login and then log out from the application. These will be captured by the Selenium IDE, as commands. It will then be played back, where Selenium IDE will launch the browser and will be able to perform the exact steps to log in and log out of the application without any user intervention.

Let’s perform the following steps for login-logout:
1. Open the application using the URL: http://practice. bpbonline.com/catalog/index.php
2. Click on the My Account link.
3. Fill in the user details; you can use the following user credentials:

  • Username: bpb@bpb.com
  • Password: bpb@123

Or you can also create your own account, by registering yourself and then using those credentials.
4. Click on the Sign-in button
5. Click on the Log Off link
6. Click on the Continue link
Please note the above scenario is not a test case, as we have added no steps for the validation. There are only test steps.

Record and playback in Selenium IDE

The following are the steps we need to perform for recording and playing back in Selenium IDE:
1. Open Chrome browser.
2. On it, click on the Selenium IDE icon. It will popup Selenium IDE window as shown in the following screenshot:

Selenium Python - Selenium IDE chapter 2 img 4

3. Here, we will select Record a new test in a new project.
4. Provide a project name on the next screen.
5. Then in the next screen, provide the base URL for recording:

Selenium Python - Selenium IDE chapter 2 img 5

6. Click here on START RECORDING.
7. This will launch the browser with the application URL, and a message Selenium IDE is recording… Now, whatever steps we perform on the browser, will all be captured by the IDE. Check the following screenshot:

Selenium Python - Selenium IDE chapter 2 img 6

7. After performing all the steps, close the browser, and on the Selenium IDE, click the OP (stop button).
8. Provide a name to the test, and save the project at a location in your system.
9. After the login logout steps are captured, your text should look as follows:

Selenium Python - Selenium IDE chapter 2 img 7

It could be possible that Selenium IDE may capture some other locator value for the same object which you see in the target field, which is absolutely fine, as long as you are able to replay the test successfully.

There could be some other extra steps captured as Selenium IDE captures every mouse action, we need to delete those extra steps and only have those steps that match our manual action.

Structure of Selenium IDE Test

If we look at the above image, there are three columns that form a Selenium IDE test:
• Command, which provides information of the action being performed.
• Target, which talks about the object on which the action is to be performed.
• Value, which talks about the data which will be used in the test.
The commands of Selenium IDE fall under three categories, as follows:
• Action: Those commands, which change the state of the application.
• Assertion: Those commands which verify the state of the application after it is performed. There are two types of assertion commands that are as follows:

  1. Verify: These commands, if they fail, still allow execution of the next step in the test case.
  2. Assert: These commands, if they fail, don’t allow the execution of the next step in the test case.

• Accessor: Those commands which allow storage of value, or creation of variables to be used in the test.

Let us write the login-logout scenario, this time with the validation steps:

  1. Open the application.
  2. Click the My Account link.
  3. Type the E-mail address and Password.
  4. Click the Sign In button.
  5. Verify the My Account Information text on the screen.
  6. Click on the Log Off link.
  7. Click on the Continue link.
  8. Verify Welcome to BPB Online text on the screen.

To record the above scenario, we will perform the same steps as we did for the login-logout one, except for steps 5 and 8, where we will perform the following.
9. Add the Command verify text during the recording after you have logged in. Refer to the following screenshot:

Selenium Python - Selenium IDE chapter 2 img 8

10. Now we will select the Target for that we click on the icon
[↵]and highlight and click the element, whose text we need to capture for verification. Refer to the following screenshot:

Selenium Python - Selenium IDE chapter 2 img 9

11. We copy the text from here and put it in the Value field. So finally, our command would look like the following:

Selenium Python - Selenium IDE chapter 2 img 10

12. We will perform a similar action for step 8.
13. Complete the steps of recording, and save the test for playback. As you playback the test, you will see all the steps in green. Now let us try to see the action of failure by changing the text of My Account Information to Dunk. We will find out that although the test gets executed, reports failure on the verification step. The following screenshot shows the behavior:

Selenium Python - Selenium IDE chapter 2 img 11

14. Now, for the same test, if we change the command from verifying the text, to assert text We will see that the execution will get halted at the step of failure. This is shown as follows:
in green. Now let us try to see the action of failure by changing the text of My Account Information to Dunk. We will find out that although the test gets executed, reports failure on the verification step. The following screenshot shows the behavior:

Selenium Python - Selenium IDE chapter 2 img 12

14. Now, for the same test, if we change the Command from verifying ‘ text, to assert text we will see that the execution will get halted at the step of failure. This is shown as follows:

Selenium Python - Selenium IDE chapter 2 img 13

So there are three states of execution here:

  • Green: All pass
  • Red: Fail
  • White: Not executed

Conclusion

In this chapter, we discussed the Selenium IDE component. We saw how we could use it for recording and playing backtests. We could use Selenium IDE for proofing concepts, to see if our application supports Selenium or not. Sometimes we struggle to find a locator for an object, in such cases recording the scenario in Selenium IDE is also helpful. In our next chapter, we will discuss the concept of locators, what techniques Selenium uses to recognize objects on web applications.

Related Articles: