Subscribe to Get Free Material Updates!
Visit my new blog WebData Scraping - Web Scraping Service provider company in India.
Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Difference Between Adapter class and Listeners Interface


When we implement a listener interface in any class then we must have to implement all the methods declared in that interface because all the methods in an interface are final and must be override in class which implement it. For example consider the following program which demonstrates handling of mouse events by implementing listener interface.

MouseEvents.java 
import java.applet.*;
import java.awt.*;
import java.awt.event.*;

/*<applet code="MouseEvents" height="300" width="300">
</applet>*/

Public class MouseEvents extends Applet implements MouseListener
{
 Public void init()
 {
  addMouseListener(this);
 }
 Public void mouseClicked(MouseEvent me)
 {
  setBackground(Color.blue);
  repaint();
 }
 Public void mouseEntered(MouseEvent me)
 {
  setBackground(Color.green);
  repaint();
 }

 Public void mouseExited(MouseEvent me)
 {
  setBackground(Color.red);
  repaint();
 }

 Public void mousePressed(MouseEvent me)
 {
  setBackground(Color.white);
  repaint();
 }

 Public void mouseReleased(MouseEvent me)
 {
  setBackground(Color.yellow);
  repaint();
 }
}


Our above example for handling mouse events implements MouseListener interface so the class MouseEvent has to implement all the five methods listed below.

  1. public void mouseClicked(MouseEvent me)
  2. public void mouseEntered(MouseEvent me)
  3. public void mouseExited(MouseEvent me)
  4. public void mousePressed(MouseEvent me)
  5. public void mouseReleased(MouseEvent me)
This can be inconvenient because if we want to use only one or two methods in your program then? It is not suitable solution to implement all the methods every time even we don’t need them. Adapter class makes it easy to deal with this situation. An adapter class provides empty implementations of all methods defined by that interface.

Adapter classs are very useful if you want to override only some of the methods defined by that interface. Here the names of Listener interface and corresponding interface are given which are in java.awt.event package.


Now consider a situation in which we want to perform any action only when mouse clicked and mouse releases then we should have to override mouseClicked() and mouseReleased() method. In this case if we use the listener interface then we must have to implements all the above five methods, the adapter class MouseAdapter will minimize programmer’s work. Following example demonstrate the use of Adapter class in place of Listener interface.

MouseEvents.java
implementing MouseListener.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;

/*<applet code="MouseEvents" height="300" width="300">
</applet>*/

Public class MouseEvents extends Applet extens MouseAdapter
{


 Public void init()
 {
  addMouseListener(this);
 }

 /*no need to implement all the methods because default implementation given in adapter class*/
 Public void mouseClicked(MouseEvent me)
 {
  setBackground(Color.blue);
  repaint();
 }

 Public void mouseReleased(MouseEvent me)
 {
  setBackground(Color.yellow);
  repaint();
 }
}

GTU MCA Sem 3 Java Practical Programs

I posted this Java programs for practice purpose. The ten programs given below are the Java programs which were asked in previous year GTU MCA  Java practical examination organized at Ahemdabad and Gandhinagar.


