Yawn, teach me how to write my first Java program, asshat!

How does one write their first java program?

We are going to make our computer say,

Hello Human, I am your servent..

I’ll do as you please!

I bow down to you master. 

But (I like big butts and I cannot lie, sorry I can’t stop singing that song).. but before that, we need to do some shit called “setup” for writing our first java program.

Your first Java program is going to look lengthy and wordy compared to other programming languages such as Python. So, I say fuck setting up your computer for now. Heck, Java’s “hello world” scares off people even if it is dumb easy just due to sheer length. Now, if I made you download a bazillion files and made you follow 10 different step to set up things, you are going to run the fuck away. 

My intention is to show you, Java is a fucking easy language. It’s not C++ which you’re only qualified to write if you’re a nerd with no sex life (ba dum diss). So, I suggest you go over here. 

An online coding environment will save us from so many steps that will come between you and your code. Fuck that for now. 

You talk a lot, show me the code 

Okay. Just in a bit..

See.. a java program has a structure to it that looks like,

java program structure

So, a java program is a bunch of thingies called classes that have code inside. That’s all to it for now. 

How does one define a class?

All you need to do is use a class keyword. 

class myClass{

//code

}

Okay, how does one write the program you mentioned above?

public class IAmTheBoss {
public static void main(String args[]) {
System.out.println("Hello Human, I am your servent..");
System.out.println("I'll do as you please!");
System.out.println("I bow down to you master.");
}
}

In JDoodle it’ll look like this if you hit the execute button. 

first java program

Explain the code, please

I knew you’d ask. Let’s break down the code. 

Iteration 1

public class IamTheBoss{

}

This is our class definition. The public here is something called access modifier. Ignore what that means for now. Just think of it like our class can be accessed from anywhere within the same folder if it’s set to public.

Iteration 2

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

} // main ends here
} //class ends here

Java programs require something called the “main method” to run. The class that has this main method is called the main class. You need one main class in your java program.

Now methods are synonymous with functions. But if you don’t know what “function” means don’t sweat it. We’ll have a whole article on that. 

public static void main(String args[])  is a way to define the main method in java. Now, each of the words there such as static, void, String etc. have certain meanings which we’ll explore in some other article. For now, just understand that it’s needed to define the main method thingy. You don’t need to rote memorize it either. If you type main and press tab on Jdoodle, it’ll generate the code for you. 

Iteration 3

public class IAmTheBoss {
public static void main(String args[]) {
System.out.println("Hello Human, I am your servent..");
System.out.println("I'll do as you please!");
System.out.println("I bow down to you master.");
}
}

System.out.println displays the output on the screen. If you type println and press tab on Jdoodle then it’ll generate the whole thing for you. println means the thing you want to display is going to be printed on a new line. So, you could do System.out.print but everything would be on the same line. 

There’s a reason behind x.y.z kinda shit in Java. It means z exists inside y which exists inside x. So, System.out.print thingy means that the “print” function resides inside “out” which further resides inside the “system”. 

So, what else can I do?

I suggest you play around with Jdoodle. And see what works and what does not. And subscribe/bookmark to this blog to read more articles on Java.

What the hell is Java programming language?

What is Java? Isn’t it coffee or something?

The Java(TM) is programming language which is a bit different from coffee java as you might have guessed. 

If you search for “Java” in Wikipedia.org, it’ll answer the following

Java is an island of Indonesia. At about 138,800 square kilometers, the island is comparable in size to England.

And if you click see Java (programming language), it’ll return

Java is a general-purpose computer programming language that is concurrent, class-based, object-oriented. It is intended to let application developers “write once, run anywhere” (WORA) meaning that compiled Java code can run on all platforms that support Java without the need for recompilation.

The first definition seems like it was written in English. It’s easy to understand. The second one seems like it was written by someone whose third or fourth language is English. It seems like it was written by someone who’s been a professional Java programmer for a while and has lost the sense of how new students find it hard to decipher the technical jargon.

But it’s still more readable than what’s in the official docs at least.  You probably skimmed through it  and are like “Okay.. so it’s a programming language and you can write it once and run it anywhere whatever that means.” And some words such as “concurrent” flew right over your head. 

If you have never programmed before. Or you just had some introductory QBasic and C shit. A lot of words in there don’t fucking make sense. 

What in the hell is a general-purpose programming language? Is it another way of saying that it’s a mainstream programming language and not for hipsters? 

What the hell is object oriented? Does it mean that Java is sexist and treats women as objects?

What is the actual hell is recompilation now? And this recompilation thing, is it that bad? Why is it bad? Maybe it’s good. Who the fuck knows?

 

Let’s define Java the way we’d like to

All those jargony words. They mean something in their own context. Those are some fancy features of the language which we don’t need to understand right now so fuck it. 

I’d say .. 

Java helps humans write instructions for machines such your laptop, mobile phone etc. so that we can make the machine do whatever the hell we want to. Like every other programming language in the observable universe.  

Sure, it has its own way of doing things with those fancy sounding words. And this “my way or the highway” attitude of Java can be a gift or a curse depending on the situation. It can be a gift because you don’t have to think much about things yourself. The language will dictate how you write and organize your code. It can be a curse when you feel like thinking outside of Java’s opinionated box. 

 

Enough Talk. How do I make this Java thingy make my computer do something for me? 

Well, we’ll look into that in the next post. Be patient. We’ll use and abuse this so-called programming language together to make our computers do shit for us. Until then chug some coffee and call Oracle service center and ask them if chugging a mug of coffee is the proper way to download Java. 

 

 

 

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()

  • 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

  • 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. 

 

  • 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.