Free Data Structures and Algorithms Course









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










OR



Subscribe to all free courses
Showing posts with label Objects and Classes. Show all posts
Showing posts with label Objects and Classes. Show all posts

Java Serializable interface : Reading and writing Objects to a file video tutorial




Video tutorial to demonstrate Java Serializable interface : Reading and writing Objects to a file.








How to Install Java JDK and Eclipse Keplar IDE ?.

A video tutorial to demonstrate how to Install Java JDK and Eclipse Keplar IDE.





How to implement Object Oriented Programming Encapsulation feature in Java programming language?

Program to demonstrate how to implement Object Oriented Programming Encapsulation feature in Java programming language.

package com.hubberspot.oops;

public class Student {

 private String name;
 private int marks;
 private int age;

 public int getMarks() {
  return marks;
 }

 // By encapsulation instance variables we can 
 // safely implement security variables data.
 // Data's integrity is maintained as we can set 
 // and get value of instance variable through
 // getters and setters
 // It also prevent unwanted access of variables to other
 // classes which can corrupt the data.
 public void setMarks(int marks) throws MarkException{

  if(marks >= 0){
   this.marks = marks;
  }
  else { 
   throw new MarkException("Marks cannot be negative");
  }
 }

 public int getAge() {
  return age;
 }

 public void setAge(int age) throws IllegalAgeException {

  if(age >= 0){
   this.marks = marks;
  }
  else { 
   throw new IllegalAgeException("Age cannot be negative");
  }
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }
}



How to demonstrate Polymorphism through a simple Java program ?.

Program to demonstrate how to implement Polymorphism in Java.

package com.hubberspot.examples;

class Shape {

 public void draw(){

  System.out.println("Shape drawn ... ");

 }

}

class Rectangle extends Shape {

 public void draw(){

  System.out.println("Rectangle drawn ... ");

 }
}

class Circle extends Shape {

 public void draw(){

  System.out.println("Circle drawn ... ");

 }

}

// Polymorphism implementing class 
// Performing decoupling as well
// Later in design if a new shape appears
// the functionality of the class has 
// decoupled the object creation hardcoding 
// to a polymorphic way using setShape() 
// and drawShape()
class Drawing {

 private Shape s;

 // Setting polymorphic behavior and 
 // this class doesnt care which shape
 // it is.
 public void setShape(Shape s) {

  this.s = s;

 }

 public void drawShape() {

  this.s.draw();

 }
}


public class Test {

 public static void main(String[] args) {

  Rectangle rectangle = new Rectangle();
  Circle circle = new Circle();

  Drawing drawing = new Drawing();

  drawing.setShape(rectangle);
  drawing.drawShape();

  drawing.setShape(circle);
  drawing.drawShape();

 }
}



Output of the program :



How to implement Comparable Interface in Java with an example ?

Program to demonstrate how to implement Comparable Interface in Java with an example.

package com.hubberspot.code;

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

public class Student implements Comparable {

 public String name;
 public double percentage;

 Student(String name, double percentage)
 {
  this.name = name; 
  this.percentage = percentage;
 }

 public String toString()
 {
  return "\nName = " + name + "\n"+
    "Percentage = " + percentage+"\n";
 }


 @Override
 public int compareTo(Object o) {
  Student other = (Student) o;

  Double percentage1 = (Double) this.percentage;
  Double percentage2 = (Double) other.percentage;

  return percentage1.compareTo(percentage2);

 }


 public static void main(String[] args) {

  ArrayList list = new ArrayList();

  list.add(new Student("Dinesh",76.2));
  list.add(new Student("Jonty",96.5));
  list.add(new Student("Gunjan",81.7));
  list.add(new Student("Parishrut",62.1));

  System.out.println("Before Sorting : \n" + list);

  Collections.sort(list);

  System.out.println("\nAfter Sorting : \n" + list);

 }
}



Output of the program :



How to convert String to primitive char array and print it on the console through a Java program ?.

Program to demonstrate how to convert String to primitive char array and print it on the console through a Java program.


package com.hubberspot.examples;

public class StringToCharArrayDemo {