Download PDF version of This Programs
     
  1.  Create a package "sales" with following items:
    • Create a class naming “Order” containing orderDate (type as java.util.Date), productName  (type as String) and quantity (type as int) as its member fields. SystemDate should be used as orderDate.
    • Create a class naming “OrderManagment”, which manages instances of Order. This class must provide following methods :
      • placeOrder: It should accept productName and quantity as its arguments, it should create a new Order instance using both arguments(productName and quantity) and adds it to TreeSet collection.
      • displayOrdersByDate:Displays all the orders placed by current customer order by orderDate.
      •  displayOrdersByName: Displays all the orders placed by current customer order by productName.
      • storeOrder: It should accept Order instance as its arguments. It stores that Order instance to the file called ordersinfo.txt. (Use Comparable and Comparator interface).


  2. Create an applet naming “timer”, which displays current time in middle of the applet screen in RED color once applet started. Provide a menu with two options: 
    • StartTimer – if user presses StartTimer then timer should start and showing updated time after each minute in random color.
    • StopTimer - if user presses StopTimer then timer should stop and display message to user that how many minutes/seconds have spent since user has started the timer.


  3. Create a menu driven application naming drawShape using GUI, which has menu option like Line, Rectangle, Oval, etc…
    • When user clicks on Line then ask user to enter line parameters using input dialog box and if parameters are proper then line should be drawn with BLUE color. Otherwise display proper error message.
    • When user clicks on Rectangle then ask user to enter rectangle parameters using input dialog box and if parameters are proper then rectangle should be drawn with RED color. Otherwise display proper error message.
    • When user clicks on Oval then ask user to enter oval parameters using input dialog box and if parameters are proper then oval should be drawn with GREEN color. Otherwise display proper error message.
    • At a time only one shape should be displayed by frame.


  4. Create a package “BankInfo” with following items
    • Create a class naming “Account” with accountId (type as int), balance (type as double) and accountType (type as char), creationDate (type as java.util.Date) as its member fields.
    • Create a class naming “Bank” class which manages a number of Account instances. Provide following methods 
      • OpenAccount (Account acc) - adds acc instance to HashSet collection.
      • CloseAccount (Account acc) – removes acc from collection.
      • ListAccOrderByBalance () – which displays all account information order by balance.
      • ListOrderByDate () - which displays all account information order by creationDate.
      • Store (File flName) – which stores all accounts info to a file flName provided as parameter.  (Note : Use Comparable and Comparator iterfaces).
    • Create a class naming “BankIntoTest” which tests above mentioned classes with main method.

  5. Design a module called NewBookEntry for LibraryManagement system using GUI.
      • This module manages information like bookId, category(MCA Sem -1, MCA Sem – 2, MBA Sem-3, ……..), title, author, edition, publication, IssueFlag (Y, N – Use checkbox).
      • Make a NewBookEntry form which allows user to enter above mentioned information and provide menu option like Save, New, Search.
      • Once user clicks Save option a unique bookId should be generated and all details along with bookId should be stored in a file called bookinfo.txt.
      • Once user clicks New than all entered details should be cleared from NewBookEntry form.
      • Once user clicks Search than whatever category user has selected, that category details should be searched in bookinfo.txt file created in option save, if details are available then display in TextArea field otherwise display proper message (eg. If user selects category MCA Sem-3 then searches this category details in file bookinfo.txt).

  6. Create a package called “residence” with following items:
    • Create a abstract class naming “Residency” which will be having an area (like 130 sq.yard, 180 sq.yard, etc..) and rate_peryard (like 20000, 18000, etc..) as its member fields and has following methods.
      • Provide necessary constructor, getter and setter methods for this class.
      • Provide one method called calculatePropertyPrice () which will return basic price (Hint : price = area * rate_peryard).
    • Create a class naming “Flat” which is inherited from Residency and having its own instance field as maintenanceCharge. Override the calculatePropertyPrice () method which will return price of a flat with maintenaceCharge.
      • Override necessary methods from Object class.
    • Create a class naming “Villa”, which is inherited from Residency and having its own instance field as furnitureCharge.Override the calculatePropertyPrice () method which will return price of a Villa with furnitureCharge.
      • Override necessary methods from Object class.
    • Create a class naming “TestResidency” which tests above mentioned classes with main method. This class creates an array of Residency type and has following method.
      • Int searchResidency (Residency res) – which searches a res instance in an array of Residency. If available then return index otherwise display proper message.
      • double totalMaintenancePrice (Residency[] houses) - which returns total of all residency’s maintenanceCharge.
      • Void DisplayOrderByPrice – which displays array of residencies order by their price (Note : Use Comparable and Comparator interfaces).

  7. Create a multiThreading application.
    • One thread will read char data from a file and print it to console (user has to create one file manually with char data separated by space).
    • Second thread called asciiVal will display ASCII value of char data read by first thread to console.
    • Use interThreadCommunication to generate following type of output.  (Assuming file has data like – T E C H N O L O G Y ……)
      • Char value : T
      • ASCII Value : 84
      • Char Value : E
      • ASCII Value : 69
      • Char value : C
      • ASCII Value : 67
      • Char Value : H
      • ASCII Value : 72

  8. Create a GUI application which calculates charges for stay in Hotel, which allows user to enter duration as start date and end date as period while user wants to book a hotelRoom and to select a particular roomType (Regular, Delux, Cottage, Family, etc… use list). After selecting a particular roomChoice, display the calculated charges with start date and end date to user in dialogBox for confirmation. If user says ok then store these details to file else just close the dialogBox. Regular rates per day are as per following table. If user start date is between April to June or October to November, then room charges increased by 15%.

  9. Create an applet naming “UnitConversion”, which allows user to select a particular conversion from following options.(Use list) 
    • Decimal to HexaDecimal [Use Inter.toHexString()]. 
    • Decimal to Octal [Use Inter.toOctalString()]. 
    • Feet to Centimeter.(1 feet = 30.48cm) 
    • Inches to Feet (1 feet = 12 inches) 
    • Once user selects particular conversion then show the converted value with proper formatted message in dialogBox.(Like if user selects Inches to Feet option and input value is 60 then message should be “60 inches is equal to 5 Feet”.) 
    • If user enters any wrong kind of input then prompt proper errorDialog and clear the entered value.

  10. Create a GUI application, which has one menu. MenuItems are ReverseOrder, UpperCase, LowerCase, ArrangeAlphabetically and Length. 
    • Once frame displayed it will display your full name in middle of screen. 
    • If user clicks on ReverseOrder then it will display your name in reverse order with random color.
    • If user clicks on LowerCase then it will display your name in lowercase with random color.
    • If user clicks on UpperCase then it will display your name in UpperCase with random color.
    • If user clicks on Arrange then it will display your name in alphabetical order in random color.(Like INDIA – will be as ADIIN).
    • If user clicks on Length then it will display length of your First name in random color.If length is greater than 9 then it will display message “Very Big Name” in MessageBox.

