It's all about Java: java
Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Saturday, 20 September 2025

File IO operations with java programming language

File Management in OS

File management includes files and folders creation, copy and paste operations, reading the file and writing into files and deleting the files and folders 

And also reading meta data about files and folders. It may include file free space, occupied space and read/write permissions etc.

These above operations are considered as file management and managed by respective operating system.

GUI that represents Windows File Manager



File Management with Java 


Though Java is platform independent, programming language depends on native file IO resources of operating system.

This is possible with the Java API support. These API are categorized into 2 types.

  1. Readers and Writers: Readers and writers does the IO operations, character by character
  2. InputStream and OutputStream: Where as InputStream and OutputStream does IO operations byte by byte

Below are simple Java programs that demonstrates different File IO operations.

Program for creating directory

package com.allabtjava.fileio;


import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.File;

import java.io.FileReader;

import java.io.FileWriter;

import java.io.IOException;

import java.nio.file.Path;


public class FileManager {


public FileManager() {


}


public void makeDirectory(String path, String dirName) {

Path dirPath = Path.of(path, dirName);

File dir = new File(dirPath.toString());

boolean isCreated = dir.mkdir();

if (isCreated)

System.out.println("A new directory with the name " + dir.getPath() + " created!");

}

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

FileManager manager = new FileManager();

manager.makeDirectory("e:\\", "students");

}

}



Program for creating file:

package com.allabtjava.fileio;


import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.File;

import java.io.FileReader;

import java.io.FileWriter;

import java.io.IOException;

import java.nio.file.Path;


public class FileManager {


public FileManager() {


}


public void createFile(String dirPath, String dirName, String fileName) throws IOException {

Path filePath = Path.of(dirPath, dirName, fileName);

File file = new File(filePath.toString());

boolean isFileCreated = file.createNewFile();

if (isFileCreated)

System.out.println("A new file with the name " + file.getPath() + " created!");

}

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

FileManager manager = new FileManager();

manager.createFile("e:\\", "students", "student_1");

}

}


Listing all files available in given folder

package com.allabtjava.fileio;


import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.File;

import java.io.FileReader;

import java.io.FileWriter;

import java.io.IOException;

import java.nio.file.Path;


public class FileManager {


public FileManager() {


}

     public void listFiles(String dirPath, String dirName) {
Path dir = Path.of(dirPath, dirName);
File file = new File(dir.toString());
String[] listOfAllFiles = file.list();
System.out.println("List of all Files in the directory/folder - " + dirName + ": ");
for (String fileName : listOfAllFiles) {
System.out.println(fileName);
}
}


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

FileManager manager = new FileManager();

manager.listFiles("e:\\", "pinterest");

}


}



Delete a directory

package com.allabtjava.fileio;


import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.File;

import java.io.FileReader;

import java.io.FileWriter;

import java.io.IOException;

import java.nio.file.Path;


public class FileManager {


public FileManager() {


}

     public void deleteDirectory(String dirPath, String dirName) {

Path dir = Path.of(dirPath, dirName);

File dirToBeDeleted = new File(dir.toString());

if (dirToBeDeleted.exists()) {

boolean isDeleted = dirToBeDeleted.delete();

if(isDeleted)

System.out.println("File deleted!");

else

System.out.println("Could not delete file. File is being used by other program or application.");

}

}


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

FileManager manager = new FileManager();

manager.deleteDirectory("e:\\", "pinterest");

}


}



Read a file content


package com.allabtjava.fileio;


import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.File;

import java.io.FileReader;

import java.io.FileWriter;

import java.io.IOException;

import java.nio.file.Path;


public class FileManager {


public FileManager() {


}

     public void readFile(String dirPath, String dirName, String fileName) throws IOException {

Path filePath = Path.of(dirPath, dirName, fileName);

File file = new File(filePath.toString());

FileReader reader = new FileReader(file.getAbsolutePath());

BufferedReader bufferedRead = new BufferedReader(reader);

String line = null;

while((line = bufferedRead.readLine()) != null) {

System.out.println(line);

}

bufferedRead.close();

}


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

FileManager manager = new FileManager();

manager.readFile("e:\\", "pinterest", "demo.txt");

}


}


