Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Monday, 29 March 2021

Methods in JAVA Language

 In general, a way may be thanks to perform some task. Similarly, the tactic in Java may be a collection of instructions that performs a selected task. It provides the reusability of code. we will also easily modify code using methods. during this section, we'll learn what's a way in Java, sorts of methods, method declaration, and the way to call a way in Java.


What is Method in JAVA language? 

A method may be a block of code or collection of statements or a group of code grouped together to perform a particular task or operation. It is wont to achieve the reusability of code. We can write a method once and use it many times. We don't require to write down code again and again. It also provides the straightforward modification and readability of code, just by adding or removing a piece of code. The method is executed only we call or invoke it.
The most important method in Java is that the main() method.


Method Declaration in JAVA. 

The method declaration provides information about method attributes, like visibility, return-type, name, and arguments. It has six components that are known as method header, as we have shown in the following figure.



Method Signature: Every method has a method signature. It is a part of the method declaration. It includes the method name and parameter list.

Access Specifier: Access specifier or modifier is that the access sort of the tactic. It specifies the visibility of the method. Java provides four types of access specifier:

Public: The method is accessible by all classes when we use public specifier in our application.

Private: once we use a personal access specifier, the tactic is accessible only within the classes during which it's defined.

Protected: once we use protected access specifier, the tactic is accessible within an equivalent package or subclasses during a different package.

Default: once we don't use any access specifier within the method declaration, Java uses default access specifier by default. It is visible only from an equivalent package only.

Return Type: Return type may be a data type that the tactic returns. It may have a primitive data type, object, collection, void, etc. If the tactic doesn't return anything, we use void keyword.

Method Name: it's a singular name that's wont to define the name of a way . It must be like the functionality of the tactic . Suppose, if we are creating a way for subtraction of two numbers, the tactic name must be subtraction(). A method is invoked by its name.

Parameter List: it's the list of parameters separated by a comma and enclosed within the pair of parentheses. It contains the data type and variable name. If the method has no parameter, left the parentheses blank.

Method Body: It is a part of the method declaration. It contains all the actions to be performed. It is enclosed within the pair of curly braces.

Wednesday, 26 September 2018

Objects

An Object represents an entity within the world like someone, thing or concept etc. An object is identified by its name. An object consists of the subsequent two things:
  • Properties: Properties are the characteristics of an object. 
  • Functions: Functions are the action which will be performed by an object. 

Examples:

Some samples of objects of different variious  are as follows:

  • Physical Objects: 

           Vehicles likes  cars, bus, trucks etc.
           Electrical components
           Elements of Computer-User Environment

  • Windows

          Menus
          Graphics objects
          Mouse and Keyboard

  • User-defined Data Types

          Time
         Angles

Properties of Object: 

The characteristics of an object are called its properties or attributes. Each object has its own properties. These properties are accustomed to describe the object. For instance, the properties of an object. Person can be as follows:

  • Name 
  • Age 
  • Weight 

The properties of an object Car is be as follows:

  • Color 
  • Price 
  • Model 
  • Engine power 

The set of values of the attributes of a selected object is named  its state. It means that the state of an object may be determined by the values of its attributes.
Functions of Object:
An object can perform different tasks and actions.The actions that may  be performed by the an object referred to as functions and methods. For the

Tuesday, 25 September 2018

Java Servlet


Java servlet are programs that run on Web or Application server and act as a middle layer between an invitation coming from an internet browser or other client and database or applications on the HTTP Server.

Simple Servlet: 

import java.io.*;
import javax.servlet.* ;

public class HelloServlet extends GenericServlet{

    public void service (ServletRequest request, ServletResponse response)
        throws ServletException, IOException {

           response.setContentType("text/html");
           PrintWriter pro = response.getWriter();
           pw.println("<B> Hello! </B>");
           pw.close();

      }
}

Writing Servlet: 

Servlet Types: 


Servlet related classes are included in two main Packages.
  • javax.servlet
  • javax.servlet.http
Every servlet must implements the javax.       
 servlet.Servlet interface, it contains the servlet's life cycle method. 

In order to write down your own servlet, you'll be  subclass from GenericServlet or HttpServlet 

Genereric Servlet class 

  • Available in javax.servlet package 
  • Implements javax.servlet.Servlet
  • Extend your class from this class if you're curious about writing protocol independent servlet.