 public static void main(String[] args) {

  // Create a String object with any value
  String welcome = "Hello !!!. Welcome to Hubberspot.com !!!.";

  // Print the String on the console
  System.out.println("String used is : " + welcome);

  // In order to convert String to char array - 
  // String class has a method by name as : toCharArray()
  // This method returns back an array which holds characters
  // of String.
  char[] message = welcome.toCharArray();

  System.out.println("\nString converted to char array : ");

  // Looping over each character in message array created above.
  // Printing each character one by one.
  for(char character : message) {

   System.out.print(character);

  }
 }
}




Output of the program : 


 

How to demonstrate working of intern() method in String class through a example ?.

Program to demonstrate working of intern() method in String class through a example.

package com.hubberspot.examples;

public class InternDemo {

 public static void main(String[] args) {

  // Using new String() each time the line 
  // executes a new instance is created
  // Avoid this kind of usage of String
  // creation
  String name1 = new String("Hubberspot");

  // String instance should be created by 
  // below statement. It maintains and avoids
  // new creation of instance each time 
  // the line gets executed.
  String name2 = "Hubberspot";

  // Before calling intern() method lets test reference value
  // equality of both name1 and name2 String objects.
  if(name1 == name2){

   System.out.println("Before calling intern() : name1 == name2 is true");

  }
  else {

   System.out.println("Before calling intern() : name1 == name2 is false");

  }

  // Whenever an String object is created by using new operator
  // always a new object gets created in the heap whether 
  // it has same value or not. 
  // Whenever an String object is created by using "" a constant
  // string object gets created in the heap memory.
  // The difference is shown by above example i.e before calling
  // intern() method.

  // When the intern method is invoked, if the pool already 
  // contains a string equal to this String object as determined 
  // by the equals(Object) method, then the string from the pool 
  // is returned. Otherwise, this String object is added to the 
  // pool and a reference to this String object is returned. 
  name1 = name1.intern();

  // After intern method gets executed name1 is added to the 
  // String constant pool and reference is returned back to 
  // name1.
  // Below results shows the variation in the result ... 
  if(name1 == name2){

   System.out.println("After calling intern() : name1 == name2 is true");

  }
  else {

   System.out.println("After calling intern() : name1 == name2 is false");

  }
 }
}



Output of the program :


How to determine whether a file name ends with a given string in Java ?.

Program to demonstrate how to determine whether a file name ends with a given string in Java

package com.hubberspot.code;

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

public class FileType {

 public static void main(String[] args) {

  try {
   // Creating a file with a name files.txt
   // placed in the root folder of your Java 
   // project in eclipse
   // Storing the name of file as a String
   String fileName = "files.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 files = scanner.nextLine();

    System.out.print(files +" is a ");

    // findFileType() takes in a string which is 
    // name of the file read from the files.txt
    findFileType(files);

   }
  }
  catch (FileNotFoundException e) {

   e.printStackTrace();
  }

 }

 // This method uses String class endsWith() method
 // taking in the string by which file name ends.
 // It uses this string to search for a substring 
 // in the name of file that whether its of particular
 // type or not
 public static void findFileType(String fileName) {

  if(fileName.endsWith(".txt")){
   System.out.println("Text file");
  } 
  else if (fileName.endsWith(".doc")){
   System.out.println("Document file");
  }
  else if (fileName.endsWith(".ppt")){
   System.out.println("Presentation file");
  }
  else if (fileName.endsWith(".xls")){
   System.out.println("Excel file");
  } 
  else if (fileName.endsWith(".java")){
   System.out.println("Java source file");
  } 
  else {
   System.out.println("Other type of file");
  }
 }
}






a) files.txt :-

 










b) Output of the program :

How to search a text for regular expression using matches method in Java's String class


Program to demonstrate how to search a text for regular expression using matches method in Java's String class

package com.hubberspot.code;

public class MatchesDemo {

