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

Sunday, 28 September 2025

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 resource in an operation is not controlled by a different flow of execution at the same time [Even in time slicing operations]

We know, Java is not pure object oriented programming language, due to primitive data types' design behavior.

Most of the Java experts, while designing and developing applications thrives hard, to create, most secured applications considering "Atomicity in multi threaded application".

Does Java language helps in developing Secured application..?

The answer is no, Java programming language does not give secured applications at all, especially in multi threaded environment.

As we know, Java supports 2 types of variables/data types. 
  1. Primitive data types
  2. User defined data types

Primitive data types:      

Java supports 8 different primitive data types. They are: 

  1.  boolean    1 byte
  2.  short        2 bytes
  3.  int            4 bytes
  4.  char         2 bytes
  5.  float         4 bytes
  6.  long         8 bytes
  7.  double     8 bytes
  8.  byte         1 byte

User Defined data types:


In Java, user defined data types are created using "new" operator. For example, to create Employee object, the following instruction is coded

Employee employee = new Employee();

Now, the employee in the above statement, is a reference to an Employee class and called as user defined data type.

Now, coming to the point [Why Java is not secured..?], the primitive data types, long and double are not atomic variables. That means they are not executed in a single operation. 

long variable's size is 64 bits. And it is divided into 32 bits + 32 bits while copying from one memory location to another memory location. and all user defined data types are based on primitive data types.

And these two primitive variables [long and double] breaks the atomicity law. 

And developers can not bypass long and double variables in their program to create application. It is almost impossible to create the application without these variables.

Especially, in multi threaded based application, these non atomic variables may give unpredictable results. 

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");

}


}

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! :)

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!...

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 ...