HttpServlet Class: 

  • Available in javax.servlet.http package
  • Extends from GenericServlet class            
  • Add functionality for writing Http specific servlet as compared to GenericServlet. 
  • Extends your class from HttpServlet, if you would like to write down http based Servlet. 
 
     

GET: 

       Request a page from server. This is the normal request used when browsing web pages.

POST: 

         This request is used to pass information to the server. Its most common use is with HTML forms.

PUT: 

       Use to put a replacement webpage on a server.

DELETE: 

           Used to delete a webpage from the server.

Reading HTML from Data using Servlet:

Types of data send to a WebServer

  • From Data
  • HTTP Request Header Data. 
The HTTPServletRequest object contain three main methods for extracting from data submitted by the user.

  1.  getParameter(String name): 

  • used to retrieve single from parameter and return String like  name specified. 
  • Empty String is returned in the case when user does not enter within the specified form field.   

     2.  getParameterValue(String name): 

  • return an array of string object containing all of the given values of the given request parameter. 
  • if the name specified does not exist, null is returned. 

     3.   getParameterNames(): 

  • it returns enumeration of string object containing the names of the parameters that come with the request. 
  • if the request has no parameters, the function return an empty enumeration.



Monday, 24 September 2018

Java Servlets

Assume that a client enter his/her name and password in a form and sends a request to servlet. Servlet 1  will creates the connection  with database and verify the user information from the database. Table (login) show success message on console, if name found otherwise enter the information of client in table (log) with current system date and display sorry message. 


HTML Form:

<!DOCTYPE html>
<html>
    <head>
        <title>HTML Form</title>
    </head>
    <body>
        <form name="form1" method="post" action="Servlet1">
            Username: <input type="text" name="t1" /><BR><BR>
            Password: <input type="password" name="t2" /><BR><BR>
            <input type="submit" name="Login" value="Login">
        </form>
    </body>
</html>

Servlet1:

import java.io.*;
import java.sql.*;
import javax.servlet.http.*;
public class Servlet1 extends HttpServlet {
    public void doPost(HttpServletRequest req, HttpServletResponse res) {
        try {
            PrintWriter pw = res.getWriter();
            res.setContentType("text/html");
            boolean flag = false;
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            Connection cn = DriverManager.getConnection("Jdbc:Odbc:Exam");
            String sql = "select * from login";
            PreparedStatement st = cn.prepareStatement(sql);
            ResultSet rs = st.executeQuery();
            String s1 = req.getParameter("t1");
            String s2 = req.getParameter("t2");
            while (rs.next()) {
                if ((rs.getString(1).equals(s1)) && (rs.getString(2).equals(s2))) {
                    flag = true;
                }
            }
            if (flag) {
                pw.print("Login Succeeded!");
            } else {
                pw.print("Sorry... Login does not Succeeded!");
                String sql1 = "SELECT * FROM log";
                PreparedStatement pStmt = cn.prepareStatement(sql1, ResultSet.TYPE_SCROLL_INSENSITIVE,     ResultSet.CONCUR_UPDATABLE);
                ResultSet rs1 = pStmt.executeQuery();
                rs1.moveToInsertRow();
                rs1.updateString("username", s1);
                long time = System.currentTimeMillis();
                java.sql.Date date = new java.sql.Date(time);
                String s = date.toString();
                rs1.updateString("system_date", s);
                rs1.insertRow();
                cn.close();
            }
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

Output:

REMOTE METHOD INVOCATION (RMI) | JAVA

Create an RMI based Examination server of Punjab University that will display the status of a student (Pass/ Fail) upon accept the roll number from client. The server will take "rollNo" of type string as an input from client and can will return his/her status. Suppose you have got find (String) method on server side for the searching of student's status. The client should display the status on console. 


RMI Interface:

import java.rmi.*;
public interface ExamInt extends Remote
{
  String find(String roll_n) throws RemoteException ;
}

Interface Implementation:

import java.rmi.server.*;
import java.rmi.*;
import java.sql.*;
public class ExamServerImpl extends UnicastRemoteObject implements ExamInt
{
public ExamServerImpl() throws RemoteException
{
                             }
//implementation of find(String) not required in asked question...
public String find(String roll_no) throws RemoteException
{
String status;
status=Examjdbc(roll_no);
return status;
}
public String Examjdbc(String r_no) throws RemoteException
{
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection cn=DriverManager.getConnection("Jdbc:Odbc:mobileDSN");
Statement st=cn.createStatement();
ResultSet rs=st.executeQuery("Select *from status");
while(rs.next())
{
if(rs.getString(1).equals(r_no))
return rs.getString(2);
}

}
catch(Exception e)
{
System.out.println(e);
}
return null;
}
}

Server:

import java.net.*;
import java.rmi.*;
public class ExamServer
{
public static void main(String args[])
{
try{
ExamServerImpl obj= new ExamServerImpl();
Naming.rebind("ExamServer",obj);
}

catch(Exception e)
{
System.out.println("Exception "+e);
}
}
}

Client:

import javax.swing.*;
import java.rmi.*;
import java.net.*;
public class ExamClient
{
public static void main(String args[])
{
try{
    String examServerURL = "rmi://" + args[0] + "/ExamServer";
ExamInt obj= (ExamInt)Naming.lookup(examServerURL);
String r_n=JOptionPane.showInputDialog("Enter Roll number:");
String Status=obj.find(r_n);
System.out.println("You are " + Status);
}
catch(Exception e)
{
System.out.print("Exception " + e);
}
}

Output:


Remote Method Invocation (RMI) | Java

You have to build a mobile outlet server based on RMI. Client will generate a call to getPrice(string mobilename) to server class and on server you will get the name of mobile. Create a connection to Database and return the price of that particular mobile to client.
Perform all steps required for complete RMI application.
DB Name: mobile.mdb                              DSN name: mobile


Interface:

import java.rmi.*;
public interface MobileInterface extends Remote
{
double getPrice(String m_name) throws RemoteException;
}

Implementation:

import java.rmi.server.*;
import java.rmi.*;
import java.sql.*;
public class MobileServerImpl extends UnicastRemoteObject implements MobileInterface {
    public MobileServerImpl() throws RemoteException {
    }
    public double getPrice(String m_name) throws RemoteException {
        double price;
        price = Mobilejdbc(m_name);
        return price;
    }
    public double Mobilejdbc(String m_nam) throws RemoteException {
        double p;
        try {
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
            Connection cn = DriverManager.getConnection("Jdbc:Odbc:mobileDSN");
            String sql = "Select *from Price where name=?";
            PreparedStatement pSt = cn.prepareStatement(sql);
            pSt.setString(1, m_nam);
            ResultSet rs = pSt.executeQuery();         
            if (rs.next()) {             
                    p = Double.parseDouble(rs.getString(2));
                    return p;
                }       
        } catch (Exception e) {
            System.out.println(e);
        }
        return 0.0;
    }
}

Server:

import java.net.*;
import java.rmi.*;
import java.sql.*;
public class MobileServer 
{
public static void main(String args[])
{
try{
MobileServerImpl obj=new MobileServerImpl();
Naming.rebind("MobileServer",obj);
}catch(Exception e)
{
System.out.println(e);
}


}

Client:

import javax.swing.*;
import java.rmi.*;
public class MobileClient 
{
public static void main(String args[])
{
try{
MobileInterface intobj=(MobileInterface)Naming.lookup("rmi://" + args[0] + "/MobileServer");
String  name=JOptionPane.showInputDialog("Enter Mobile Name:");
double p=intobj.getPrice(name);
System.out.println("Price for mobile: "+name+" is: "+p);
}catch(Exception e)
{
System.out.println(e);}
}


}

Output:



Write a Mulitithreaded TCP Server which will send system data and time to clinet.

Multithreaded TCP server:

import java.io.*;
import java.net.*;
import java.util.*;
public class MultiServe implements Runnable
{
 private ServerSocket ss;
 public static void main(String args[]) throws Exception
 {
  MultiServe m = new MultiServe();
  m.go();
 }
 public void go() throws Exception
 {
  ss = new ServerSocket(DayClient1.DAYTIME_PORT, 5);
  Thread t1 = new Thread(this, "1");
  Thread t2 = new Thread(this, "2");
  Thread t3 = new Thread(this, "3");
  t1.start(); t2.start(); t3.start();
 }
 public void run()
 {
  Socket s = null;
  BufferedWriter out = null;
  String myname = Thread.currentThread().getName();
  for (;;)
  {
   try
   {
    System.out.println("thread " + myname + " about to accept..");
    s = ss.accept();
    System.out.println("thread " + myname + " accepted a connection");
    out = new BufferedWriter(
    new OutputStreamWriter(s.getOutputStream()));
    out.write(myname + " " + new Date());
    Thread.sleep(10000);
    out.write("\n");
    out.close();
   }
   catch (Exception e)
   {
    e.printStackTrace();
   }
  }
 }
}

Client:

//A TCP Client for the Daytime service
import java.net.*;
import java.io.*;
public class DayClient1 {
public static final int DAYTIME_PORT = 2012;
String host;
Socket s;
public static void main(String args[]) throws
IOException {
DayClient1 that = new DayClient1("192.681.158.1");
that.go();
}
public DayClient1(String host) {
this.host = host;
}
public void go() throws IOException {
s = new Socket(host, DAYTIME_PORT);
BufferedReader i = new BufferedReader(
new InputStreamReader(s.getInputStream()));
System.out.println(i.readLine());
i.close();
s.close();
}
}

Output:


‘OR’

Server:

import java.io.*;
import java.net.*;
public final class TcpServerStarter 
{
 public static void main(String[] args) throws IOException 
 {
  ServerSocket serverSocket = null;
  boolean listening = true;
  try 
  {
   serverSocket = new ServerSocket(2012);
  } 
  catch (IOException e) 
  {
   System.err.println("Could not listen on port: 2012.");
   System.exit(-1);
  }
  while (listening)
  new ConnectionHandler( serverSocket.accept()).start();
  serverSocket.close();
 }
}

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Date;
public final class ConnectionHandler extends Thread {
    private Socket socket;
    public ConnectionHandler(Socket socket){
          setName("ConnectionHandler");
          this.socket = socket;
    }
    public void run(){
          BufferedReader in = null;
          PrintWriter out = null;
          String request;
          try{
                // Get the input and output streams
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                out = new PrintWriter(socket.getOutputStream(), true);

                while( (request = in.readLine()) != null){

                      // Deliver the current date and time if the client sends GET_TIME
                      if(request.equals("GET_TIME"))
                            out.println(new Date().toString());

                      // Deliver the JRE version if the client sends GET_JAVA_VERSION
                      else if(request.equals("GET_JAVA_VERSION"))
                            out.println(System.getProperty("java.version"));

                      // Exit the loop if the client sends CLOSE
                      else if(request.equals("CLOSE"))
                            break;
                }
          }
          catch(IOException e){
                e.printStackTrace();
          }
          finally{
                try{
                      if(socket != null)
                  socket.close(); // Close the socket (closing the socket also closes the input and output streams)
                }
                catch(IOException e){
                      e.printStackTrace();
                }
          }
    }
}

Client:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public final class TcpClient {
    private void process() {
          Socket socket = null;
          BufferedReader in = null;
          PrintWriter out = null;
          try{
                /* Establish a TCP connection with the server running locally on the port number 2012.
                 * You can write "localhost" instead of "192.681.158.1".
                                  */
                socket = new Socket("192.681.158.1", 2012);

                // Get the input and output streams
                in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                out = new PrintWriter(socket.getOutputStream(), true);

                // Send a GET_TIME request and print the response to the standard output
                out.println("GET_TIME");
                System.out.println(in.readLine());

                // Send a GET_JAVA_VERSION request and print the response to the standard output
                out.println("GET_JAVA_VERSION");
                System.out.println(in.readLine());

                // Send a CLOSE request to the server to end communication
                out.println("CLOSE");
          }
          catch(IOException e){
                e.printStackTrace();
          }
          finally{
                try{
                      if(socket != null)
                            socket.close(); // Close the socket (closing the socket also closes the input and output streams)
                }
                catch(IOException e){
                      e.printStackTrace();
                }
          }
    }
    public static void main(String[] args){
          new TcpClient().process();
    }
}

Output:


Multithreading Program in Java

Write down a complete multithreaded connection oriented socket based server, that'll wait for the connections from clients, after the establishment of connection with client, it will receive a string word from the client and send it back the meaning of that word from the array stored on server to client. 


Multithreaded Server Starter: 

import java.io.*;
import java.net.*;
public final class TcpServerStarter 
{
 public static void main(String[] args) throws IOException 
 {
  ServerSocket serverSocket = null;
  boolean listening = true;
  try 
  {
   serverSocket = new ServerSocket(7777);
  } 
  catch (IOException e) 
  {
   System.err.println("Could not listen on port: 7777.");
   System.exit(-1);
  }
  while (listening){
  new P10_5( serverSocket.accept()).start();
  System.out.println("Accepted connection from client");}
  serverSocket.close();
 }
}

Multithreaded Server:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
public final class P10_5 extends Thread {
    private final Socket socket;
    public P10_5(Socket socket) {
        setName("P10_5");
        this.socket = socket;
    }
    public void run() {
        BufferedReader in = null;
        PrintWriter out = null;
        int n = 3;
        String request;
        try {
            // Get the input and output streams
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream(), true);
            class dic {
                String word, mean;
                dic(String w, String m) {
                    word = w;
                    mean = m;
                }
            }
            dic d[] = new dic[4];
            d[0] = new dic("coincidence", "itifaq");
            d[1] = new dic("thanks", "shukriya");
            d[2] = new dic("problem", "masla");
            d[3] = new dic("night", "raat");
            while ((request = in.readLine()) != null) {
                for (int i = 0; i < n; i++) {
                    if (request.equals(d[i].word)) {
                        out.println(d[i].mean);
                        break;
                    }
                    if (i == n - 1) {
                        out.println("No knowledge for " + request);
                        break;
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (socket != null) {
                    socket.close(); // Close the socket (closing the socket also closes the input and output streams)
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Client:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
public final class P10_5Client {
    private void process() {
        Socket socket = null;
        BufferedReader in = null;
        PrintWriter out = null;
        try {
            /* Establish a TCP refrenced to  the server running locally on the port number 7777.
             * You can write "localhost" instead of "127.0.0.1".
             * If the server is running on a foriegn computer, replace "127.0.0.1" with the server's IP address or hostname
             */
            socket = new Socket("127.0.0.1", 7777);
            // Get the input and output streams
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream(), true);
            Scanner user = new Scanner(System.in); // Scanning for user input
            String input;
            while (true) {
                System.out.print("Enter String: ");
                input = user.next(); // Hold the input from the user
                if (input.equals("end")) {
                    System.out.println("You ended...");
                    break;
                } else {
                    out.println(input); // Send it to the server
                    System.out.println("Name: " + input + " Meaning: " + in.readLine());
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (socket != null) {
                    socket.close(); // Close the socket (closing the socket also closes the input and output streams)
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public static void main(String[] args) {
        new P10_5Client().process();
    }
}

Output:





Sunday, 23 September 2018

Difference between Abstract Classes and Interface in Java

Abstract Class:

Abstract class can have abstract and non-abstract methods.

Abstract class doesn't support multiple inheritance.

Abstract class can have final, non-final, static & non-static variable.

Abstract class can have static methods, main method and constructors.

Abstract class can provide the implementation of interface.

    public abstract class Shape
          {
                public abstract void shape();
          }


 A Java abstract class can have instance methods that implements a default behavior.

 An abstract class may contain non-final variable.

An abstract class can extend another Java class & implement multiple Java interfaces.

Java abstract classes are faster than interface.

Interface: 

Interface can have only abstract method.

Interface support multiple inheritance.

Interface has only static & final variable.

Interface can't  have static methods main method or constructor.

Interface can't provide the implementation of abstract classes.

public interface Drawable {
 void draw();
}

Method of Java interface are implicitly abstract & cannot have implementation.

Java interface should be implemented using keyword "implements".

Java  class can implements multiple interface.

In comparison with  java abstract classes, java interface  are slow as it requires extra indirection. 

Socket Programming in Java

Networking / Socket Programming :
                      
A socket is one endpoint of a two way  communication link between two programs running  on a Network. A socket is a bi-directional communication between host. A computer on a network often termed as host.

Socket Dynamics : 


Socket is an abstraction of the network.Each end has an input stream( to send data) and output stream( to receive data) wired up to the other host.You store and retrieve data to and from network through socket, without actually going into underlying mechanism.

What is Port?


It is transport address to which processes can listen for connection request. There are different protocols available to communicate such as TCP and UDP. There are 64k ports available for TCP sockets and 64k ports for UDP.

Client-Server Communication: 

  • A server runs on a specific computer and has  a socket that is bound to a specific port number.
  • The server just waits, listening to the socket for a client to make a connection request. 
  • On the client side : The client knows the hostname of the machine on which the server is running and the port number to which the server is connected. 
  • As client creates  a socket that socket attempts to connect to the specified server. 
  • The server listens through a specific kind of socket, which is named as server socket.
  • The sole purpose of the server socket is to listen for incoming request; it is not used for communication. 
  • If everything goes well, the server accepts the connection. 'Upon acceptance, the server gets a new socket, a communication  socket , bound to a different port number.
  • The server needs a new socket so that it can continue to listen through the original server socket for connection requests while tending to the needs  of the connected client. The scheme is helpful when two or more clients try to connect to a server simultaneously. 
  • On the server side, if the connection is accepted, a socket is successfully created and the client can use the socket  to communicate with the server. 
  • Note that the socket on the client side is not bound to the port number used to make contact with the server. Rather, the client is assigned a port number  local to the machine on which the client is running.
  • The client and server can now communicate by writing to or reading from their socket. 
Steps - To Make a Simple Client: 
 To make a client, process can be split into 5 steps. These are:

1. Import required package: 
You have to import two packages 
  • java.net.*; 
  • java.io.*; 
2. Connect / Open a Socket with server: 
Create a client socket(Communication Socket)
     Socket s  = new Socket("serverName" , serverPort);
  • serverName: Name or address of the server you wanted to connect such as  http://www.google.com  or  172.2.4.98 etc. For testing if you are running client  and server on the same machine then you can specify "localhost" as the name of server.
  • serverPort: Port number you want to connect to 
The scheme is very similar to our home address and then phone number. 

3. Get I/O Streams of Socket: 
Get input & output streams connected to your socket. 
  • For reading data from socket 
          A socket has input stream attached to it. 
               InputStream is =  s.getInputStream(); 
               // now to convert byte oriented streams into character oriented buffered reader. 

              // we use intermediary stream that helps in achieving above stated  purpose. 
              InputStreamReader isr = new InputStreamReader(is); 
             BufferedReader br = new BufferedReader(isr);
  • For writing data to socket
         A socket has also output stream attached to it. Therefore, 
                OutputStream os = s.getOutputStream(); 
                // now to convert byte oriented stream into Character oriented Printer Writer
               // here we will not use any intermediary stream because PrintWriter constructor
              // directly accepts an Object of  OutputStream. 
              PrintWriter pw = new PrintWriter(os, true); 

Here notice that true is also passed to so that output buffer will flush. 

Monday, 19 December 2016

Difference between Method Overloading and Method Overriding

Method Overloading: 

  • If a class have multiple methods by same name but different parameters(method signature), it is known as Method Overloading. 
  • Overloading happens at compile-time. The binding of overloaded method call to its definition has happens at compile-time.
  • Static methods can overload which means that a class can have more than one static method of the same name. 
  • Overloading is being done in the same class. 
  • Static binding is used for overloaded methods. 
  • Overloading gives better performance as compared to overriding, the reason is that the binding of overridden methods  is being done at runtime. 
  • Private and final methods can be overloaded. It means a class can have more than one private or final methods of same name.
  • Return type of methods doesn't matter in case of overloading, it can be same or different but argument list should be different.  
  • Java Method overloading example 
                    public  class OverloadingExample {
                           public int sum (int a, int b){
                                    return a+b;
                           }
                          public int sum (int a, int b, int c){
                                     return a+b+c;
                          }
                    }

Method Overriding:

  •  If a subclass (child class) has the same method as declared in the parent class, it is known as method overriding. 
  • Overriding happens at runtime. The binding of overridden method call to its definition happens at runtime. 
  • Static methods can't be overridden, even if you declare a same static method in child class it has nothing to do with the same method of parent class. 
  • Overriding is all about  giving a specific implementation to the inherited method of parent class. 
  • Dynamic binding is used for  overridden methods. 
  • A child class cannot override the private and final methods of their base class. 
  • Overridden methods should be more specific return type  and argument list should be same. 
  • Java Method overriding example: 
                    class Animal{
                        void eat(){
                             System.out.println("Eating"); 
                          }
                    }

                    public class Cat extends Animal{
                          void eat(){
                              System.out.println("Eating Meat"); 
                           }
                    }

Thursday, 10 November 2016

How to write, compile and Run First Program





Lets start from building a classical"Hello World" program, which is generally used as the first program for learning nay new language.


Hello World Program: 

  • Open notepad.
  • Write the following code into it. 

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

                                          System.out.println("Hello World!");
                   }

            }

  • To save your program, move to File menu and select save as option.
  • Save your program as "HelloWorld.java" in some directory. 
  • Name of the file must be same as name of the public class in the file. As java is case-sensitive, so if   your class name is HelloWorld, than file name must be HelloWorld. Otherwise the Java compiler will refuse to compiler the program. 
  • I saved my program in C:\Java\jdk\bin
  • Now open command prompt and type cd File Location i.e cd C:\Java\jdk\bin.
  • To compile java program type javac HelloWorld.java and press Enter. 
  • Now type java HelloWorld to run your program.
  • You can see the HelloWorld! would be displayed on console. Hurrah! You are successful in writing, compiling and executing your first program in java.


 A Closer Look at the First Sample Program:

  // Hello World Program

  • This is a comment. Single-line comment start with two forward slashes(//). Like most other programming languages, Java lets you enter a remark into a program's source file. The contents of a comment are ignored by the compiler.

public class Hello World{ 
  • This line uses the keyword class to declare that a new class is being defined. HelloWorld  is an identifier that is the name of  class. 
  • The entire class definition, including all of  its members, will be between the opening curly brace ({) and the closing curly brace ({). 


public static void main(String args[]) {
  • All Java applications begins execution by calling main(). 
  • The public keyword is an access specifier, which allows the programmer to control the visibility of class members. When  a class member is preceded by public, then that member may be accessed by code outside the class in which it is declared. 
  • main()  must be declared as public, since  it must be called by code outside of  its class when  the program is started. 
  • The keyword static allows main() to be called without having  to instantiate a particular instance of the class. This is necessary because main is called by the Java interpreter before any objects are made. 
  • The keyword void simply tells the compiler that main() doesn't return any value.
  • The main() is the method called when program begins. 
  • Any information that you need to pass to a method is received by variables specified within the set of parentheses. These variables are called parameter. In main() there is only one parameter, String args[] declare a parameter name args, which is an array of  instances of class String. args receives any command-line arguments presents when program executed.
  • The last character you see is the {. This is the sign of start of the method in our example start of the main()'s body. All of the code will occur should be written between the method's  starting and  ending braces. 
 System.out.println("Hello World!");
  • This string outputs the string "Hello World!" , followed by a new line on the console. 
  • Output is accomplished by the built-in function println() method.
  • Here System is a predefined class that provides access to the system, and out is the output stream that is connected to the console. 
  • At the end of the statement  you see a semi-colon(;). All  java statement in Java end with a semi-colon.
      }

   }
  • Ending braces- the first } in the program ends main() and the last } ends the HelloWorld class definition.
         

Wednesday, 9 November 2016

Java Installation and Environment Setting



We are going to learn about how to download , install Java and set Environment setting to make a Java program run.


Installation:
  • Download the latest version of  Java from http://java.sun.com.
  • Click on Download button to go  to download page and start download the latest version available there. 





  • Assume that Java installed in  C:\Program Files\Java\jdk
  • If installation is done properly you can see two files  java and javac in C:\Program Files\Java\jdk\bin
Environment Setting:

Now the next step is environment and path setting. There are two ways to accomplish this 

Temporary Path Setting: 
  • Open the command prompt 
  • Write the command on the command prompt according to the following format                                                 C:\Program Files\Java\jdk\bin
  • To check weather path has been set or not, write javac and press ENTER. If the list of options displayed, means that you have successfully completed the steps of path setting. 
  • The above procedure is shown in the picture given below: 


The issue with this procedure is that you have to repeat this again and again each time you open a new command prompt window. To avoid this overhead, it is better to set path permanently.

Permanent Path Setting: 
  • Write click on My Computer icon and click on Properties. 
  • Then select Advanced tab and click on Environment Variables. 
  • Now click on new and then in variable name field write path and in variable value field write path of the bin folder i.e C:\Program Files\Java\jdk\bin.

  • Press OK button.
  • Now open command prompt and write javac, and press Enter key. A list of  option would be displayed. 
  • After setting path by this method , you have no need to set path for each new opened command prompt. 



Methods in JAVA Language

 In general, a way may be thanks to perform some task. Similarly, the tactic in Java may be a collection of instructions that performs a sel...