Free Data Structures and Algorithms Course









Subscribe below and get all best seller courses for free !!!










OR



Subscribe to all free courses

How to demonstrate working of CheckBox and adding ActionListener to it in Java's Swing Framework ?.

Program to demonstrate working of CheckBox and adding ActionListener to it in Java's Swing Framework.


package com.hubberspot.swing;

import java.awt.Container;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class CheckBoxDemo {

 public static void main(String[] args) {

  // 1. Create a simple frame by creating an object 
  // of JFrame. 
  JFrame frame = new JFrame();

  // 2. Give the frame a title "CheckBox Demo" by calling 
  // setTitle method on frame object
  frame.setTitle("CheckBox Demo");

  // 3. Give frame a size in pixels as say 300,300 
  frame.setSize(300, 200);

  // 4. set a operation when a user close the frame, here it 
  // closes the frame and exits the application
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

  // 5. Create a checkbox by creating an Object of class 
  // JCheckBox. 
  final JCheckBox checkBox1 = new JCheckBox();

  // 6. set the text of checkbox1 as "check box 1"
  checkBox1.setText("check box 1");

  // 7. Create another checkbox by creating an Object of class 
  // JCheckBox.
  final JCheckBox checkBox2 = new JCheckBox();

  // 8. set the text of checkBox2 as "check box 2"
  checkBox2.setText("check box 2");

  // 9. Make it selected that is (checked)
  checkBox2.setSelected(true);

  // 10. Create a label by creating an Object of class 
  // JLabel
  final JLabel label = new JLabel();

  // 11. set the text of label as "check box 2 selected"
  // as initially we have made checkbox2 selected
  label.setText("check box 2 selected");

  // 12. We add an ActionListener to the checkbox1
  // which will listen about the action user performs
  // over the checkbox1. Here user only checks and unchecks
  // it. As soon as user checks checkbox1 the text of the 
  // label changes from check box 2 selected to check box 1 selected
  // and checkbox2 is unchecked
  checkBox1.addActionListener(new ActionListener() {

   @Override
   public void actionPerformed(ActionEvent event) {

    JCheckBox checkBox = (JCheckBox) event.getSource();
    if (checkBox.isSelected()) {
     checkBox.setSelected(true);
     checkBox2.setSelected(false);
     label.setText("check box 1 selected");
    }

   }
  });


  // 13. We add an ActionListener to the checkbox2
  // which will listen about the action user performs
  // over the checkbox2. Here user only checks and unchecks
  // it. As soon as user checks checkbox2 the text of the 
  // label changes from check box 1 selected to check box 2 selected
  // and checkbox1 is unchecked

  checkBox2.addActionListener(new ActionListener() {

   @Override
   public void actionPerformed(ActionEvent event) {

    JCheckBox checkBox = (JCheckBox) event.getSource();
    if (checkBox.isSelected()) {
     checkBox.setSelected(true);
     checkBox1.setSelected(false);
     label.setText("check box 2 selected");
    }

   }
  });


  // 14. for adding all these swing components to frame
  // we first get the content pane which returns a 
  // Container
  Container container = frame.getContentPane();

  // 15. We create a Layout for Swing Components
  // here we are using FlowLayout with value as "center'
  // it will make the swing components float to center
  FlowLayout layout = new FlowLayout(FlowLayout.CENTER);

  // 16. We set the layout for container
  container.setLayout(layout);

  // 17. We add the checkboxes and label to it
  container.add(checkBox1);
  container.add(checkBox2);
  container.add(label);

  // 18. after adding checkboxes and label, we make it 
  // visible on the frame by calling the method as 
  // setVisible and passing value as true.
  frame.setVisible(true);


 }

}




Output of the program :



















How to use and set ToolTip for Swing components in Java ?.

Program to demonstrate how to use and set ToolTip for Swing components in Java

package com.hubberspot.example;