Write content into file



package com.allabtjava.fileio;


import java.io.BufferedReader;

import java.io.BufferedWriter;

import java.io.File;

import java.io.FileReader;

import java.io.FileWriter;

import java.io.IOException;

import java.nio.file.Path;


public class FileManager {


public FileManager() {


}

     public void writeToFile(String dirPath, String dirName, String fileName) throws IOException {

Path filePath = Path.of(dirPath, dirName, fileName);

File file = new File(filePath.toString());

FileWriter writer = new FileWriter(file);

BufferedWriter bufferedWriter = new BufferedWriter(writer);

bufferedWriter.write("allabtjava.com is a web site, has information about java technologies \n");

bufferedWriter.write("This article explains about, files and IO management with java programming language.");

bufferedWriter.close();

}


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

FileManager manager = new FileManager();

manager.writeToFile("e:\\", "pinterest", "demo.txt");

}


}

Sunday, 9 May 2021

Demonstration of Java NullPointerException

NullPointerException causes and reasons

Since Java is object oriented programming language, every thing is considered to be an object. and there is always a scope of an object to be null or "No value". 

Since Java supports primitive data types, Java is not considered to be pure Java object oriented programming language. 


Few Notable points about NullPointerException

  1. NullPointerExceptions is unchecked exception
  2. Please read post Exception handling and java keywords before reading this article
  3. Usually if program tries to fetch the value from reference and finds nothing as value, then program throws NullPointerException
  4. 'Zero' is not null
  5. And empty String is not considered to be null
  6. It is not the subclass of RuntimeException class

Demo code that throws NullPointerException 



package com.allabtjava.blog;

public class DemoNullPointerException {

class BeanDemo {
String name;
Integer ID;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getID() {
return ID;
}
public void setID(Integer iD) {
ID = iD;
}
}
public DemoNullPointerException() {
}
public void createNullPointerException() {
BeanDemo bean = new BeanDemo();
bean.setName("All about Java!");
System.out.println(bean.getName());
if(bean.getID() == null) {
throw new NullPointerException();
}else {
System.out.println(bean.getID());
}
}
public static void main(String args[]) {
new DemoNullPointerException().createNullPointerException();
}
}

Output


All about Java!
Exception in thread "main" java.lang.NullPointerException
at com.allabtjava.blog.DemoNullPointerException.createNullPointerException(DemoNullPointerException.java:36)
at com.allabtjava.blog.DemoNullPointerException.main(DemoNullPointerException.java:44)

Monday, 26 April 2021

Evolution of Java Programming Language

Evolution of Java:

First of all, The Java programming language and it's tools that we currenly using is not what actually expected. This language started as a project to give solutions for embedded devices, mobile phones and other portable peripherals. 

Initially, the Java was called Oak. 


Why it is Oak first..? and Why it transformed to Java..?


The team of five technocrats including Dr. James Gosling and also known as Dr. Java, together working on a project, which expected to give solutions on embedded devices, portable smart devices and TV Set top Boxes etc. at Sun Micro Systems. 

In the process of achieving this solution, at their breaktime, team used to relax with a coffee by having a glimpse on a scenery of Oak tree next to their facility. 

Once the project has come to conclusion and in the process of giving a title to it, they noticed the Oak trees [Always observing them in their break time], they named this programming language as Oak.

Oak Logo


Why it transformed to Java..?

When the first version of Oak is about to release, The trademark search revealed that Oak is already registered for Oak Technologies company. Then, Java was named to this project.

In the previous paragraph, it is told that, "team used to relax with a coffee by having a glimpse on a scenery of Oak trees next to their facility...". When one of the team members asked to barista, [Usually a coffee bar tender is called with that name] about the name of the coffee bean that she/he serves in the break..? The reply was "Coffee is made of Java Beans.."




