Core Java assignments 2

Below are few assignments on Core Java, which you can try out

1.Swap Numbers Without Using Third Variable Java Example*
2.Java program to find Palindrome Number or not. For eg. 12321 is palindrome, and 124869 is not palindrome
3.Program to create an outer and inner classes with some methods and then create an two objects to access both the methods in innner and outer class.
4.Write a program that shows how to access the private members of a class using inner class.
5.Program to create enum class in java
6.Write a Java program by using BufferedReader class to prompt a user to input his/her name from keyboard and then the display output, until done is given as input.(Hint use any loop)
7.Write a program in Java to print Fibonacci series up to given number? Write both iterative and recursive version
8.write a Java program to calculate factorial of an integer number ? Both iterative and recursive solution.
9.Write a program to extract each digit from an int. For example, if the int is 86543, the output shall be 8,6,5,4,3.
Hints: Use n % 10000 to extract first digit, and n = n / 10000 to remove first digit, and continue with this process, to get each digit.

10.Write a program to read an int, a float, and a String in text file called “abc.txt”, and output in below way
integer read is 12
decimal number read is 33.44
String read is “Hello”

11.Write a program to reverse an input String. For example:
Enter input String: wxyz
Reversed String is: zyxw

12.Write a program to print fibonacci series less than 100?

13.Write a program to print, if given number is armstrong number. For example 371 is armstrong number because 3*3*3+7*7*7+1*1*1 = 371

14.When a given string Hello, output need to be printed as H l o
That is only odd characters need to be printed, space need to be printed for even characters.

15.Explain difference between Compile time polymorphism and run time ploymorphism

16.Write program to display Greatest Common Factor, of given numbers.

17.To a TreeSet, add Employee objects, with below fields/data members
employee name, salary, age, department.
Store the employee objects in ascending order of salary. Get all employees with salary greater than 15,000
Hint:Use Comparator or Comparable interface

18.Repeat assignment 17, with descending order of salary.

19.Use 4 threads along with main thread to display each character of a given string. For eg. if “Hello, How are you” String is given, output can be something similar as below.
Thread 1: H
Thread 3: e
Main Thread: l
Thread 2: l
Thread 1: o
Thread 2:
and so on…..

20. Develop
(a) RMI Server object exposing methods, taking radius as parameter, and returns diameter, circumference, surface area,etc…
(b) Develop RMI Client which can lookup to above RMI Server object, and invoke the methods.

21. Develop a circular linked list, by implementing List interface.

22.Develop
(a) RMI Server object exposing a method, taking Collection of City objects as input parameter.A city object can have below fields city name, temperature. RMI Server object need to find average of temperatures in all City objects.
(b) RMI Client object, which can look up and invoke above method.

23. Simple Client and Server. A Client sends int or float to Server. Server need to multiply with 10, and send result back to Client. Client need to display final value.

24. Develop a console based Server and Client. Client need to send commands like current directory, change directory, list files & file properties(like modified date, etc…). Server program need to provide above details, when requested by client.

25. Implement a simple Web Server, which receives request, and serve the requested file, to the Client.

26. Develop a simple console based chat broadcast client, and chat server, using socket programming. Chat server need to serve multiple chat clients. Whenever a client sends a message, the message need to be received by all the chat clients running currently.

27. Can I pass array as parameter to a constructor?
Can an object be declared as static data member.Can u give an example of it, from built ib classes?

28. A method which can take any number of one dimensional arrays, write a program, then create and return an array, which removes duplicate elements.

29. Write program to take non english characters from keyboard, and print them.

30. Can we make a constructor synchronized?

31. Assume that sorted order of alphabets are different, which can be given as input. Given a String arrange characters of this String in customized alphabetical order?

32. What is the difference between Scanner and BufferedReader

33. How to convert Reader to InputStream, and viceversa?

34. What is the output of below program?
package p1;

class Alpha extends Beta{

}

class Beta extends Teta{

}

class Teta extends Alpha{

}

public class Misc1 {
public static void main(String[] args) {
Teta ot = new Teta();
System.out.println(“Everything works fine”);
}
}