import java.awt.Container;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class ToolTipDemo {

 public static void main(String[] args) {

  // 1. Create a simple frame by creating an object 
  // of JFrame. 
  JFrame frame = new JFrame();

  // 2. Give the frame a title "Tool Tip Frame" by calling 
  // setTitle method on frame object
  frame.setTitle("Tool Tip Frame");

  // 3. Give frame a size in pixels as say 300,300 
  frame.setSize(300, 300);

  // 4. set a operation when a user close the frame, here it 
  // closes the frame and exits the application
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

  // 5. Create a button by creating an Object of class 
  // JButton. 
  JButton button = new JButton();

  // 6. set the text of button as "Button"
  button.setText("Button");

  // 7. Create a label by creating an Object of class 
  // JLabel
  JLabel label = new JLabel();

  // 8. set the text of label as "Label"
  label.setText("Label");

  // 9. In order to create a tool tip for label, 
  // button or any swing components, we call setToolTipText
  // method and passing it the information we want to display 
  // when user hovers over the swing components
  button.setToolTipText("Tool Tip for Button");
  label.setToolTipText("Tool Tip for Label");

  // 10. for adding all these swing components to frame
  // we first get the content pane which returns a 
  // Container
  Container container = frame.getContentPane();

  // 11. We create a Layout for Swing Components
  // here we are using FlowLayout with value as "center'
  // it will make the swing components float to center
  FlowLayout layout = new FlowLayout(FlowLayout.CENTER);

  // 12. We set the layout for container
  container.setLayout(layout);

  // 13. We add the button and label to it
  container.add(button);
  container.add(label);

  // 14. after adding button and label, we make it 
  // visible on the frame by calling the method as 
  // setVisible and passing value as true.
  frame.setVisible(true);
 }

}



Output of the program :





















 


How to calculate Exponential of a number through a Java program ?.

Program to demonstrate how to calculate Exponential of a number in Java.






Click here to download complete source code



package com.hubberspot.code;

import java.util.Scanner;

public class ExponentialCalculation {

 public static void main(String[] args) {

  // Create a Scanner object which will read 
  // values from the console which user enters
  Scanner scanner = new Scanner(System.in);

  // Getting input from user from the console
  System.out.println("Enter value of number ");

  // Calling nextDouble method of scanner for
  // taking a double value from user and storing
  // it in number variable
  double number = scanner.nextDouble();

  System.out.println();

  System.out.println("Calculating exponential of a number ... ");

  // In order to calculate exponential of a number 
  // we use Math class exp() static method which takes in a 
  // number and returns back the exponential of a number
  double result = Math.exp(number);

  // printing the result on the console
  System.out.println("Exponential of " + number + " is : " + result); 

 }

}


Click here to download complete source code

Output of the program :



How to calculate natural and base 10 logarithm of a number through a Java program ?.

Program to demonstrate how to calculate natural and base 10 logarithm of a number in Java.

package com.hubberspot.code;

import java.util.Scanner;


public class LogarithmCalculation {

 public static void main(String[] args) {

  // Create a Scanner object which will read 
  // values from the console which user enters
  Scanner scanner = new Scanner(System.in);

  // Getting input from user from the console
  System.out.println("Enter value of number ");

  // Calling nextDouble method of scanner for
  // taking a double value from user and storing
  // it in number variable
  double number = scanner.nextDouble();

  System.out.println();

  System.out.println("Calculating base 10 logarithm of a number ... ");

  // In order to calculate base 10 logarithm of a number 
  // we use Math class log10() static method which takes in a 
  // number and returns back the base 10 logarithm of a number
  double result = Math.log10(number);

  // printing the result on the console
  System.out.println("Base 10 Logarithm of " + number + " is : " + result); 

  System.out.println();

  System.out.println("Calculating Natural logarithm of a number ... ");

  // In order to calculate natural logarithm of a number 
  // we use Math class log() static method which takes in a 
  // number and returns back the natural logarithm of a number
  result = Math.log(number);

  // printing the result on the console
  System.out.println("Natural Logarithm of " + number + " is : " + result); 

 }

}




Output of the program :



How to use instanceof operator for testing IS-A relationship in Java ?.


Program to demonstrate how to use instanceof operator for testing IS-A relationship in Java

package com.hubberspot.code;

// Create a Shape class
interface Shape { }

// Create a Triangle class which 
// implements Shape class
class Triangle implements Shape{ } 

// Create a Parallelogram class which 
// implements Shape class
class Parallelogram implements Shape { }

// Create a Rectangle class which 
// extends Parallelogram class
class Rectangle extends Parallelogram { }

// Create a class Car in different hierarchy
class Car { }



public class InstanceOfTest {