Immediately the name of the project confirmed to be Java and first version 1.0 is released into the industry in the year 1994. Rest we know, how Java programming language was developed and evolved into the bigger scope like smart phones, Inbuild JRE into web browsers etc.

The Oracle claims that more than 1 billion devices uses JRE and millions of developers uses Java and it's tools every day.

Java Version 16  is released in March 2021.




Few of the Java products are:

  • TV Set top Boxes,
  • Android OS
  • Realtime JVMs
  • Embedded devices
  • Almost all Browsers


Java evolved almost 30 years ago since 1994 from it's first version and almost all devices used Java and it's products directly or indirectly in their daily use. Hope Java continues it's charisma infinity days and will do wonders.


Happy Coding..! :)  





Thursday, 22 April 2021

Java programming language and IDEs

IDE: Integrated Development Environment

Integrated development environment, in short IDE is a convenient environment to write, execute and  debug the code or programs on a single platform. IDEs support not only writing code smoothly but also provides a provision to write scripts, XML files, simple text files and build scripts like Ant, Maven are few among others.

In short IDEs are development environments to execute complete development activities using one application.


IDEs and Editors

IDEs and Editors fulfills the same purpose. That is writing code. But IDEs are glued or closely works with respective programming language's compilers, runtime environments, profilers and other language specific tools to put developer in a comfortable zone. 

Some of the features of IDE:
  1. Auto completion
  2. Syntax Highlighting
  3. Code debugger
  4. Profilers
  5. Multipage editors

Auto completion:

Auto completion feature suggests APIs [methods, classes and interfaces] and keywords etc as we start typing in the editor. This helps in not spending much time on typing APIs.




Syntax Highlighting:

Syntax is a structure of arranging APIs, operators and keywords to make computer instructions, subsequently which becomes executables.

Class names, method names, operators and Keywords are highlighted with different colors and formats to differentiate them and to increase the readability. Syntax highlighting helps importantly when single program or file has thousands of statements or lines.

Code Debugger:

Debugger is a feature to identify bugs, errors and shows intermittent results of set of programming instructions or statements and subsequently helps in correcting and developing a bug free computer programs






Profilers:

Profiler is the tool usually shipped along with JDK [if it is a Java] and helps in understanding the memory usage of a computer application graphically. These graphics includes different charts and GUI controls. 



Profilers gives information about

  •  Memory usage,
  •  details of Threads being used,
  •  Heap dumps,
  •  CPU utilization etc

Multipage Editors:

Multipage editors shows the same file content in multiple perceptions. For example XML file content can be viewed in different views. 1. Hierarchical view 2. Simple text format and 3. Graphical view etc


  


Few more notable points about IDEs and Editors:

  1. IDEs are scalable to support multiple programming languages
  2. Editors can not be glued to a programming language's compiler
  3. Editors does not support Auto completion
  4. Editors does not support code debugging
 

IDEs for Java and IDEs built using Java

Usually IDEs are developed using different programming languages where, few of them are open source and few are commercial. Few of the industry endorsed IDEs are:

  • Eclipse
  • Netbeans
The above listed IDEs are developed using Java programming language and also used to develop Java applications and programs. It is little tricky to understand for beginners. 
And both IDEs share common features like scalability, modularity, code completion etc.
You can download Eclipse and Netbeans distributions from their respective sites.


Happy Coding! :)

Monday, 11 January 2021

Java API support for Exception Handling

First of all, please read below blog post to understand basics of Exception Handling in java.

Exception handling and java keywords


To continue from there, Basically Java default API has hierarchy of  java classes to support different uses cases of exceptions. 

The parent class of all Exceptions and Errors is Throwable. Please check below pictorial representation of  API Hierarchy 

Exception:

The class Exception and any subclasses that are also not subclasses of RuntimeException are checked exceptions.

And all subclasses of RuntimeException and RuntimeException class itself are Unchecked exception. Rest all are Checked exceptions

Examples of Unchecked Exceptions: 

         ArrayIndexOutOfBoundException

         NullPointerException

