Java AWT viva questions with answers

  1. What is AWT?
    Java AWT (Abstract Windowing Toolkit) is an API to develop GUI or window-based application in java. It contains numerous classes and methods that allow you to create windows and simple controls. It was Java’s first GUI framework, and it has been part of Java since version 1.0.

  2. Where are AWT classes contained? / Which package contains AWT classes? 
    The AWT classes are contained in the java.awt package. It is one of Java’s largest packages.
  3. What is a component?
    By definition, the subclass of a java.awt.Component class is known as a component. A component can be a Button or TextField etc. Component class lies at the top of AWT hierarchy. Component class is an abstract class that encapsulates all of the attributes of a visual component.

  4. What is an abstract class ?
    A class that is declared with abstract keyword, is known as abstract class in java. It can have abstract and non-abstract methods (method with body).
  5. Are menus subclass of a component?
    No. Except for menus, all user interface elements that are displayed on the screen and that interact with the user are subclasses of Component.

  6. What is a component?
    By definition, the subclass of a java.awt.Container class is known as a container. A container can be a Frame or Applet or Dialog box etc. A container holds the components. If a button is to be displayed to the user, it must be added to a container.
  7. What is a container class? 
    The Container class is a subclass of Component.

  8. What is the super class of all containers?
     java.awt.Container.
  9. What is a window?
    The window is the container that has no borders and menu bars. You must use frame, dialog or another window for creating a window. Generally, you won’t create Window objects directly. Instead, you will use a subclass of Window called Frame.

  10. What is a panel? 
    The Panel class is a concrete subclass of Container. Like window panel also does not contain a title bar, menu bar, or border. 

    To have a greater flexibility on the arrangement of components, panels are extensively used with layout managers. Components are added to panel and panel, in turn, can be added to a container. That is, a panel can work like a container and a component. As container, components can be added to it and as a component, panel can be added to a frame or applet.

  11. What are subclasses of the component?
    Subclasses of Container include Frame, Panel, and Applet which is a subclass of Panel.
  12.  Among the standard classes in Java are Container and Component. In order to create a GUI, the programmer uses subclasses of these two classes. What are some examples of subclasses of Container and Component? What is the essential difference between Containers and Components?

    Java’s Component class represents visual elements of a Graphical User Interface. Its subclasses include Button, Checkbox, TextField, Choice, and Canvas. The Container class is another subclass of Component. A Container is a component that can contain other components (including other containers). This is the essential difference between containers and other types of component. Subclasses of Container include Frame, Panel, and Applet.

  13. How to add other components to a panel?
    Other components can be added to a Panel object by its  
    • add( ) method (inherited from Container).

  14. How to position components in a Panel? 
    setLocation( ), setBounds() methods defined by Components class can be used to position components. 

  15. How to resize components?
    setLocation( ) and setPreferredSize( ) methods. 

  16. What is a Frame? 
    Frame encapsulates what is commonly thought of as a “window.” It is a subclass of Window and has a title bar, menu bar, borders, and resizing corners. The Frame is the container that contains title bar and can have menu bars. It can have other components like button, textfield etc.

  17. Mention any 4 methods of component class? 
    public void add(Component c) -> inserts a component on this component.
    public void setSize(int width,int height) -> sets the size (width and height) of the component.
    public void setLayout(LayoutManager m) -> defines the layout manager for the component.
    public void setVisible(boolean status) -> changes the visibility of the component, by default false.

  18.  What are the two ways to create a frame in awt? 
    By extending Frame class (inheritance)
    By creating the object of Frame class (association) 
  19. What are the constructors of Frame? 
    Frame( ) throws HeadlessException  -> creates a standard window that does not contain a title.
    Frame(String title) throws HeadlessException -> creates a window with the title specified by title.
  20. Constructors of setSize() ?
    • void setSize(int newWidth, int newHeight)
    • void setSize(Dimension newSize)

      The new size of the window is specified by newWidth and newHeight, or by the width and height fields of the Dimension object passed in newSize. The dimensions are specified in terms of pixels.

  21. How to obtain a current size of a window? 
    The getSize( ) method is used to obtain the current size of a window.

Java Servlet Example 3