 public static void main(String[] args) {

  // Create an Object of Car, Rectangle, 
  // Parallelogram and Triangle
  Car car = new Car();
  Rectangle rectangle = new Rectangle();
  Parallelogram parallelogram = new Parallelogram();
  Triangle triangle = new Triangle();

  // Lets now have a IS-A test of all these object 
  // in order to know that whether a particular object 
  // created above is of particular type we have a 
  // test of it using instanceof operator / keyword
  // This operator tells us whether a particular 
  // object is a instance of particular type or not.

  // The usage : object instanceof Class 
  if(rectangle instanceof Shape) { 

   System.out.println("rectangle is a Shape");

  }else{ 

   System.out.println("rectangle is not a Shape");

  }

  if(triangle instanceof Shape) { 

   System.out.println("triangle is a Shape");

  }else { 

   System.out.println("triangle is not a Shape");

  }

  if(parallelogram instanceof Shape) { 

   System.out.println("parallelogram is a Shape");

  }else { 

   System.out.println("parallelogram is not a Shape");

  }

  if(rectangle instanceof Parallelogram) {

   System.out.println("rectangle is a Parallelogram");

  }else { 

   System.out.println("rectangle is not a Parallelogram");

  }

  if(car instanceof Shape) {

   System.out.println("car is a Shape");

  }else {

   System.out.println("car is not a Shape");

  }

  // throws compile time error as "Incompatible conditional 
  // operand types Car and Rectangle" : means we are comparing 
  // class of different hierarchies plus they are incompatible
  // types

  /*if(car instanceof Rectangle) {

   System.out.println("car is a Rectangle");

  }else {

   System.out.println("car is not a Rectangle");

  } */
 }
}



Output of the program :



How to calculate Area and Perimeter of Square in Java ?.


Program to demonstrate how to calculate Area and Perimeter of Square in Java




 

package com.hubberspot.example;

// Import java.util.Scanner to read data from 
// console
import java.util.Scanner;

public class SquareAreaPerimterDemo {

 public static void main(String[] args) {

  // Creating a Scanner object using a constructor
  // which takes the System.in object. There are various 
  // constructors for Scanner class for different
  // purposes. We want to use Scanner class to read
  // data from console on the system, So we are using 
  // a constructor which is taking an System.in object
  Scanner scanner = new Scanner(System.in);

  // Create three variables which will hold the
  // values for side, area and perimeter of square
  int side = 0;  
  int area = 0;
  int perimeter = 0;

  // prompt the user to enter value of length of side of 
  // square
  System.out.println("Enter the length of side of square ");

  // store the side length into side variable entered by user
  side = scanner.nextInt();

  // Calculate area of square by multiplying side into side
  area = side * side;
  // Calculate perimeter of square by multiplying 4 into side
  perimeter = 4 * side;

  // Output area and perimeter to the console
  System.out.println("Area of Square is : " + area);
  System.out.println("Perimeter of Square is : " + perimeter);
 }
}



Output of the program :



How to compare two or more arrays equality in Java ?.


Program to demonstrate how to compare two or more arrays equality in Java

package com.hubberspot.collections.example;

import java.util.Arrays;

public class CompareArraysEquality {

 public static void main(String[] args) {

  // 1. Lets create three arrays of same size
  String[] array1 = new String[5];
  String[] array2 = new String[5];
  String[] array3 = new String[5];

  // 2. Lets add few strings to each of them 
  array1[0] = "One";
  array1[1] = "Two";
  array1[2] = "Three";
  array1[3] = "Four";
  array1[4] = "Five";

  array2[0] = "A";
  array2[1] = "New";
  array2[2] = "Different";
  array2[3] = "Array";
  array2[4] = "Created";

  array3[0] = "One";
  array3[1] = "Two";
  array3[2] = "Three";
  array3[3] = "Four";
  array3[4] = "Five";

  // 3. Using Arrays.equals() to compare whether
  // arrays are equal or not
  boolean firstCompare = Arrays.equals(array1, array2);
  boolean secondCompare = Arrays.equals(array1, array3);
  boolean thirdCompare = Arrays.equals(array2, array3);

  // 4. printing the result on the console
  System.out.println("array1 equals array2 : " + firstCompare);
  System.out.println("array1 equals array3 : " + secondCompare);
  System.out.println("array2 equals array3 : " + thirdCompare);

 }

}



Output of the program :



How to print collections in the Collections Framework on the console in Java ?.


Program to demonstrate how to print collections in the Collections Framework on the console in Java

package com.hubberspot.example;

// 1. Importing all the highly used Collection 
// classes, Collection and Map interface 
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.Map;
import java.util.TreeMap;
import java.util.TreeSet;

public class PrintingCollections {