Error:

An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions.

Examples: The ThreadDeath error


Wednesday, 6 January 2021

Java - Swing custom components - Rounded JButton

Unlike AWT, Java Swing tool kit provides feasibilty to create custom components and containers.

To understand Java GUI toolkits more clearly, please read my other articles on Swing and AWT. 

In this article I focus more on building custom components.

Let us see how to create simple Rounded JButton. The below program demonstrates How rounded JButton can be created and added to a JFrame.

 

Program:


import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Shape;
import java.awt.geom.Ellipse2D;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class RoundedJButton extends JButton {

/**
*/
private static final long serialVersionUID = 1L;

public RoundedJButton(String title) {
super(title);
Dimension size = getPreferredSize();
size.width = size.height = Math.max(size.width, size.height);
setPreferredSize(size);

setContentAreaFilled(false);
}

@Override
protected void paintComponent(Graphics g) {
if (getModel().isArmed()) {
g.setColor(Color.lightGray);
} else {
g.setColor(getBackground());
}
g.fillOval(0, 0, getSize().width - 1, getSize().height - 1);

super.paintComponent(g);
}

@Override
protected void paintBorder(Graphics g) {
g.setColor(getForeground());
g.drawOval(0, 0, getSize().width - 1, getSize().height - 1);
}

Shape shape;

@Override
public boolean contains(int x, int y) {
if (shape == null || !shape.getBounds().equals(getBounds())) {
shape = new Ellipse2D.Float(0, 0, getWidth(), getHeight());
}
return shape.contains(x, y);
}

public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, UnsupportedLookAndFeelException {

JFrame frame = new JFrame();
frame.setTitle("It's all about Java...");
frame.setSize(150, 150);
GridLayout layout = new GridLayout();
layout.setRows(1);
layout.setHgap(10);
layout.setVgap(10);
frame.setLayout(layout);

JTextField field1 = new JTextField();
field1.setText("This is a textfield!");
frame.getContentPane().add(field1);

RoundedJButton button = new RoundedJButton("Browse");
button.setBackground(Color.gray);
button.setForeground(Color.GREEN);
frame.getContentPane().add(button);

UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
frame.pack();
frame.setVisible(true);
}
});
}
}

There are two parts in the program. First part creates RoundedJButton component by extending JButton. and second part creates JFrame and appends two components. 1. RoundedJButton and 2. JTextField

First Part:


RoundedJButton overrides paintComponent(Graphics g) and paintBorder(Graphics g) to get the circled shape to the Button. 

Second Part:

Second part contains main method which creates JFrame object and adds 2 components to JFrame dialog.

Also applies System look and feel by using following

UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());

I will explain clearly about pluggable look and feels also known as PLAF in future articles.

That's all for now!

Happy coding... :) 

Tuesday, 15 September 2020

Coding and best practices

 Write code or write code in right way...

Writing a coding solution to a problem can be done in many ways. If the solution can be obtained with less number of code lines, then it is easy to understand and maintain.

But what if code is large with having millions of lines. Moreover maintenance and readability becomes difficult as the code base grows... Right? 

In this blog I want to share my views and experiences on writing code efficiently and effectively with less maintenance efforts.

Aspects to consider while coding:

  • Naming convention
  • Cyclomatic Complexity
  • SOLID principles
  • DRY Principle
  • Managing dead code
  • Comments


Naming conventions:

Every programming language mandates few norms in order to name variables, classes and functions etc. For ex: Java uses class names first letter to be a alphabet and rest to be lower case letters. 

But if we dig little bit more, naming conventions are not limited to only upper case or lower case letters and using alphanumeric letters etc.

Naming a variable must be enough concise as naming your first child's name...

Few bad names for variables and constants:

          int final static TWO = 2;  [wrong]

          int final static MAX_LENGHT = 2; [Correct] 

  

Cyclomatic Complexity:

Cyclomatic complexity is a measure or metric to estimate complexity level of a snippet or block of code. 