 public static void main(String[] args) {

  // Lets create a String. We have a long text assigned to it. 
  String text = "Welcome to Hubberspot 1.0 !";

  // String class has a method called as matches()
  // this method is been called over a String and takes
  // a parameter which is a regular expression. 
  // It returns a boolean value true or false whether or not 
  // string matches the given regular expression.
  // In the result variable below for the 1 it returns true 
  // because the regular expression passed is the exact match 
  // to the string
  boolean result = text.matches("Welcome to Hubberspot 1.0 !");
  System.out.println("1. : "+result);

  // for 2 result variable holds false because the regular 
  // expression passed is not the exact match to the string 
  result = text.matches("Welcome");
  System.out.println("2. : "+result);

  // for 3 result variable holds true because the regular
  // expression will test against both upper & lower case "W" and "H"
  // and will return true
  result = text.matches("[Ww]elcome to [Hh]ubberspot 1.0 !");
  System.out.println("3. : "+result);

  // for 4 result variable holds true because the regular
  // expression will test against a number checking whether 
  // it is in between 0 to 9
  result = text.matches("Welcome to Hubberspot [0-9].[0-9] !");
  System.out.println("4. : "+result);

  // for 5 result variable holds true because the regular
  // expression will test against alphanumeric combination
  // and will be used with any word holding .*
  result = text.matches("Welcome to .* [0-9].[0-9] !");
  System.out.println("5. : "+result);

 }
}



Output of the program :



How Static Initializer block works in Java through a simple program?.


Program to demonstrate working of Static Initializer block in Java.

package com.hubberspot.code;

public class StaticInitializationTest {

 // static instance variable
 public static int x = 5;

 // static initialization block
 // it gets executed as soon as 
 // class loads
 static {

  System.out.println("In static initialization block");  
  System.out.println("static instance variable x = " + x);

 }

 public static void main(String[] args) {

  // main method is called by JVM after executing
  // the static initialization block of code
  System.out.println("In the main method");
 }
}



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 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 add and subtract hour to current hours using Calendar class in Java ?.

Program to demonstrate addition and subtraction of hours to current hour of the day using Calendar class in Java


package com.hubberspot.example;

import java.util.Calendar;


public class TimeManipulation {

 public static void main(String[] args) {

  // Create a Calendar object
  Calendar calendar = Calendar.getInstance();

  // Get current day from calendar
  int day = calendar.get(Calendar.DATE);
  // Get current month from calendar
  int month = calendar.get(Calendar.MONTH) + 1;  
  // Get current year from calendar
  int year = calendar.get(Calendar.YEAR);

  System.out.print("Today's Date : ");
  // printing todays date in dd/mm/yy
  System.out.println(day+"/"+month+"/"+year);

  // Get current hour from calendar
  int hour = calendar.get(Calendar.HOUR_OF_DAY);
  // Get current minute from calendar
  int minutes = calendar.get(Calendar.MINUTE);
  // Get current second from calendar
  int seconds = calendar.get(Calendar.SECOND);

  System.out.print("Current Time : ");
  // printing current time in hh:mm:ss
  System.out.println(hour+":"+minutes+":"+seconds);

  // adding 6 hours to current hour of the day
  calendar.add(Calendar.HOUR_OF_DAY, 6);

  hour = calendar.get(Calendar.HOUR_OF_DAY);
  minutes = calendar.get(Calendar.MINUTE);
  seconds = calendar.get(Calendar.SECOND);

  System.out.print("Time after 6 hours : ");
  // printing time after 6 hours
  System.out.println(hour+":"+minutes+":"+seconds);

  // Calendar class automatically adjust date if 
  // on adding hours makes a date change
  day = calendar.get(Calendar.DATE);
  month = calendar.get(Calendar.MONTH) + 1;  
  year = calendar.get(Calendar.YEAR);

  System.out.print("Date after 6 hours : ");
  // printing date after 6 hours in dd/mm/yy
  System.out.println(day+"/"+month+"/"+year);

  // as our current hour is set to 6 hours plus from
  // the current hour , in order to subtract 6 
  // hours from current hour minus it with 12 
  calendar.add(Calendar.HOUR_OF_DAY, -12);

  hour = calendar.get(Calendar.HOUR_OF_DAY);
  minutes = calendar.get(Calendar.MINUTE);
  seconds = calendar.get(Calendar.SECOND);

  System.out.print("Time before 6 hours : ");
  // printing time after subtraction in hh:mm:ss
  System.out.println(hour+":"+minutes+":"+seconds);

 }

}




Output of the program :



How to check if a character is an Uppercase or Lowercase letter in a Java program ?.