 public static void main(String[] args) {

  // 2. Creating an Object of each Collection
  // --- Array ---
  int[] integers = new int[6];

  // --- Array ---
  Collection arrayList = new ArrayList();
  // --- Array ---
  Collection linkedList = new LinkedList();
  // --- Array ---
  Collection hashSet = new HashSet();
  // --- Array ---
  Collection treeSet = new TreeSet();
  // --- Array ---
  Collection linkedHashSet = new LinkedHashSet();

  // --- Array ---
  Map hashMap = new HashMap();
  // --- Array ---
  Map treeMap = new TreeMap();
  // --- Array ---
  Map linkedHashMap = new LinkedHashMap();

  // 3. Adding few elements to described Collections above
  addElements(integers);

  addElements(arrayList);
  addElements(linkedList);
  addElements(hashSet);
  addElements(treeSet);
  addElements(linkedHashSet);

  addElements(hashMap);
  addElements(treeMap);
  addElements(linkedHashMap);

  // 4. Printing all the elements in Collections

  System.out.println("The Collection printing goes like this : \n");

  // 5. Arrays are usually printed by passing whole array to 
  // Arrays class method named as toString()
  System.out.println("Array : "+Arrays.toString(integers));

  // arraylist and linkedlist usually displays elements
  // in order of their entry to Collection
  System.out.println("ArrayList : "+arrayList);
  System.out.println("LinkedList : "+linkedList);

  // hashset doesn't allow duplicate entries to be 
  // inserted in to an collection
  System.out.println("HashSet : "+hashSet);

  // treeset doesn't allow duplicate entries plus it 
  // sorts the elements added to it 
  System.out.println("TreeSet : "+treeSet);

  // linkedhashset doesn't sort the elements but it 
  // displays the order in which the elements were added
  System.out.println("LinkedHashSet : "+linkedHashSet);

  System.out.println("HashMap : "+hashMap);

  // treemap sorts the elements added to it 

  System.out.println("TreeMap : "+treeMap);

  // linkedhashmap doesn't sort the elements but it 
  // displays the order in which the elements were added
  System.out.println("LinkedHashMap : "+linkedHashMap);


 }

 // 6. For adding elements to Collection type created above
 static Collection addElements(Collection collection) {

  collection.add(3);
  collection.add(2);
  collection.add(1);
  collection.add(1);
  collection.add(2);
  collection.add(3);
  return collection;
 }

 //7. For adding elements to Map type created above
 static Map addElements(Map map) {

  map.put(6, "One");
  map.put(5, "Two");
  map.put(4, "Three");
  map.put(3, "Four");
  map.put(2, "Five");
  map.put(1, "Six");
  return map;
 }

 // 8. For adding elements to array type created above
 static int[] addElements(int[] integers) {
  integers[0] = 1;
  integers[1] = 2;
  integers[2] = 3;
  integers[3] = 4;
  integers[4] = 5;
  integers[5] = 6;
  return integers;
 }

}



Output of the program :



How to add or group one collection into another collection in Java ?.

Program to demonstrate how to add or group one collection into another collection in Java

package com.hubberspot.example;

//1. We have to import three Collections
//framework class and interface as 
//ArrayList, Collections and Collection

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;


public class GroupCollectionsDemo {

 public static void main(String[] args) {

  // 2. Creating a Collection reference variable
  // for holding the objects. Collection is interface
  // which is the base interface for all the collections
  // such as ArrayList, Queue etc. Here we have created 
  // an ArrayList object which is holding the Integer objects
  // and its object is been referenced by Collection 
  Collection<Integer> list = new ArrayList<Integer>();

  // 3. Adding six Integer objects to Collection
  list.add(1);
  list.add(2);
  list.add(3);
  list.add(4);
  list.add(5);
  list.add(6);

  // 4. Creating yet another array collection and adding six 
  //Integer objects to it
  Integer[] array = new Integer[6];
  array[0] = 7;
  array[1] = 8;
  array[2] = 9;
  array[3] = 10;
  array[4] = 11;
  array[5] = 12;

  // 5. Looping each Collection object and printing it on 
  // console
  System.out.println("Elements in Collection before adding :");
  for(Integer i : list) {
   System.out.print(i + " ");
  }
  System.out.println("\n");

  // 6. Using Collections class addAll() method to add array of
  // Integers to the list Collection 
  Collections.addAll(list, array);

  System.out.println("Elements in Collection after adding :");

  // 7. Looping each Collection object after adding 
  // Integer array to it and printing it on 
  // console
  for(Integer i : list) {
   System.out.print(i + " ");
  }
  System.out.println("\n");

  // 8. Using Collections class addAll() method to add some
  // more integers to it after adding an array of
  // Integers to the list Collection
  Collections.addAll(list, 13,14,15,16,17,18);


  // 9. Looping each Collection object after adding 
  // Integer array to it plus some more integers 
  // to it and printing it on 
  // console

  System.out.println("Elements in Collection after adding more elements :");
  for(Integer i : list) {
   System.out.print(i + " ");
  }
 }
}



Output of the program :



How to use transient keyword in a Java program ?.