Cyclomatic complexity and best practices:

  • Never put more than three conditional checks (&& operator and || operator etc.) in one if condition
  • Never exceed more than thirty lines in one function or method.
  • Never exceed more than 1000 lines in one class or one file.

SOLID principles:

Usually developing a large and scalable application, requires better design. Adhering to SOLID principles yields better scalable and easily maintainable applications.

There are five SOLID principles. They are:

  1. Single Responsibility Principle
  2. Open/Closed Principle
  3. Liskov's Substitution Principle
  4. Interface Segregation Principle
  5. Dependency Inversion Principle

DRY Principle:  

DRY stands for Do Not Repeat Yourself. Sometimes, There could be a need to use same or similar set of lines of code to be used multiple times in the same application. For ex. String utilities, DB connections or updating records in database etc.

Writing frequently used code snippets multiple times is not a good practice. Instead move this code to a function or method and use this method in places where ever required.

Simple use cases are:

  • DB Connections
  • File IO Operations
  • String Utilities etc. 

Managing Dead Code:

Sometimes there are some lines or instructions in code base, which are completely not executed in all cases at all. This is considered as dead code. 

Dead code reduces the quality with respect to the readability.  


Comments:

Comments increases the readability of the program for programmers. Comments are written at class level, method level and variable level [Constants, instance variables and class variables] differently. 

The reason for this difference is, the pattern of comments is identified by API document generator tools and generates API documents.


Conclusion:

What all I tried to share through this post is, writing code for a specific problem can be done in different ways. But making sure that the program is more readable, maintenance free and easily scalable is also very important. 

The above few solutions or hacks will definitely help in developing better applications. 

Hope you enjoyed reading the post. Comments are welcomed. Thank you!! 

Happy coding!...

Sunday, 9 August 2020

Exception handling and java keywords

Exception:

Exception in a programming language and in English language is pretty similar. Exception means being different from or not following the rules. And in programming language like Java, exception is  an event which occurs during the execution of a program that disturbs the complete flow of application or program.

When something beyond expected happens while executing a program is considered as an error. handling these errors or abnormality is called as Exception handling.


Exception Handling:

Exception handling in java is managed with the help of java keywords and java API support.. 

            1. Java Keywords

            2. Java API support


Java Keywords: 

There are 5 keywords in Java.

          1. Try

          2. catch

          3. finally

          4. throw

   and 5. throws

These five keywords used all together or combination of few keywords are used on need basis.

1. Try:

The code or set of instructions which are prone to errors or exceptions are enclosed in try block.

For example dividing a five or some number with zero [5/0]. The result of 5/0 is undefined and in Java,  this scenario is considered as exception.

2. Catch:

Usually try block is followed by a catch block. If some exception is occurred in try block, the execution control is moved to catch block instead of  continuing the execution of  try block's code. 

The purpose of catch block is, handling the exceptions that are raised in try.

There is a possibility of handling multiple scenarios in multiple catches. 

NOTE: Multiple catches can be written for single try.

Java code example:

           try{

                   ---                     // code

                } catch(OtherException e) {

                   ---                    // code

               }catch(AnotherException e) {

                }      

3. Finally:

Usually if there is an exception in try block, the rest of the lines in try are not executed and control moves on to catch block. And if there is no exception at all in try block control never moves to catch block. Then catch block is considered to be dead code. 

Then where must we write mandatory code? 

So, finally block is written after try and catch which gets executed always. 

Java code example:

            try{

                  ---

                } catch (Exception e) {

                  ---

                } finally{

                  ---              // mandatory code for execution

                } 


NOTE: Always put mandatory code in finally block. For example: closing IO resources connections like network and database connections etc

4. Throws and Throw:

Throws and throw keywords works along with Java API support. I will explain the Java API support for Exception handling in next subsequent articles. 

For now, we can understand that for every exception scenario there is one Java class(Java API). Example: Number divided by zero. [5/0]. The result is ArithmeticException