35. A client program, having two threads, at atime only one thread can send a request to a server program. When one client thread is in the process of sending request, and if other client thread wants to send request, then it need to wait, until first thread completes sending request to server. Note that, the two client threads, can execute simultanesouly, but only one thread can interact with server at a time.

36. In InputStreams what is the purpose of mark and reset?

37. What is chain of responsibility Design Pattern?

38. Advantage of Facade Pattern?

39. Lets assume there is a framework, which is released to App developers. How do you ensure that old Apps are not affected with newer versions of Framework? i..e how do you take care of backward compatibility of already developed Apps, even though underlying components of framework may change. which design patterns do you suggest?

40. A program which receives an input thru network socket, based on the string received, a specific observer need to do some processing. All this can be performed with one thread.

There can be multiple observers, each of which can do one of the following
a. which reverses string
b. which replaces some character in string
c. which concatenates string

Hint: use Observer and Observable

41. Repeat above problem, by using separate thread for each Observer, and perform some long processing in each Observer thread.

42. Solve the same above problem using wait() notify()

43. Create a vehicle class, with below data members

String make_and_model;

String registration_number;

String registration_date; //in format dd-mm-yyyy

You can add appropriate constructor, setter & getter methods to above class. Then create about 10 objects of above class, with different values of data members. Now add these objects to a TreeSet, and ensure that the objects in TreeSet are arranged in ascending order of registration_date.

NOTE: use Comparator interface

44. Print your name 10 times, without using a loop. NOTE: use method recursion

You may also like to read:
Basic Core Java Assignments 1

Program to send HTTP Request to Web server

Below is an example on how to send an HTTP request to any web Server like Tomcat, Glass Fish, Web Logic, Web Sphere. Below Java program acts like a simple Web Browser, which sends HTTP GET or POST Request to Web Server, and prints response( from Web Server) to console.

HTTP Protocol is further dependent on TCP/IP Protocol.
i..e HttpURLConnection further uses underlying Sockets to interact with Web Server.

Difference between HttpURLConnection and HttpsURLConnection

Both HttpURLConnection and HttpsURLConnection classes are in java.net package.
HttpURLConnection uses unsecured version of HTTP(Hyper Text Transfer Protocol), where as HttpsURLConnection is secured version of HTTP Protocol.

Both HttpURLConnection and HttpsURLConnection can use any of the HTTP methods, either GET or POST method.

Difference between GET and POST HTTP Methods

HTTP POST
Data is sent thru URL
Eg: /abc.jsp?mytext=fdfsdfsdf&pwd=fgfdgfdgfd
Data is sent internally
Only limited data can be submitted Unlimited data can be submitted to server program
Unsecured compared to POST Secured compared to GET

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.MalformedURLException;

import javax.net.ssl.HttpsURLConnection;

public class HttpURLConnectionEg {

	private final String USER_AGENT = "Test Client";

	public static void main(String[] args) throws Exception {

	HttpURLConnectionEg http = new HttpURLConnectionEg();

	System.out.println("Sending Http GET request to URL:");
	http.sendGet();
	System.out.println("---------------------------------");
	System.out.println("Send Http POST request to URL:");
	http.sendPost();

	}

	// HTTP GET request example
	private void sendGet() throws Exception {

	String url = "http://localhost/index.php";

	URL obj = new URL(url);
	HttpURLConnection con = (HttpURLConnection) obj.openConnection();

	// optional, default Request method is GET
	con.setRequestMethod("GET");

	//add request header
	con.setRequestProperty("User-Agent", USER_AGENT);

	int responseCode = con.getResponseCode();
        //responseCode is numeric value of HTTP response, can be 2XX,3XX,4XX or 5XX

	System.out.println("Sending GET request to URL : " + url);
	System.out.println("Response Code : " + responseCode);

	BufferedReader in = new BufferedReader(
		new InputStreamReader(con.getInputStream()));
	String inputLine;
	StringBuffer response = new StringBuffer();

	while ((inputLine = in.readLine()) != null) {
		response.append(inputLine);
	}
	in.close();

	//print result
	System.out.println(response.toString());

	}