Program to demonstrate how to use transient keyword in a Java program.
Program actual working is shown here if we have not placed transient keyword. After we use transient keyword the program would have behaved as below see the difference ---

package com.hubberspot.example;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

// 1. Create a Pojo class say User which 
// implements Serializable Interface
// Implementing this interface is must as 
// this interface tells JVM that its object can
// be serialized. This interface has no methods and 
// it acts as Marker Interface.

class User implements Serializable {

 // 2. Have a few properties to it ...
 // two of them email and password as transient
 private String firstName;
 private String lastName;

 private transient String email;
 private transient String password;


 // 3. Have a constructor which can set properties of it 
 // We can even use setter methods for the same
 public User(String firstName, String lastName, String email, String password) {
  super();
  this.firstName = firstName;
  this.lastName = lastName;
  this.email = email;
  this.password = password;
 }

 // 4. Have getters and setters for each property
 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 public String getEmail() {
  return email;
 }

 public void setEmail(String email) {
  this.email = email;
 }

 public String getPassword() {
  return password;
 }

 public void setPassword(String password) {
  this.password = password;
 }

}

// 5. Create a Test class which can store object of
// User into a text file and read it back again 
// thus proves that object state was saved into the 
// text file and after its destruction, its state was 
// gained by reading the object stored state in the 
// user.txt

public class StoreAObject {

 public static void main(String[] args) {

  try {

   // 6. Create a FileOutputStream Object by passing text file
   // name which will be used to store the object state

   FileOutputStream fos = new FileOutputStream("user.txt");

   // 7. Create a ObjectOutputStream object which wraps 
   // object of FileOutputStream thus helping to pass object 
   // to a text file.
   ObjectOutputStream oos = new ObjectOutputStream(fos);

   // 8. Create a User object by passing the dummy values to 
   // its constructor
   User user = new User("Jonty", "Magic", "Jonty@Magic.com", "password");

   // 9. Calling the writeObject method present in the ObjectOutputStream
   // which will save the object state into the text file created above
   oos.writeObject(user);


   // 10. Flushing and closing the ObjectOutputStream
   // as they are very critical resource
   oos.flush();
   oos.close();

   // 11. Assigning the user object to null so that its actual
   // object goes into unreachable state in heap ... similar to 
   // destruction of object in this case
   user = null;

   // 12. Create a FileInputStream Object by passing text file
   // name which will be used to read the state of the object 

   FileInputStream fis = new FileInputStream("user.txt");

   // 13. Create a ObjectInputStream object which wraps 
   // object of FileInputStream thus helping to pass object 
   // state from text file to Object

   ObjectInputStream ois = new ObjectInputStream(fis);

   // 14. In order to read the User object we will use the 
   // ObjectInputStream.readObject() method. After this method gets 
   // executed it reads object state from text file and return a object
   // of type Object so we need to cast it back the its origin class, 
   // the User class.
   user = (User) ois.readObject();

   // 15. After getting back the required object back, in order to prove
   // the result we outputs its state to console. The usage of transient 
   // variable is visible when we print out email and password at the 
   // console. The output at console shows that state of email and password
   // isnt retrieve and stored in text file and default values are set
   System.out.println("First Name : " + user.getFirstName());
   System.out.println("Last Name : " + user.getLastName());
   System.out.println("Email : " + user.getEmail());
   System.out.println("Password : " + user.getPassword());

   // closing the critical resources
   ois.close();
  } catch (IOException e) {
   e.printStackTrace();
  } catch (ClassNotFoundException e) {
   e.printStackTrace();
  }
 }

}



Output of the program at the console :



















State of object in a text file :  



How to access Temporary Directory and delete its files through a Java program ?.


Program to demonstrate how to access Temporary Directory and delete its files through a Java program.

package com.hubberspot.example;

import java.io.File;


public class TemporaryDirectory {

 public static void main(String[] args) {

  // 1. Create a Properties refernce pointing to 
  // System.getproperties() as this method returns all
  // the System properties
  java.util.Properties properties = System.getProperties();

  // 2. System class has a property by name "java.io.tmpdir"
  // which returns String which is the name of the location
  // of temp directory. See the output for my machine's temp
  // directory
  System.out.println(properties.getProperty("java.io.tmpdir"));

  String tempFileName = properties.getProperty("java.io.tmpdir");

  // 3. Create a File object which will point to this temp 
  // directory.
  File directory = new File(tempFileName);

  // 4. Get all files in directory using the method listFiles()
  File[] files = directory.listFiles();

  // 5. Loop through each file and call delete() on it

  for (File file : files)
  {
   // 6. This will loop each file/directory and delete file
   file.delete();

   // 7. If it cannot delete the file it prints the name 
   // of file it cant delete
   if (!file.delete())
   {   
    System.out.println("Failed to delete "+file);
   }
  }


 }

}