Java code example:

     try{

               int result = 5/0;

                ---        // other code

         }catch(ArithmeticException e) {

                ---        // exception of try block is handled here   

         }  

  Why there is no "throws" keyword here....?

The alternative solution for above snippet with throws and throw for checking election voting age eligibility exception is:

void votingAgeNumber() throws ArithmeticException{

                int age = 12; 

                if(age <=18) {

                           throw new ArithmeticException("Age is not sufficient to vote");

                 }

                 ---       // other code              

           }

NOTE: Sometimes "throws" keyword works as an alternative solution for try and catch blocks. The throws keyword is used instead of try and catch.

Example:

Solution with throws:

void divideNumber() throws ArithmeticException{

         int result = 5/0;

 } 

 And snippet with try and catch:        

void divideNumber(){

   try{

      int result = 5/0;

    }catch(ArithmeticException e){

     ----      // handle exception

    }

} // method end                      

         

The above both solutions are same, but with different keywords.


 Some key points:

1. There can be one try with multiple catch blocks.

2. Try block can be followed by either catch or finally block.

3. Or both can be followed

4. Throws is like warning that exception can be thrown and throw keyword is real accident took place.


I wrote here  https://www.allabtjava.com/2021/01/java-api-support-for-exception-handling.html on checked exceptions and runtime or unchecked exceptions.



Happy coding... :)





   

Sunday, 29 April 2018

Java and OOPS concepts

Java is an object oriented programming language which can be downloaded and installed in your local Machine from java.com


To explain java binaries and tools requires block diagram which gives clear picture. For now I brief few important tools.

  • JDK - java development toolkit
  • JVM - Java virtual machine
  • JRE - Java Run time environment
From oracle site we can download JDK which is shipped along with JVM and JRM. Mostly java programmers need the JDK. For end users JRE alone is enough.

Basic OOPS characteristics are

Inheritance

Encapsulation

Abstraction

and Polymorphism

The above concepts collectively makes application software extendable and changeable with less effort.
Also helps in Developing design patterns. Design patterns gives solutions for common challenges usually a programmer faces while development applications.
Factory design pattern, Abstract design pattern, Builder pattern etc. I explain these Design patterns in another article.

Inheritance:
Inheritance is all about reusing one class behavior and members in it's child class. In java terminology these classes are called as super class and sub class. If class B extends class A then, class A becomes super class and class B becomes class A's sub class.

public class A{
  public A(){
 }
   -------
}
public class B extends A{
   public B(){
    } 
    -------
}   
Encapsulation:
Encapsulation is a technique of putting the source code all together within a unit. Java uses class and interface as keywords to represent unit. Data Hiding is one of the buzzwords which is possible only with implementation of Encapsulation in the program.

Abstraction:
Abstraction is the concept of hiding the irrelevant data from client/user visibility. To implement this feature java uses abstract keyword. this can be be prefixed to a class and methods. Once the class is abstract class then it's object can not be created. And id one or all methods of same class are followed by abstract keyword it can not be implemented.
The point here is java programming language gives implementation freedom to the developers where ever expected.
Sometimes java program is written to a another programmer rather a end user. Usually this code is called Application programming interface in short API. When a programmer writes a program with the intention to be used by another programmer, He/She may not need all the details [line by line] instruction's description is not required. Right?
The punch line is abstraction helps in showing only relevant data to the client of our program.
One of the mostly used design pattern is abstract factory design pattern.

Polymorphism:
In generic terminology poly means many morph means forms. It means many forms of a single method names.
Polymorphism can be achieved within the class or using inheritance i.e extends keyword.

Overloading and overriding:

Overloading rules:
within the class a same method can be duplicated but accepts different arguments and returns different result
  1.       Number of arguments must be different
  2. Or  Sequence of arguments must be different
  3. Or  Type of the arguments must be different.
Uses:
Let us take a method .
     int add(int a, int b){
        return a+b;
     }

Now let us overload this method to add decimal values
 float add(float a, float b){
     return a+b;
 }