	// HTTP POST request example
	private void sendPost() throws MalformedURLException,IOException{

	String url = "https://localhost/index.php";
	URL obj = new URL(url);
	HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();

	//set request method
	con.setRequestMethod("POST");

        //set header values, first parameter is header name, second parameter is header value
	con.setRequestProperty("User-Agent", USER_AGENT);

	String urlParameters = "a=1234&b=5678&c=65465&d=7263543";

	// Send post request
	con.setDoOutput(true);
	DataOutputStream wr = new DataOutputStream(con.getOutputStream());

        //write the bytes of Request Parameters, to the Server
	wr.writeBytes(urlParameters);
	wr.flush();
	wr.close();

	int responseCode = con.getResponseCode();
	System.out.println("Sending POST request to URL : " + url);
	System.out.println("Post parameters : " + urlParameters);

        //responseCode is numeric value of HTTP response, can be 2XX,3XX,4XX or 5XX
	System.out.println("Response Code : " + responseCode);

        //Create BufferedReader, with the input stream of the response from Web Server
	BufferedReader in = new BufferedReader(
		new InputStreamReader(con.getInputStream()));
	String inputLine;
	StringBuffer response = new StringBuffer();

	while ((inputLine = in.readLine()) != null) {
		response.append(inputLine);
	}
	in.close();

	//Now the response from Web Server, is in response StringBuffer
        //Then print response on the console
	System.out.println(response.toString());

	}

}

You may also like to read:
What is a network port?

TCP Socket Client Program

Below is TCP Socket client program.
Step 1: import required packages java.net and java.io
Step 2: Use Socket(with Server IP Address and port number) class to connect to Server Program.
Step 3: Write data to Server Program
Step 4: Read response String from Server
Step 5: Print response from Server

TCP Socket example
TCP Socket example

Click here for step by step Java Server Program

//step 1
import java.net.*;
import java.io.*;

public class HelloClient
{
   public static void main(String [] args)
   {
      String serverName = "localhost";
      //"localhost" can b replaced with Loopback IP addr 127.0.0.1,
      //if server program is on same machine as client

      //If server is locate on some other machine, pls specify it's IP address, above
      int port = 6066;
      try
      {
         //step 2
         System.out.println("Client: Connecting to (Server) " + serverName +
		 " on port number " + port);
         Socket client = new Socket(serverName, port);
         System.out.println("Client: Just connected to (Server) "
		 + client.getRemoteSocketAddress());
         OutputStream outToServer = client.getOutputStream();

         //step 3
         DataOutputStream out = new DataOutputStream(outToServer);
         out.writeUTF("[From Client]Request from "
                      + client.getLocalSocketAddress());
         InputStream inFromServer = client.getInputStream();

         //step 4
         DataInputStream in =
                        new DataInputStream(inFromServer);

         //step 5
         System.out.println("Client: Response on Server " + in.readUTF());
         client.close();
      }
      catch(MalformedURLException me)
      {
          me.printStackTrace();
      }
      catch(IOException e)
      {
         e.printStackTrace();
      }
   }
}

You may also like to read:
ServerSocket Program
How to use IPv6 address in Java
How remote objects can interact in Java

TCP ServerSocket Program

Below is Server program, based on TCP/IP. For details on TCP, please read Java Networking
Step 1.import java.net and java.io packages
Step 2.Create ServerSocket Listening on a port
Step 3.Waits for 65000 milliseconds for request from any client. On receiving a request from client, read request from client
Step 4.Print client request on server console
Step 5.Now send response to client program.

SocketServer Example
SocketServer example

Using Thread for a server is not mandatory, and can be used for better performance, if required

//step 1
import java.net.*;
import java.io.*;

public class HelloServer extends Thread
{
   private ServerSocket server_obj;

   public HelloServer(int port) throws IOException
   {
     //step 2, Create ServerSocket and listen on a port
      server_obj = new ServerSocket(port, 5);//5 is number of back log requests

      //waits for 65000 milliseconds to receive request from client
      //If no request is received from client within 65000, SocketTimeoutException is thrown
      server_obj.setSoTimeout(65000);
   }