Output of the program :



How to terminate a program using System and Runtime class in Java ?.

Program to demonstrate how to terminate a program using System and Runtime class in Java

package com.hubberspot.example;

public class JavaTerminate {

 public static void main(String[] args) {

  int i = 0;

  if (i > 0) {
   // 1. In order to terminate a Java Application
   // we can use System.exit(int) to exit a Java 
   // Application.
   System.exit(i);
  }
  else {
   // 2. In order to terminate a Java Application
   // another way we can use is creating a Runtime Object
   // and calling exit(int) of Runtime to terminate the Java 
   // Application.
   Runtime runtime = Runtime.getRuntime();
   runtime.exit(i);
  }

 }

}



How to read a file using java.util.Scanner class in Java through a simple program ?.

A simple Java program demonstrating how to read a file using java.util.Scanner class.

1. Create a text file say demo as customer.txt below -

a. customer.txt


-------Customer Details -------

First Name : Jonty
Last Name  : Magic
Email      : Jonty@Magicman

-------------------------------



2. Create a Java class to read customer.txt file -

package com.hubberspot.example;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;


public class ScannerExample {

 public static void main(String[] args) {

  try {
   // Creating a file with a name customer.txt
   // placed in the root folder of your Java 
   // project in eclipse
   // Storing the name of file as a String
   String fileName = "customer.txt";

   // Creating a File object by passing it a 
   // String containing the name of file
   File file = new File(fileName);

   // Creating a Scanner object using a constructor
   // which takes the file object. There are various 
   // constructors for Scanner class for different
   // purposes. We want to use Scanner class to read
   // data from a file on the system, So we are using 
   // a constructor which is taking an File object
   Scanner scanner = new Scanner(file);

   // Scanner class has many methods for scanning file
   // line-by-line. We use hasNextLine method which returns
   // true if there is yet another line to be read. putting the
   // condition in the while loop we traverse file line by line
   // and as soon as new line is figured out, we capture it by 
   // Scanner class's nextLine method and prints it on the console
   while(scanner.hasNextLine()) {
    String readLine = scanner.nextLine();
    System.out.println(readLine);
   }
  }
  catch (FileNotFoundException e) {

   e.printStackTrace();
  }

 }

}




Output of the program at the console :



How to use Jsp action elements useBean, setProperty and getProperty to add, set and get property of a bean in a JSP page ?.

A simple Web-Application showing how to use action jsp action elements useBean, setProperty and getProperty to add, set and get property of a bean in a JSP page


Create a simple JavaBean by name User.java

package com.hubberspot.bean;


public class User {

 private String firstName;
 private String lastName;
 private String email;
 private String password;

 public User() {

 }

 public String getFirstName() {
  return firstName;
 }

 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }

 public String getLastName() {
  return lastName;
 }

 public void setLastName(String lastName) {
  this.lastName = lastName;
 }

 public String getEmail() {
  return email;
 }

 public void setEmail(String email) {
  this.email = email;
 }

 public String getPassword() {
  return password;
 }

 public void setPassword(String password) {
  this.password = password;
 }

}



Create style.css file

 body {
  font-family: Verdana, Geneva, Arial, helvetica, sans-serif;
  background-color: #FDF4DF;
  font-size: 14px;
  color: #333333;
 }
 
 td {
  font-family: Verdana, Geneva, Arial, helvetica, sans-serif;
  font-size: 14px;
 }
 
 .small {
  font-family: Verdana, Arial, Helvetica, sans-serif;
  font-size: 12px;
  font-weight: bold;
 }



Create user.jsp file



1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>User Details !!!</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
    <form method="post" action="done.jsp">
        <p>&nbsp;</p>
        <p class="small" align="left">Enter Your Details !!!</p>
        <table align="left" bgcolor="#728DCF">
            <tr>
                <td class="small">First Name</td>
                <td><input name="firstName" size=25 class="small"></td>
            </tr>
            <tr>
                <td class="small">Last Name</td>
                <td><input name="lastName" size=25 class="small"></td>
            </tr>
            <tr>
                <td class="small">Email</td>
                <td><input name="email" size=25 class="small"></td>
            </tr>
            <tr>
                <td class="small">Password</td>
                <td><input name=password type="password" size=25 class="small"></td>
            </tr>

            <tr>
                <td colspan="2" align="center"><input type="submit"
                    value="Update" /></td>
            </tr>
        </table>
    </form>