Java program to demonstrate how to check if a character is an Uppercase or Lowercase letter.

package com.hubberspot.example;


public class IsUpperLowerCaseTest {

   public static void main(String[] args) {
        // Create a String of character having mixture of 
     // upper-case, lower-case letters, digits and symbols
 // in between just for a test
 String characters = "hH1u2U3b4B5b sS9pPo0Ot^%T";

 // we take the length of characters by length()
 int length = characters.length();

 // we than loop each character one by one 
 for(int i = 0; i < length; i++) {
    // we store each character in a variable
    // for each loop
    char character = characters.charAt(i);
         
    // checking for each character that its a Upper-case or Lower-case
    // letter or not by calling Character class isUpperCase() method,
    // and isLowerCase() by passing the character. It returns true 
    // if the character passed is lower-case or upper-case and false 
    // if not separately
    if(Character.isUpperCase(character)) {
         System.out.println("Given character : " + characters.charAt(i)
    + " is an Uppercase letter");
    }
    else if(Character.isLowerCase(character)) {
  System.out.println("Given character : " + characters.charAt(i)
    + " is a Lowercase letter");
    }
    else {
  System.out.println("Given character : " + characters.charAt(i)
    + " is neither Uppercase nor Lowercase letter");
    }
       }

   }

}


Output of the program : 


 

How to get field, set and get its value by using Field class in Java Reflection API ?

Program to demonstrate working of Field class in Java Reflection API for getting field, setting and getting its value

package com.hubberspot.example;

import java.lang.reflect.Field;

class Customer {
 public String firstname;
 public String lastname;
 public String email;
 public static int counter;
}

public class FieldDemo {
 
   public static void main(String[] args) {
  
 // Create a test object. We can create
 // and apply reflection on any class 
 // we want without knowing which fields
 // it has. We are taking Customer here.
 Customer customer =  new Customer();
  
 // Getting Class associated with Customer
 Class demo = customer.getClass();
  
 try {   
  
 // Using Field class we can get field of any
 // class we want. Here we are getting field
 // firstname by calling getField method of the
 // Class associated with Customer 
  Field field = demo.getField("firstname");
   
 // After getting the field we are assigning it
 // with a value by using set method of Field
 // First parameter is the Object of Customer and
 // second parameter is the value we want to set 
  field.set(customer, "Jonty");
  
 // After assignment we are getting the value back
 // by using get method of Field and passing the 
 // Object of Customer for which we want the value 
  Object result = field.get(customer);
  
 // printing it to console
  System.out.println("Customer First Name is : "
        + result);
   
 // similarly doing for lastname and email 
  field = demo.getField("lastname");
  field.set(customer, "Magicman");
                result = field.get(customer);
  System.out.println("Customer Last Name is : "
        + result);
   
  field = demo.getField("email");
  field.set(customer, "Jonty@Magic.com");
  result = field.get(customer);
         System.out.println("Customer Email is : "
        + result);
     
  field = demo.getField("counter");
 // while working with static we are not passing
 // Object as Customer instance but we are 
 // passing it a null because its static field 
  field.set(null, 1);
  result = field.get(null);
  System.out.println("Customer Counter is : "
        + result);
  
 } catch (SecurityException e) {
   
  e.printStackTrace();
  
 } catch (NoSuchFieldException e) {
   
  e.printStackTrace();
  
 } catch (IllegalArgumentException e) {
   
  e.printStackTrace();
  
 } catch (IllegalAccessException e) {
   
  e.printStackTrace();
  
 }

   }

}




Output of the program :



How to make a Java class immutable ?


Program to demonstrate how to make and code a Java Class Immutable

package com.hubberspot.example;

// 1. Create a class with final keyword
// so that no other class can extend this
// class, to change the state of class
final class Product {

 // 2. Create variables with final keyword
 // so that once values are assigned to it 
 // they cannot be modified
 private final String name;
 private final int count;

 // 3. Create a public constructor which sets
 // the state of these variables
 public Product(String name, int count) {
  this.name = name;
  this.count = count;
 }

 // 4. Generate only the getters method and 
 // no setters, so that no application calling class
 // can change the state of variables
 public String getName() {
  return name;
 }

 public int getCount() {
  return count;
 } 
}