Now based on the arguments passed to the add() respect add() method will be invoked.
Overriding:
Overriding is possible only by using inheritance.For an instance super class has add(int a, int b). and sub class also needs add operation but computes differently. Then programmer simply overrides the add() of super class overrides the add() with his new implementation. 
public class SuperClass{

  int add(int a, int b){
       ....
   }
}

public Subclass extends SuperClass{
@Overrides
int add(int a, int b){
// computes his own add operation
}
} 
In next article I write about tools of JDK and JRE and internals of JVM Java Virtual Machine.

Please click the link for more good look and feel and elegant font

Happy Coding. ;-)


Wednesday, 31 January 2018

Core Java: Immutable objects and mutable objects with an example

Immutable objects and mutable objects with an example 


In object oriented programming language in short OOPS, every problem, precisely every requirement is viewed as an object. Understanding the problem in this point of view brings many good things possible in programming like encapsulation, abstraction, polymorphism and inheritance. Anyways this post is not intended for describing benefits of OOPS.

Object could be any thing. Let us take Car for an instance. Basically car is an object and it has name, wheels, metal body, engine, maximum speed,  gear box etc as properties.

Let us consider the car name is Ferrari, maximum speed is 200 km per hr with 6 gears. While driving the car driver can change the speed of the car and change the gear etc.
So while car is running it's current speed, current gear are considered to be state of the object.
The current speed can be changed using accelerator and gear can be changed using gear box. These can be considered as behavior of the car object. Of course car has a name as well.

 Every object has 3 characteristics they are State, Behavior and Name. 

In our example Ferrari is name of the object. Number of gears, current gear, current speed are State and accelerator and gear box decides the behavior of the car object. In java language object's reference name is name of object and methods which decides state are behavior.  

ImmutableObject ferrari = new ImmutableObject("Ferrari", 200, "Red");

             1. new operator creates the object
             2. ferrari is name of object
             3. Ferrari, 200, and Red are State of object

Objects based upon it's behavior can be categorized into two types. They are 
              1. Immutable objects and 
              2. Mutable objects


Mutable and Immutable objects



Mutable object's state can be changed at run time, where as immutable object's state can not be changed. String class is the ideal example for immutable objects. 
    
The state of an object can be decided at it's creation time or at run time or at both times. If state is decided at creation time and it is restricted not be changed at run time, this object is considered to be an  immutable object. If this can be changed at run time, it is called as mutable object.

If car is automatic [no gears] and it's speed can not be changed at any time, then it is immutable car object.  

Below program creates immutable objects:




01  public final class ImmutableObject {
02
03  private String name;
04
05  private int maxSpeed;
06
07  private String color;
08
09  /**
10  * @param name
11  *            holds car name
12  * @param maxSpeed
13  *            holds maximum speed of the car
14  * @param color
15  *            holds color of car
16  */
17  public ImmutableObject(String name, int maxSpeed, String color) {
18  this.name = name;
19  this.maxSpeed = maxSpeed;
20  this.color = color;
21  }
22
23  public String getName() {
24  return name;
25  }
26
27  public int getMaxSpeed() {
28  return maxSpeed;
29  }
30
31  public String getColor() {
32  return color;
33  }
34
35  public static void main(String[] args) {
36  ImmutableObject ferrari = new ImmutableObject("Ferrari", 200, "Red");
37  System.out.println("Car name: " + ferrari.getName());
38  System.out.println("Car color:" + ferrari.getColor());
39  System.out.println("Car maximum speed:" + ferrari.getMaxSpeed());
40  System.out.println();
41
42  ImmutableObject anotherCar = new ImmutableObject("BMW", 180, "White");
43  System.out.println("Car name: " + anotherCar.getName());
44  System.out.println("Car color:" + anotherCar.getColor());
45  System.out.println("Car maximum speed:" + anotherCar.getMaxSpeed());
46  }
47  }
48

Output:

Car name: Ferrari
Car color:Red
Car maximum speed:200

Car name: BMW
Car color:White
Car maximum speed:180

Explanation