</body>
</html>


Create done.jsp file



1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>User Confirm !!!</title>
<link href="style.css" rel="stylesheet" type="text/css">
</head>
<body>
    <p>&nbsp;</p>
    <p class="small" align="left">Details You Entered !!!</p>

    <jsp:useBean id="user" scope="request" class="com.hubberspot.bean.User">
        <jsp:setProperty property="firstName" name="user" />
        <jsp:setProperty property="lastName" name="user" />
        <jsp:setProperty property="email" name="user" />
        <jsp:setProperty property="password" name="user" />
    </jsp:useBean>
    <table align="left" bgcolor="#728DCF">
        <tr>
            <td class="small">First Name -</td>
            <td><jsp:getProperty name="user" property="firstName" /></td>
        </tr>
        <tr>
            <td class="small">Last Name -</td>
            <td><jsp:getProperty name="user" property="lastName" /></td>
        </tr>
        <tr>
            <td class="small">Email -</td>
            <td><jsp:getProperty name="user" property="email" /></td>
        </tr>
        <tr>
            <td class="small">Password -</td>
            <td><jsp:getProperty name="user" property="password" /></td>
        </tr>
    </table>

</body>
</html>

After running JSP's on browser :






















 On Updating the User details :




How to include one JSP into another JSP ?.

A simple Web-Application demonstrating how to include one jsp page into another jsp.



1. Create a JSP : index.jsp


1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login Page !!!!</title>
</head>
<body>
    <h1></h1>
    <jsp:include page="/welcome.jsp">
        <jsp:param name="firstName" value="Enter First Name" />
        <jsp:param name="lastName" value="Enter Last Name" />
    </jsp:include>
    <hr>
    <h2>welcome.jsp page gets included along with parameters</h2>
</body>
</html>

2. Create a JSP : welcome.jsp


1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>A User Input Page !!!</title>
</head>
<body bgcolor="#ADB1A9">
    
    <form method="POST" action="xxx.jsp">
        
        First Name : <input type="text" id="firstName"
            value='<%=request.getParameter("firstName")%>' /><br> 
        
        Last Name : <input type="text" id="lastName"
            value='<%=request.getParameter("lastName")%>' /><br> <br>

        <input type="submit" value="Submit" />
    </form>

</body>
</html>


Output of the program :


As soon as user request for index.jsp page, the request goes to index.jsp and there it finds that it has included a page welcome.jsp by the use of jsp:include tag along with the necessary parameters with it. The control internally brings welcome.jsp to index.jsp and the rendered page of welcome.jsp is visible at the browser. 



How to forward a request from one Jsp to another Jsp ?.

A simple Web-Application demonstrating how to forward a request from one jsp page to another jsp.

1. Create a JSP : index.jsp


1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login Page !!!!</title>
</head>
<body>
 <jsp:forward page="/welcome.jsp">
  <jsp:param name="firstName" value="Enter First Nam" />
  <jsp:param name="lastName" value="Enter Last Name" />
 </jsp:forward>
 <h1>This wont print as control forwards to welcome.jsp page</h1>
</body>
</html>

2. Create a JSP : welcome.jsp


1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>A User Input Page !!!</title>
</head>
<body bgcolor="#ADB1A9">

 <form method="POST" action="xxx.jsp">

  First Name : <input type="text" id="firstName"
   value='<%=request.getParameter("firstName")%>' /><br> 
    Last Name : <input type="text" id="lastName"
   value='<%=request.getParameter("lastName")%>' /><br> <br>

  <input type="submit" value="Submit" />
 </form>

</body>
</html>

Output of the program : 

As soon as user request for index.jsp page, the request goes to index.jsp and there it finds that it is been forwarded to welcome.jsp by the use of jsp:forward tag along with the necessary parameters with it. The control internally forwards to welcome.jsp and the rendered page of welcome.jsp is visible at the browser. Note : As soon as forward request comes the execution of calling JSP page gets stopped and request gets forwarded to another JSP. Here output shows that the last H1 tag doesn't gets outputted on the browser. 





How to calculate minimum and maximum of a number using Math class in Java ?.

Program to demonstrate how to calculate minimum and maximum of a number using Math class in Java

package com.hubberspot.code;

import java.util.Scanner;


public class MinMaxDemo {