   public void run()
   {
    for(;;) //infinite for loop
    {
    try
    {
       System.out.println("Server: ..Waiting for client request on port number " +
       server_obj.getLocalPort() );
       //step 3
       Socket server = server_obj.accept();
       System.out.println("Server: Connecting to client with IP addr "
             + server.getRemoteSocketAddress());
       DataInputStream in =
             new DataInputStream(server.getInputStream());
       //step 4
       System.out.println(in.readUTF());

       //step 5
       DataOutputStream out =
            new DataOutputStream(server.getOutputStream());
       out.writeUTF("[From Server] This message is from server "
         + server.getLocalSocketAddress() + " Thanks for your request");
       server.close();
    }
    catch(SocketTimeoutException s)
    {
       System.out.println("Server: SocketTimeoutException occurred");
       s.printStackTrace();
       break;
    }
    catch(Exception ep)
    {
       System.out.println("Server: Exception occurred");
       ep.printStackTrace();
       break;
    }
    }
   }
   public static void main(String [] args)
   {
       //port number on which server is listening
       //clients need to send request to this port number
      int port_number = 6066;
      try
      {
         Thread t = new HelloServer(port_number);
         t.start();
      }catch(IOException e)
      {
         e.printStackTrace();
      }
   }
}

You may also like to read:
Step by Step Socket Client Program
What is Remote Method Invocation?
Where does printStackTrace() print to?
Can I create Child Thread to another Child Thread?

Java Networking

Network programming refers to writing programs that execute across multiple devices (computers), in which the devices are all connected to each other using a network.

java.net package of the J2SE APIs contains classes for Network or Socket Programming.

TCP

: TCP stands for Transmission Control Protocol, which allows for reliable communication between two applications. TCP is typically used over the Internet Protocol, which is referred to as TCP/IP. TCP is Connection oriented Protocol. All packets are traversed thru the connection created between devices.

UDP

: UDP stands for User Datagram Protocol, a connection-less protocol that allows for packets of data to be transmitted between applications. Packets traverse thru multiple paths, between devices. There is no guarantee in the order of packets received.

IP Address

: Each device on network is identified by IP Address. There are two versions of IP Address, IPv4 and IPv6. IPv4 is 32 bit, and IPv6 is 128 bit IP Address.

Port Numbers

: A device will have multiple(thousands) of Network port numbers. Purpose of port numbers is multiple programs(on a machine) can simultaneously send/receive data.
For example you may want to use Chat Application, Email Client, Web Browser etc… simultaneously. And those Applications may need to send and receive data over network at same time. For which each Application is binded to a port number, hence multiple port numbers are required, for Applications to simultaneously read and write data to network.Hence, if multiple port numbers are not available on device, then only one Application on Device can connect to Network.

TCP Sockets
TCP Sockets

Standard Port Numbers:
80 – HTTP (Protocol used by Web Browser and WebServer) Stands or Hyper Text Transfer Protocol
443 – HTTPS(also used by Web Browser and Web Server, for secured communication)
25 – SMTP(Simple Mail Transfer Protocol)
110 – POP3(Post Office Protocol),etc…

DNS(Domain Name Server)

converts domain name to IP Address. IP Address of Machines are required to Transfer data between Machines in a Network.

java networking
java networking

java.net

How to create TCP sockets between Client and Server Machines

ServerSocket class is used by server applications to obtain a port and listen for client requests.
Socket represents the socket that both the client and server use to communicate with each other. The client obtains a Socket object by instantiating one, whereas the server obtains a Socket object from the return value of the accept() method.

Socket and ServerSocket support both versions of IP Address IPv4 and IPv6.

How to create UDP sockets between Machines

DatagramSocket: Each packet sent or received on a datagram socket is individually addressed and routed. Multiple packets sent from one machine to another may be routed differently. Datagram packets may be received in different order, than sent.
DatagramPacket: Data is sent thru DatagramPacket over DatagramSocket

How to send and receive HTTP request/response, from/to Web server?

URLConnection – Base class of HttpURLConnection
HttpURLConnection – sends HTTP Request(GET or POST method) to a Web Server, and gets the response.
HttpsURLConnection – same as HttpURLConnection, but this is secured version.

You may also like to read:
RMI in Java
Java Socket Client example
ServerSocket example