3. Develop a servlet that displays the number of visits on the servlet. Also display the client’s hostname and IP address, as shown in Figure. Use an instance variable to store count. When the servlet is created for the first time, the count is 0. count is incremented every time the servlet’s doGet method is invoked. When the Web server stops, the count is lost.

getRemoteHost()

getRemoteAddr()

Screen Shot 2018 03 09 at 3.56.54 PM - Java Servlet Example 3

  • VisitorServlet.java (put it in the “src” folder)
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; @WebServlet("/VisitorServlet") public class GreetingServlet extends HttpServlet {
static int count = 0;     
protected void doGet(HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException {
response.setContentType("text/html");         
PrintWriter out = response.getWriter();         
// client's IP address         
String remoteAddr = request.getRemoteAddr();         
// client's hostname         
String remoteHost = request.getRemoteHost();         
if (count == 0){             
out.print("<h3>");             
out.print("Welcome to the fist Time </h3>");             
count++;         
} else {            
 out.print("<h3>You have visited " + count + " times");         
    count++;             
out.print("</h3>");      
   }         
out.println("Host name: ");         
out.print(remoteAddr);       
  out.println("<br>");         
out.println("IP address:");         
out.print(remoteHost);        
 out.close();    
 } }
  • index.jsp(put it in the “web” folder) 
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
 <html>
   <head>
     <title></title>
   </head>
   <body> </body>
 </html>
  • web.xml(put it in the “WEB-INF” folder which resides inside the “web”.) 

      Note: This step is not mandatory. You may choose not to do it. And the program will still run. 

<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, 
Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd"> 
<web-app> 
    <display-name>myweb</display-name> 
    <!-- Servlet Definitions  --> 
   <servlet> 
      <servlet-name>VisitorServlet</servlet-name> 
      <servlet-class>VisitorServlet</servlet-class>  
  </servlet> 
<!--   Servlet Mappings   --> 
   <servlet-mapping> 
      <servlet-name>VisitorServlet</servlet-name> 
       <url-pattern>/VisitorServlet</url-pattern>  
  </servlet-mapping> 
</web-app>  

Note: To run this program, type inlocalhost:8080/VisitorServlet the browser URL. Click here if you don’t know how to set up a servlet project in NetBeans.

 

 

Java Servlet Example 2

HTML Form

Screen Shot 2018 03 09 at 4.00.55 PM - Java Servlet Example 2 Screen Shot 2018 03 09 at 4.01.09 PM - Java Servlet Example 2

  • index.jsp (put it in the “web” folder) 

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  <title>Calculator</title>
</head>
<body bgcolor="aqua">

<form method="post" action="GreetingServlet">


  <h3 style="text_align:center;">Choose an operation:
    <input type="radio" name="r1" value="add" />addition
    <input type="radio" name="r2" value="sub" />subtraction
    <input type="radio" name="r3" value="mul" />multiplication
    <input type="radio" name="r4" value="div" />division
  </h3>

  </label>
  <label>Choose 1<sup>st</sup> number:</label>
  <input type="text" name="n1" />
  <br>
  <label>Choose 2<sup>nd</sup> number:</label>
  <input type="text" name="n2" />
  <br>
  <label>
      <input type="submit" value="Submit" style="background-color: hotpink">
  </label>

</form>
</body>
</html>

  • FormServlet.java (put it in the “src” folder) 

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebServlet("/FormServlet")
public class GreetingServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

   public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try
        {
            response.setContentType("text/html");
            PrintWriter out= response.getWriter();
            out.println("<body style='background-color:black;color:yellow;'>");
            out.println("<h3 style='color:red;'>Output of your inputs </h3>");
            int a1= Integer.parseInt(request.getParameter("n1"));
            int a2= Integer.parseInt(request.getParameter("n2"));
            if(request.getParameter("r1")!=null)
            {
                out.println("<p>Addition</p>"+(a1+a2));
            }
            if(request.getParameter("r2")!=null)
            {
                out.println("<p>Subtraction</p>"+(a1-a2));
            }
            if(request.getParameter("r3")!=null)
            {
                out.println("<p>Multiplication</p>"+(a1*a2));
            }if(request.getParameter("r1")!=null)
        {
            out.println("<p>Division</p>"+(a1/a2));
        }
        }
        catch(Exception e)
        {
            System.out.println("error" + e.getMessage());

        }
    }
}