 public static void main(String[] args) {

  // In order to calculate minimum and maximum of
  // number from the two numbers we use max and min 
  // method of Math class

  // Create a Scanner object which takes System.in object
  // this makes us read values from the console
  // We will ask user to input two numbers
  Scanner scanner = new Scanner(System.in);

  // Prompting user to enter first number ... 
  System.out.println("Enter the first number : ");
  double number1 = 0;
  // Scanner objects nextDouble reads output from the console
  // entered by user and stores into the double variable
  number1 = scanner.nextDouble();  

  // Prompting user to enter second number ... 
  System.out.println("Enter the second number : ");
  double number2 = 0;
  number2 = scanner.nextDouble();

  System.out.println("Calculating Minimum and Maximum number " +
    "from the two numbers entered.... ");

  System.out.println();

  // Math.max method calculates the maximum number from the 
  // two numbers passed to it as a argument
  // Math.min method calculates the minimum number from the 
  // two numbers passed to it as a argument

  double maximum = Math.max(number1, number2);
  double minimum = Math.min(number1, number2);

  System.out.println("Maximum number from the numbers " 
    + number1 + " and " + number2 + " is : " + maximum);
  System.out.println("Minimum number from the numbers " 
    + number1 + " and " + number2 + " is : " + minimum);

 }

}



Output of the program : 


 

How to create a thread by extending the Thread class ?.

Program to demonstrate creation of a thread by extending the Thread class in Java

package com.hubberspot.multithreading;

public class ProducerConsumerTest {


 public static void main(String[] args) {
  // 3. Create a thread by instantiating
  // an object from the class
  Thread producer = new Producer();
  Thread consumer = new Consumer();

  // 4. Call the start() method of the 
  // thread object
  producer.start();
  consumer.start();
  // Overall three threads are created 
  // 1. for main method , 2. for the Producer class
  // 3. for the Consumer class  

 }

}

// 1. Create a class that extends Thread
class Producer extends Thread {
 // 2. Overload the run method to perform 
 // the desired task
 public void run(){

  for (int i = 0; i < 10; i++){

   System.out.println("I am Producer : Produced Apple " + i);
   // static method that pause current thread so that other thread
   // gets the time to execute
   Thread.yield();   
  }

 }
}

class Consumer extends Thread {
 public void run(){

  for (int i = 0; i < 10; i++){

   System.out.println("I am Consumer : Consumed Apple " + i);
   Thread.yield();

  }

 }
}


Output of the program : 
 


How to perform Factorial caching in a Java application ?.

A simple program to demonstrate how to do Factorial caching in Java

package com.hubberspot.example;

import java.util.Scanner;

public class FactorialCaching {

 // an array of long values to cache the factorial values
 public static long[] factorial = new long[21];

 // a loop counter that counts till end of number for 
 // which we want to calculate factorial
 public static int fact = 0;

 // static initializer block, the block of executes as 
 // soon as the class is loaded into the memory for 
 // the first time. Here it initializes value of first
 // element of array to be 1 as factorial of 1 is 1
 static { 
  factorial[0] = 1; 
 }     

 // method where the logic for factorial 
 // calculations goes. It takes a argument which
 // is the number passed for which we want to 
 // calculate the factorial
 public static long factorial(int x) {

  // fact goes from zero to number-1 for which we want to 
  // calculate the factorial
  while(fact < x) {

   // applying formula as 3! = 3 * 2!
   factorial[fact + 1] = factorial[fact] * (fact + 1);

   // increment the fact for next value
   fact++;
  }

  // return the result
  return factorial[x];
 }

 public static void main(String[] args) {

  // Create a Scanner object to read input from console
  Scanner scanner = new Scanner(System.in);

  // prompt the user to enter the number for which factorial
  // is to be calculated
  System.out.println("Enter the number for which you " +
    "want to calculate factorial -  ");

  // prompting the user to enter number between 0 to 20 
  System.out.println("Note : \"The number should range " +
    "from 0 to 20\"");

  // store the number entered into number variable
  int number = scanner.nextInt();

  // For the first time call factorial method to store
  // values into the array of calculated factorials
  long result = FactorialCaching.factorial(number);

  // the result displayed on the console
  System.out.println("The factorial of "+ number +" : " + result);

  System.out.println();
  System.out.println("Enter the another number for which you " +
    "want to calculate factorial -  ");

  // prompting the user to enter number between 0 to 20 
  System.out.println("Note : \"The number should range " +
    "from 0 to "+number+"\"");

  // store the number entered into number variable
  number = scanner.nextInt();

  // After first call to factorial method next time 
  // we just access the factorial by accessing the 
  // long array through index
  System.out.println("The factorial after caching is done : " 
    + FactorialCaching.factorial[number]);

 }

}


Output of the program : 


 
 
© 2021 Learn Java by Examples Template by Hubberspot