Line 1: First and fore most rule is to make your class final class.

Line 3 to Line 7: All variables are private variables. private access modifier restrics usage of members within the class

Note: Do not use other classes as data types of your instance variables which are mutable in behavior. All of our example variables are of String type. String is immutable. See API document of String class for more information.   


Line 17: Creates parameterised constructor with state which can not be changed at run time

Line 23 to Line 33: Create only those methods which shares it's state to the other classes. As we did in our example ImmutableObject. Allows only getter methods and no setter methods at all.


Line 36 to Line 42: Finally, create 2 objects ferrari and another car with different state which can not be changed at run time..

Now, let us change the same class which allows creating mutable objects:

01
02 public class MutableObject {
03
04 private String name;
05
06 private int maxSpeed;
07
08 private String color;
09
10 private int currentGear;
11
12 private int currentSpeed;
13
14 /**
15 * @param name
16 *            holds car name
17 * @param maxSpeed
18 *            holds maximum speed of the car
19 * @param color
20 *            holds color of car
21 */
22 public MutableObject(String name, int maxSpeed, String color) {
23 this.name = name;
24 this.maxSpeed = maxSpeed;
25 this.color = color;
26 }
27
28 public String getName() {
29 return name;
30 }
31
32 public int getMaxSpeed() {
33 return maxSpeed;
34 }
35
36 public int getCurrentGear() {
37 return currentGear;
38 }
39
40 public void setCurrentGear(int currentGear) {
41 this.currentGear = currentGear;
42 }
43
44 public int getCurrentSpeed() {
45 return currentSpeed;
46 }
47
48 public void setCurrentSpeed(int currentSpeed) {
49 this.currentSpeed = currentSpeed;
50 }
51
52 public String getColor() {
53 return color;
54 }
55
56 public static void main(String[] args) {
57 MutableObject ferrari = new MutableObject("Ferrari", 200, "Red");
58 System.out.println("Car name: " + ferrari.getName());
59 System.out.println("Car colo: " + ferrari.getColor());
60 System.out.println("Car maximum speed:" + ferrari.getMaxSpeed());
61
62 ferrari.setCurrentGear(5);
63 ferrari.setCurrentSpeed(150);
64 System.out.println(String.format("Current speed is %s and current gear is %s \n", ferrari.getCurrentSpeed(), ferrari.getCurrentGear()));
65
66
67 ferrari.setCurrentGear(1);
68 ferrari.setCurrentSpeed(10);
69 System.out.println(String.format("Changed state at run time!.. \nCurrent speed is %s and current gear is %s ", ferrari.getCurrentSpeed(), ferrari.getCurrentGear()));
70
71
72 System.out.println();
73
74 }
75}
76

Output:


Car name: Ferrari
Car colo: Red
Car maximum speed:200
Current speed is 150 and current gear is 5 

Changed state at run time!.. 
Current speed is 10 and current gear is 1 


Explanation

  

Line 2: Remove final keyword. This makes the class extendable using extend keyword

Line 10 to Line 12: Introduced new variables which adds new information to the state of object

Line 40 and Line 48: Introduced new setter methods which changes state at run time.

Line 57: Finally, create the ferrari object and change it's state run time by calling different setter methods.

Line 62 to Line 72: Changes the state by calling setters on member variables.  

Few more details about immutable objects:


  • It is always good practice to use immutable objects in our application especially in concurrent apps where ever applicable
  • Immutable objects ensures correct results/output always in all environments like multi threading environment, collection framework.
  • HashMap<key, value> always requires immutable object as key. Otherwise it behaves in undetermined way.
  • Consider cloning when creating immutable classes. I will post another article about importance of deep cloning and shallow copy in details in near future.
  • Cache memory implementation uses immutable objects 
  • java.lang.String is the most used immutable class in java

    .

Popular posts

Atomicity with Java Programming Language

 Atomicity with Java What is Atomicity Atomicity, in computer science, is considered to be a property [ALL-OR-NOTHING], that the state of a ...