Note: To run this program type: localhost:8080 in the browser URL. 

Click here if you don’t don’t how to set up a NetBeans servlet project. 

Java Servlet Example 1

Write a servlet to display a table that shows ODD numbers and EVEN numbers from number 1 to 10, as shown in the figure below. 

Screen Shot 2018 03 09 at 4.02.12 PM - Java Servlet Example 1

 

  • EvenOddServlet.java (put it in the “src” folder) 

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class EvenOddServlet extends HttpServlet {
    public void doGet(HttpServletRequest req, HttpServletResponse res) throws 
ServletException, IOException {
        res.setContentType("text/html");
        PrintWriter pw = res.getWriter();
        // Send the message
        pw.println("<table border='1'>");
        pw.println("<tr>");
        pw.println("<th style='background-color:red;'> Even </th>");
        for (int i = 1; i <= 10; ++i) {
            if (i % 2 == 0) {
                pw.println("<td>" + i + "</td>");
            }
        }
        pw.println("</tr>");
        pw.println("<tr>");
        pw.println("<th style='background-color:red;'> Odd </th>");
        for (int i = 1; i <= 10; ++i) {
            if (i % 2 != 0) {
                pw.println("<td>" + i + "</td>");
            }
        }
        pw.println("</tr>");
        pw.println("<table>");
    }
}

  • index.jsp (put it in the “web” folder) 

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title></title>
  </head>
  <body>

  </body>
</html>

  • web.xml (put it in the “WEB-INF” folder which resides inside the “web”) 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd">

<web-app>
    <display-name>myweb</display-name>

    <!-- Servlet Definitions  -->
   <servlet>
      <servlet-name>EvenOddServlet</servlet-name>
      <servlet-class>EvenOddServlet</servlet-class>
   </servlet>
<!--   Servlet Mappings   -->
   <servlet-mapping>
      <servlet-name>EvenOddServlet</servlet-name>
       <url-pattern>/EvenOddServlet</url-pattern>
   </servlet-mapping>
 </web-app>

 Note: To run this go to your browser and type: localhost:8080/EvenOddServlet

If you don’t know how to set up a servlet project in NetBeans, you may use this video as a reference:

 

java servlet

What the fuck is a java servlet?

 

Remember Java’s write once, run anywhere bullshit? Run anywhere…  Yeah, well Java programs can run on anything that has JVM. A toaster with JVM can run Java. An iPhone without it cannot. TAKE THAT JAVA! Well, it hasn’t stopped java developers to develop apps on iPhone using Java though. You see, this magical JVM thingy works and is fast enough because it is written in C/C++ for that specific OS. But the fucking pointers suck the life out of you so let’s stick to Java for now. 

 

WHAT THE FUCK IS A JAVA SERVLET THEN? 

As you’ve noticed I’ve just beat around the bush and haven’t still answered what the fuck Java Servlet is till now. Well, what if you wanted to leave the comfort of your desktop and mobile phone and wanted to develop apps for the good OL‘ web. Could you still do that? Now, what fun is it … if a language claims to run everywhere and can’t even run on the web. That would suck, right? 

Well for all the Java evangelists, the good news is that Java comes with full-fledged Servlet API which lets you build web apps without much hassle, unlike non-standard CGI thingy that Java used to have which we are not going to talk about because fuck it. 

 

WHAT? HOW THE HELL, DOES IT DO THAT? 

Think of a Servlet as a Java program or a Java class that is executed within the scope of Servlet containers (or web containers). You must be thinking, hold on their chief? What the fuck is a Web container now? Shit like Tomcat, Jetty etc. allow handling client requests and server responses and they are Web containers. 

Servlets use GET and POST request thingies to be able to snatch data from users. They can handle session and cookies thingies. They can process the motherfucking data and output the data in both text and binary formats such as XML, HTML, pdf, gif etc. They may use a thingy called JSP in many cases which we’ll talk about some other time.