Java - Opening a URL in new window from an applet

This Applet example demonstrate how to open any URL in new browser page. The applet has Text Field  in which user  enters web URL and when user press Go button the specified URL will open in new browser window.
applet


Create an applet which has a Text Field to accept a URL string, and displays the document of the URL string in a new browser window. When user enters http://www.google.com and clicks on Go button the applet will opens the url in new window and this is accomplished by getAppletContext.showDocument(url, target) method of the AppletContext.

Open_URL.Java
-----------------------------------------------------------------------------------------------
/* Applet program which takes URL from user into textfield and opens the url in new page */
/* Use applet in browser to get it run*/
import java.applet.*;
import java.awt.*;
import java.net.*;
import java.awt.event.*;

public class Open_URL extends Applet implements ActionListener
{
String link = "";
TextField tf;

public void init()
{
   
   Button b = new Button("Go");
   tf=new TextField("http://www.google.com");
 b.addActionListener(this);
 add(tf);
   add(b);
}

public void actionPerformed(ActionEvent ae)
{
   //get the link entered by user from textbox
  link= tf.getText();
        
   try
   {
    AppletContext a = getAppletContext();
    URL url = new URL(link);
    a.showDocument(url,"_blank"); // Opens the url in new window

         //a.showDocument(url,"_self");    _self to open url in same window  

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


}
Applet.html
-------------------------------------------------------------------------------------------
<html> 
<head>
         <title> Open URL in new page Using Java Applet</title>
</head>
<body>
         <applet code="Open_URL.class" height=300 weight=300></applet>
</body>
</html>

How To Create CSV File In Java

TestCsv.csv (Excel file) Looks as bellow:


/* Read Data From Comma Seprated File (CSV) using  FileInputStream and DataInputStream*/
import java.io.*;
import java.util.*;

class ReadCsv
{

 public static void main(String args[])
 {


  try
  {
  
  int sum=0;
  FileInputStream fi1=new FileInputStream("TestCsv.csv");
  DataInputStream di=new DataInputStream(fi1);


  String line;
   
   while((line=di.readLine())!=null)

   {

   StringTokenizer st=new StringTokenizer(line,",");

   while(st.hasMoreTokens())
   {
    String s=st.nextToken();
    System.out.println(s);
    sum=sum+Integer.parseInt(s);
   }
   
   
    System.out.println("Total:"+sum+"");
   }
   
  }

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

 }



}
Output:

Java FileOutputStream Example


/* Create A File and Write String of Byte (Byte Array) using FileOutputStream*/

import java.io.*;


class OutputStreamDemo1
{
  
 public static void main(String[] args)
 {
  
  try
  {
  File f1=new File("MyFile.txt");
  FileOutputStream fout=new FileOutputStream(f1);
  byte[] byte_arr=new byte[10];
  String str="Java File Handling";
  byte_arr=str.getBytes();

  fout.write(byte_arr);
  
  }

  catch(Exception e)
  {

  }

 }
}

Read Single Byte FileInputStream

/* Read A Single Byte From File using FileInputStream*/

import java.io.*;


class InputStreamDemo
{
  
 public static void main(String[] args)
 {
  
  try
  {
  File f1=new File("MyFile.txt");
  FileInputStream fin=new FileInputStream(f1);

  int ch=fin.read();
  System.out.println("Byte Data Readed From File="+(char)ch);
  }

  catch(Exception e)
  {

  }

 }
}

Read File Using InputStream

/* Read A String (Byte Array) From File using FileInputStream*/

import java.io.*;


class InputStreamDemo1
{
  
 public static void main(String[] args)
 {
  
  try
  {
  File f1=new File("MyFile.txt");
  FileInputStream fin=new FileInputStream(f1);
  DataInputStream din=new DataInputStream(fin);
  byte[] byte_arr=new byte[100];
  
   while(din.available()!=0)
   {
   
    System.out.println(din.readLine());
   }
  }

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

 }
}

Java Program To Create New File

The below Java program creates new blank file named MyFirstFile.txt by passing  file name as argument to the constructor of File object. We must have to place file creation code in try block because it may throw IOException. We can check whether new file is created or not by using createNewFile() method of File object and place it in if...else condition.

import java.io.*;
class CreateFile
{
  
 public static void main(String[] args) 
 {
  
  try
  {
   /*Creates File MyFirstFile.txt in current Directory*/
   File f1=new File("MyFirstFile.txt"); 
   
   if(f1.createNewFile())
    System.out.println("File Created Successfuly!");
   else
    System.out.println("Fail to Create File!");
  
  }

  catch(IOException e)
  {

  }

 }
}

Unit -2: Inheritance and sub classing in Java and packages and use of access specifiers

  • Defining subclasses
  • Using super to use constructor of a super-class, Method overriding and use of super, Variable shadowing and use of super.
  • Method and variable binding
  • Using final with variables, methods and classes
  • Abstract classes and interfaces, Abstract classes and abstract methods
  • Single inheritance of classes, Interfaces
  • Object class as the super class of all classes, Methods inherited from the Object class
  • Uses of package and import statements, use of static imports
  • Use of CLASSPATH for class loading
  • Access specifiers, Access specifiers for members of a package, Access specifiers for members of a class, Access specifiers for overriding methods
  • Using the Java APIs
  • Commonly used classes from the java. language package
  • Comparable and Comparator interfaces
  • String, String Buffer and the String Builder classes
  • Understanding pass by value and pass by reference for Java
  • Wrapper classes
  • Math class constants and methods
Also See Unit 1

Download Unit 2 PPT

Java Unit 1 Object Oriented Programming And Introduction To Java, Data Types, Operators, Statements And Defining Classes In Java


  •  Features of the Java Language, Object-oriented Programming
  • Creating an Application in Java, Compiling and executing Applications in Java
  • Program comments
  • Primitive data types, Integer Data Types, Floating Point Data Types
  • Reference Data types
  • Arrays, single and multi-dimensional arrays
  • Other reference types, classes, interfaces, enums and annotations
  • Unicode escapes in Java source code
  • Understanding super types and subtypes.
  • Operators - Arithmetic, String concatenation, Relational, Logical, Bitwise, increment-decrement,conditional, assignment, cast and instance of operators.
  • Understanding the narrowing and widening conversions of numeric data types.
  • Statements - if, if-else, switch-case, for, while, do-while, break, continue and return statements.
  • Various members within a class instance variables
  • methods and their overloading
  •  constructors and their overloading
  • Garbage collector and finalize method
  • static variables and methods
  • initializer blocks and the class initializer blocks 
Also See Unit-2

Download Unit 1 PPT


Related Posts Plugin for WordPress, Blogger...

 
Design by Wordpress Theme | Bloggerized by Free Blogger Templates | coupon codes