public class ImmutableExample {

 public static void main(String[] args) {

  // 5. Create a Product and assign values in 
  // its constructor
  Product product = new Product("pen" , 1);

  System.out.println(product.getName());
  System.out.println(product.getCount());  

  // 7. No way for the application class
  // to change the state of Product class
  // as there are no setters or a way to 
  // extend the final class , thus immutable
  // class is created
 }
}





Video tutorial to demonstrate how to make a Java class immutable.








How to store and retrieve objects in a text file by a simple Java program ?.

Program to demonstrate how to store and retrieve objects in a text file in Java

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 ... 
 private String firstName;
 private String lastName;
 private String email;
 private 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.
   System.out.println("First Name : " + user.getFirstName());
   System.out.println("Last Name : " + user.getLastName());
   System.out.println("Email : " + user.getEmail());
   System.out.println("Phone : " + 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 :  







Video tutorial to demonstrate Java Serializable interface : Reading and writing Objects to a file.









How to Capture Screen through a Java program using Robot class ?.

Program to demonstrate screen capture through a Java program using Robot class.

package com.hubberspot.example;

import java.awt.AWTException;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class RobotScreenCapture {
 
   public static void main(String[] args) {
  
 try {
   
 // 1. Create a Robot Object 
 Robot robot = new Robot();
        // 2. Create a Dimension Object for the screen capture 
 // by providing width and height for the screen area 
 Dimension dimension = new Dimension(300,300);
 // 3. Create a Rectangle by taking the dimension reference
 // to create a screen capture of area specified by dimension 
 Rectangle screen = new Rectangle(dimension);
 // 4. Calling createScreenCapture method of Robot class by 
 // passing it Rectangle reference. It will return a reference 
 // to a BufferedImage Object.  
 BufferedImage buffer = robot.createScreenCapture(screen);
 // 5. Create a file to store the image 
 File screenCapture = new File("screen.jpg");
 // 6. Call the write method of ImageIO class by passing
 // it BufferedImage and File created above 
 ImageIO.write(buffer, "jpg", screenCapture);
   
 } catch (AWTException e) {   
  e.printStackTrace();
 } catch (IOException e) {  
  e.printStackTrace();
 } 

   }

}




Output of the program :



How to get color of a Screen through Robot class in Java ?

A simple program to demonstrate capturing of pixel colors of screen in Java

package com.hubberspot.example;

import java.awt.AWTException;
import java.awt.Color;
import java.awt.Robot;

public class RobotColorDemo {
 
   public static void main(String[] args) {
  
      try {
 // Create a Robot object
        Robot robot = new Robot();

        // Robot class has method getPixelColor which takes
        // two parameters as (x,y) x for X position of pixel
        // and y for Y position of pixel and it returns back  
        // refernce to object of Color which is stored in color         
            
        Color color = robot.getPixelColor(100, 100);

        // Color class has methods such as getRed() , getGreen() 
        // and getGreen() and getBlue() method which prints RGB 
        //  information of the pixel color
            
        System.out.println("Red color of pixel   = " + color.getRed());
        System.out.println("Green color of pixel = " + color.getGreen());
        System.out.println("Blue color of pixel  = " + color.getBlue());

     } 
     catch (AWTException e) {
        e.printStackTrace();
     }

   }

}




Output of the program :




How to Play an MP3 File in Java ?

In order to play Mp3 files in Java , you need to download  jl1.0.jar from the website  javazoom.net. After downloading put the jar into Eclipse or Netbeans buildpath and execute below code.


Program to demonstrate how to play Mp3 files in Java

package com.hubberspot.example;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import javazoom.jl.player.Player;


public class Mp3Player {
   
    private String filename;
    private Player player; 


    public Mp3Player(String filename) {
 this.filename = filename;
    }


    public void play() {
 try {   
            BufferedInputStream buffer = new BufferedInputStream(
    new FileInputStream(filename));
     player = new Player(buffer);
     player.play();
 }
 catch (Exception e) {

     System.out.println(e);
 }

    }

    public static void main(String[] args) {
 Mp3Player mp3 = new Mp3Player("song.mp3");
 mp3.play();

    }

}




 
© 2021 Learn Java by Examples Template by Hubberspot