Java annotations

 Do you want to add information about the code as meta data? If your answer is yes then this is the feature to add annotations.

Why is it needed?

It is used to provide supplementary information about the classes, member variables and functions.

What is the difference between annotations and comments?

Annotations provides the meta data about coding which can be used by tools and compilers. But comments are simple information to know about coding.

Syntax:

‘@’ annotation name                                                                                                                                       

Annotation types:

Annotations can be classified into the following types..

1. Built- in annotations:

These are annotations created by the java itself

Eg: ‘@Depreccated’, ’@Override’, ‘@SuppressWarnings’

2. Custom annotations:

The user can create this type of annotations.

Eg:

‘@interface’

Java code for built-in annotation:

These are included in java package itself. Here ‘@Override’ is used.

This annotation is used to tell the compiler that this base class code is overridden.

Base class or Super class: sClass1

Child class: cClass

Method: display() – same method with two definition is called overridden.  

Sample Code:

   class sClass1 {

       void display() {

           System.out.println("This is the Super Class");

       }

   }

   class cClass extends sClass1 {

       @Override

       void display() {

           System.out.println("This is the Child Class");

       }

   }

Next type of annotation is given below.

Java code for custom annotation:

              User defined annotations are called custom annotation. Here, the custom annotations are listed below..

@Retention :it specifies how long the annotations are retained.

@Target : It specifies the kind of program, the annotations are applicable.

@interface : user defined interface

@custAnnotation: user defined custom annotation name.

Sample Code:

import java.lang.annotation.ElementType;

import java.lang.annotation.Retention;

import java.lang.annotation.RetentionPolicy;

import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)

@Target(ElementType.METHOD)

public @interface custAnnotation {

    String name();

}

public class egClass {

    @custAnnotation("This is the custom annotation")

    public void egMethod() {

        // Method implementation

    }

}

These are the sample codes used to provide annotations in both built-in and custom type. Hope this codes are useful to you.Keep coding!!!

Symmetric Encryption in java

              Symmetric encryption is the process of using same key for both encryption and decryption.

Encryption: It is the process of converting plain text into ciphertext using an encryption key.

Decryption: It converts the ciphertext into original plain text using the same key.

Program implementation in java:

              Program implementation starts from reading input text from the user. A secret key is generated. The input is encrypted using the secret key. Same key is used for decryption.

Steps to follow:

  • Built-in packages javax.crypto.* ,java.util.Base64 and java.util.Scanner are included.
  • A public class is created with main() function.

Input reading:

  • Scanner object is created to read the system input.
  • Using this object, input text is read until the next line.

Secret key Generation:

  • KeyGenerator object is created to get instance for AES(Advanced Encryption Standard).
  • It is initialised as 128 bit.
  • generateKey() is used to generate secret key.

Encryption Process:

  • Cipher object is created and get assigned with instance of AES.
  • Cipher object is initialised with encrypted mode and secret key.
  • A byte of data is created from input text.
  • It gets encoded Base64.getEncoder(). The encrypted text is printed in the output screen.

Decryption Process:

  • Cipher object is initialised with Decrypted mode and secret key.
  • The data is decoded using Base64 decoder.
  • Finally, it displays in the output screen.          

Program:

import javax.crypto.Cipher;

import javax.crypto.KeyGenerator;

import javax.crypto.SecretKey;

import javax.crypto.spec.SecretKeySpec;

import java.util.Base64;

import java.util.Scanner;

public class SymmetricEncryptionEg {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);

        // Get the input from the user

        System.out.println("Enter a string: ");

        String inputTxt = scanner.nextLine();  

        try {

            // A secret key is generated

            KeyGenerator keyGenerator1 = KeyGenerator.getInstance("AES");

            keyGenerator1.init(128);

            SecretKey secrKey = keyGenerator1.generateKey();

            // Let us Encrypt the input text

            Cipher cipher1 = Cipher.getInstance("AES");

            cipher1.init(Cipher.ENCRYPT_MODE, secrKey);

            byte[] encryptBytes = cipher1.doFinal(inputTxt.getBytes());

            String encryptTxt = Base64.getEncoder().encodeToString(encryptBytes);

            System.out.println("The Encrypted Text is: " + encryptTxt);

            // it is the process of Decrypting the encrypted text

            cipher1.init(Cipher.DECRYPT_MODE, secrKey);

            byte[] decryptBytes = cipher1.doFinal(Base64.getDecoder().decode(encryptTxt));

            String decryptTxt = new String(decryptBytes);

            System.out.println("The Decrypted Text is : " + decryptTxt);

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

}

Output:

C:\raji\blog>javac SymmetricEncryptionEg.java

C:\raji\blog>java SymmetricEncryptionEg

Enter a string:

Welcome to Cryptography in java

The Encrypted Text is: TK8+C2B1+DwJ+CyFPc2YhOn1uRRN4V9W6n1KAGgtNd0=

The Decrypted Text is : Welcome to Cryptography in java

This is the way of implementing Symmetric encryption in java. Keep coding!!!

Java Program to implement Password Hashing using SHA-256:

              A simple java security Program is implemented here. It uses SHA-256.

What is SHA-256?

              Secure Hash Algorithm 256-bit is the expansion of SHA-256. It is a hashing algorithm in the form of cryptography. The input data size is 32 bits. Common usage of this algorithm deals with password hashing, data integrity and digital signatures.

Logic behind the program:

  • A password is given by the user as input.
  • This password is hashed in the format of 32 bits by the use of SHA-256 function.
  • Here, MessageDigest is used to make the user password into hashed format.

Program implementation:

              Program implementation starts with including the built-in packages from java.security.

  • A Public class”PassWordHashEg” is created with main() function.
  • A string variable “pwd” is assigned with user password.
  • Using a try catch block, the process is created.
  • A MessageDigest object is created and it gets assigned the instance of SHA-256.
  • Using digest function, it gets the bytes of user password “pwd”. The value is assigned to a byte array hBytes.
  • StringBuilder object sBuilder is created.
  • Using a for loop, the process is repeated until last hBytes value.
  • Each and every byte is converted to hash value and added to string builder sBuilder.
  • Finally, original password and hashed password is printed as output.

Program:

import java.security.MessageDigest;

import java.security.NoSuchAlgorithmException;

public class PassWordHashEg {

    public static void main(String[] args) {

        String pwd = "Mypassword@6";

        try {

            MessageDigest msgDigest = MessageDigest.getInstance("SHA-256");

            byte[] hBytes = msgDigest.digest(pwd.getBytes());

 

            StringBuilder sBuilder = new StringBuilder();

            for (byte b : hBytes) {

                sBuilder.append(String.format("%02x", b));

            }

            System.out.println("The original Password is: " + pwd);

            System.out.println("The Hashed Password is: " + sBuilder.toString());

        } catch (NoSuchAlgorithmException e) {

            e.printStackTrace();

        }

    }

}

Output:

C:\raji\blog>javac PassWordHashEg.java

C:\raji\blog>java PassWordHashEg

The original Password is: Mypassword@6

The Hashed Password is: c9dc8f3bb0ffe6a8883899a6d4c97a9572a6f16c137c167e8b24e60b324d7b79

 Applications:

Security Protocols (SSL/TLS and Digital Signatures)

Blockchain Technology.

This is the way of creating a java program to implement Password Hashing using SHA-256 is explained briefly. Keep coding!!!!

Java storage management: Heap memory

              Java objects can be stored in heap memory. It can be handled by JVM (Java Virtual Memory).

How it will be created???

              Whenever a new object is created using ‘new’ keyword, the memory is allocated the space in heap.

As java has a garbage collector, it easily deallocates the memory. To perform the efficient garbage collection, heap is divided into different generations.

Young Generation: It deals with new objects.

Old Generation: when an object survived in multiple garbage collection cycles, it is considered as old generation.

Permanent Generation : It has the metadata in older versions. Now, it is considered as Meta space.

Java Program to illustrate Heap Memory:

public class GenerationalHeapEg {

    public static void main(String[] args) {

        // A varible is initialised with 0 value for iteration

        int iter = 0;

        // Loop to create objects using the iteration variable

        while (true) {

            iter++;

            createObjects(iter);

           // to view the process,make the threas to sleep

            try {

                Thread.sleep(100);

            } catch (InterruptedException e) {

                e.printStackTrace();

            }

            //current iteration is displayed

            System.out.println("Current Iteration is displayed here: " + iter);

        }

    }

   // A method is created

    private static void createObjects(int iter) {

        // for loop to create the new objects

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

            // Object creation

            new Object();

        }

       // Display the iteration

        System.out.println("Created 10 objects in iteration: " + iter);

    }

}

Output:

C:\raji\blog>javac GenerationalHeapEg.java

C:\raji\blog>java GenerationalHeapEg

Created 10 objects in iteration: 1

Current Iteration is displayed here: 1

Created 10 objects in iteration: 2

Current Iteration is displayed here: 2

Created 10 objects in iteration: 3

Current Iteration is displayed here: 3

Created 10 objects in iteration: 4

Current Iteration is displayed here: 4

Created 10 objects in iteration: 5

Current Iteration is displayed here: 5

Created 10 objects in iteration: 6

Current Iteration is displayed here: 6

Created 10 objects in iteration: 7

Current Iteration is displayed here: 7

Created 10 objects in iteration: 8

Current Iteration is displayed here: 8

Created 10 objects in iteration: 9

Current Iteration is displayed here: 9

This is the way of implementing the java program to illustrate heap memory.Keep Coding!!!

Memory Management in Java: Weak references

              Reference is a pointer which points to another variable or pointer. It plays a vital role in memory management. It deals with the access of data.

Depends on the reference, it may be strong or weak. A strong reference prevents the garbage collector to reclaim the object memory until the reference exists.

A weak reference allows the garbage collector to reclaim the object memory.

Note: Weak reference is used in memory sensitive type of applications.

Let us create a java memory management program to implement the weak reference example.

Java implementation of weak references:

This program has the following logic.

Logic:

  • ·       A string object is created as Strong object reference.
  • ·       It gets assigned with a value.
  • ·       A weak reference is created as like strong reference.
  • ·       Get the weak reference.
  • ·       Assign the strong reference as null.
  • ·       Make the system to call the garbage collector.
  • ·       If you get the value of weak reference, it become null.

Program:

//Built-in packages are included.

import java.lang.ref.WeakReference;

//class with main() function

public class WeakReferenceEg {

    public static void main(String[] args) {

        String sReference = new String("Welcome to the world of Java Programming");

        // Let us create a weak reference using Strong reference

        WeakReference<String> wReference = new WeakReference<>(sReference);

       // Get the the reference

        System.out.println("Get the reference: " + wReference.get());

      // make the strong reference as null

        sReference = null;

      // Garbage collection is done

        System.gc();

      // final result after garbage collection

        System.out.println("Final reference value: " + wReference.get());

    }

}

Output:

When you compile and execute the above program, you get the below output.

C:\raji\blog>javac WeakReferenceEg.java

C:\raji\blog>java WeakReferenceEg

Get the reference: Welcome to the world of Java Programming

Final reference value: null

This is the sample java program to implement the weak reference is executed successfully. Hope this blog post is useful for you. Keep Coding!!!

Memory Management in java: Memory Leak

             Memory leak occurs when a computer program doesn’t manage the Memory allocation. This causes a part of memory is allocated, but it is not freed. Even though, the memory is not needed.

Memory leak makes the system performance low. If the programming language is java, it mostly uses the garbage collector to manage the memory. 

Sometimes, few of object references are there unintentionally. This may cause memory leak.

For eg, let us consider an infinite loop.

  • Here, a list is created as String. Using a while loop, the elements are added.
  • But the loop is infinite. So, the list elements are added in infinite times.
  • So, garbage collector unable to reclaim the memory of ‘l1’. So, it causes memory leak.

Program: Memory Leak Example

Steps:

  • Include the built in packages java.util.ArrayList, java.util.List.
  • Create a public class with main () function.
  • A list l1 is created as String using ArrayList.
  • Create a while loop with true argument. Just the add the data to list ‘l1’.

Code:

import java.util.ArrayList;

import java.util.List;

public class MemoryLeakEg {

    public static void main(String[] args) {

        List<String> l1 = new ArrayList<>();

       //Infinite loop  

      while(true) {

            l1.add("Number: " + i);

          }

}

Some of the techniques are used to avoid the memory leak as follows…

Techniques to avoid memory leak:

Consider the references:

  First, avoid static references. It may hold the object for long time.

  Release the references whenever the objects are completed its process.

Resources:

 It can be used as “try-with-resources”. For eg: Streams

Profiling Tools:

 This is used to monitor the memory and find the potential leak.

The memory leak and the mechanisms used to handle the memory leak is coated with example.

Memory Management in java: Object Creation and Garbage Collection

     Memory plays a vital role in programming. Any objects, variables need memory to store its value. Generally, memory management involves the allocation and deallocation of memory space.

The memory areas in java can be classified into 4 types listed as follows.

  • ·       Heap Memory: It stores the objects and variables.
  • ·       Stack Memory: Method calls and local variables.
  • ·       Code (Method) Area: byte codes of methods and constructors are stored.
  • ·       Native Method Stack: It has Native Method information.

Some of the concepts in memory management are given below.

  • ·       Object Creation and Garbage Collection
  • ·       Detecting Memory Leak
  • ·       Using Weak References

Let us implement these concepts in Java.

Java Program to implement Object Creation and Garbage Collection:

This program illustrates the object creation and garbage collection.

Steps:

  • ·       First, a class is created with main() function.
  • ·       A loop is created with condition i<10. Until this condition fails, the process is repeated.
  • ·       A string is created an object “temp”.
  • ·       It holds the integer value and an output statement is printing this object value.
  • ·       As it is a temporary value, it is garbage collected at the end.

Program:

public class MemoryMgtEg {

    public static void main(String[] args) {

        System.out.println("The string created its object");

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

            String temp = new String("String number: " + i);

            System.out.println(temp);

            }

        System.out.println("The garbage collection is done.");

    }

}

Output:

When you compile and execute this program, you get the output as follows…

C:\raji\blog>javac MemoryMgtEg.java

C:\raji\blog>java MemoryMgtEg

The string created its object

String number: 0

String number: 1

String number: 2

String number: 3

String number: 4

String number: 5

String number: 6

String number: 7

String number: 8

String number: 9

The garbage collection is done.

This is the way of implementing the java program to illustrate the object creation and garbage collection. Hope this will be useful for you.Keep coding!!!

Java NIO examples to illustrate channels and buffers.

    As the earlier blog gives you a basic knowledge about java NIO. Here, is the some examples to understand the concept of channels and buffers.

Channel is a foundational construction. It helps you to connect the input, output, hardware devices, files and sockets.

Buffer: it is a storage place where we can store the temporary data.

Let us create a channel for processing file reading and writing operations. Make it connected with a buffer.

File Reading Example using java NIO:

  • ·       It includes the built in packages.
  • ·       A public class is created with main() function.
  • ·       Three objects are created. FileInputStream,FileChannel and ByteBuffer.
  • ·       Data is read through the channel and gets stored in buffer.
  • ·       Until the buffer has data, it reads the data and display it in the output screen
  • ·       Finally, all file objects are closed.

Program:

import java.io.FileInputStream;

import java.nio.ByteBuffer;

import java.nio.channels.FileChannel;

public class FileReadEg {

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

        FileInputStream fInStream = new FileInputStream("example.txt");

        FileChannel fChannel = fInStream.getChannel();

        ByteBuffer buff = ByteBuffer.allocate(1024);

        int bRead = fChannel.read(buff);

        while (bRead != -1) {

            buff.flip();

            while (buff.hasRemaining()) {

                System.out.print((char) buff.get());

            }

            buff.clear();

            bRead = fChannel.read(buff);

        }

       fChannel.close();

        fInStream.close();

    }

}

Output:

‘example.txt’

It is the time read the data

Output in the command prompt…

C:\raji\blog>javac FileReadEg.java

C:\raji\blog>java FileReadEg

It is the time read the data

Next part is writing the data into file.

Writing data into the file:

This program starts with including the built-in packages.

  • A public class is created with main() function.
  • Here, three objects are created foe FileOutputStream, FileChannel and ByteBuffer.
  • FileOutputStream opens the file.
  • FileChannel gets the channel for the output stream.
  • ByteBuffer is used to allocate the memory.
  • Data is created and stored the size in the buffer.
  • Until the buffer size, it writes the data to the file.
  • Finally, the FileChannel and fileOutputStream objects are closed.

Program:

import java.io.FileOutputStream;

import java.nio.ByteBuffer;

import java.nio.channels.FileChannel;

public class FileWriteEg {

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

        FileOutputStream fOpStream = new FileOutputStream("example.txt");

        FileChannel fChannel = fOpStream.getChannel();

        ByteBuffer buff = ByteBuffer.allocate(1024);

        String data = "Have a nice day";

        buff.put(data.getBytes());

        buff.flip();

        while (buff.hasRemaining()) {

            fChannel.write(buff);

        }

        fChannel.close();

        fOpStream.close();

    }

}

Output:

Output in the command prompt:

C:\raji\blog>javac FileWriteEg.java

C:\raji\blog>java FileWriteEg

Output in the file:

‘example.txt’

Have a nice day

These are simple ways to illustrate channels and buffers in Java NIO. Keep Coding!!!!

Java implementation of NIO(New Input/Output)

     Java NIO (New Input/Output). It is an API (Application Programming Interface) which provides non-blocking input, output operations.it ensures high-speed in executing the operations.

Java 1.4 includes the feature.

Features:

It has the following features listed below…

  • ·       Non-blocking I/O
  • ·       Selectors
  • ·       Channels and Buffers
  • ·       Charset
  • ·       Coders/decoders
  • ·       Path and file operations

Program implementation:

This implementation starts from creating a text file”example.txt” with some text.

Steps to follow:

Include the built in packages such as java.io.RandomAccessFile,java.nio.ByteBuffer and java.nio.channels.fileChannel.

  • A public class with main() function is created.
  • RandomAccessFile object is created. It opens the file “example.txt” in readwrite mode.
  • FileChannel object is created.it gets the channel.
  • ByteBuffer object is allocated with size 48.
  • Read the buffer by character by character.
  • Write it to the command prompt.
  • Close the file pointer.

Program:

import java.io.RandomAccessFile;

import java.nio.ByteBuffer;

import java.nio.channels.FileChannel;

public class jNIOEg {

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

       //A file "example.txt" opens in read and write mode("rw")

        RandomAccessFile raf = new RandomAccessFile("example.txt", "rw");

      //Filechannel object is created. file object gets the channel

        FileChannel ch = raf.getChannel();

     //ByteBuffer object gets allocated with the size of 48

        ByteBuffer buff = ByteBuffer.allocate(48);

    // channel reads the buffer and assign it to bRead variable

        int bRead = ch.read(buff);

    // until bRead is not equal to -1, it continues

        while (bRead != -1) {

            buff.flip();  // make buffer ready for read

            while (buff.hasRemaining()) {

                System.out.print((char) buff.get()); // read 1 byte at a time

            }

            buff.clear(); // make buffer ready for writing

            bRead = ch.read(buff);

        }

        raf.close();

    }

}

Text in the “example.txt” file is given below...

Output:

Compile and execute the above program to get the output.

C:\raji\blog>javac jNIOEg.java

C:\raji\blog>java jNIOEg

It is the time read the data

This is the sample program for implementing Java NIO. Hope this program helps you to know about Java NIO.  Keep Coding!!!

Java Networking Examples: Client and Server Application in UDP

    UDP(User Datagram Protocol). It is a transport layer protocol which is not a reliable communication. But it suitable for video streaming applications.

Logic:

UDPServer:

  • ·       A DatagramSocket object is created with a port ‘9876’.
  • ·       Data is declared as byte to receive the data packet from client.
  • ·       Server starts receiving packets.
  • ·       Prints the received message in the command prompt.
  • ·       The server stops when it receives the exit message.
  • ·       The server socket is closed.

UDP Client:

  • ·       A datagramSocket is created.
  • ·       IP address of the system is get using getByName() function.
  • ·       Data is declared as byte.
  • ·       Message is created.
  • ·       Data is sent as a datapacket. The datapacket contains the sending data,its length,ip address,port number.
  • ·       After sending the data packet,the socket is closed.

Program implementation:

Client:

import java.net.DatagramPacket;

import java.net.DatagramSocket;

import java.net.InetAddress;

public class UDPClientEg {

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

        DatagramSocket cSocket1 = new DatagramSocket();

        InetAddress IPAddress1 = InetAddress.getByName("localhost");

        byte[] sendData1 = new byte[1024];

        String msg = "welcome to the java networking programming";

        sendData1 = msg.getBytes();

        DatagramPacket sPacket = new DatagramPacket(sendData1, sendData1.length, IPAddress1, 9876);

        cSocket1.send(sPacket);

        System.out.println("Message is sent.");

        cSocket1.close();

    }

}

Server:

import java.net.DatagramPacket;

import java.net.DatagramSocket;

public class UDPServerEg {

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

        DatagramSocket sSocket = new DatagramSocket(9876);

        byte[] recData = new byte[1024];

        while (true) {

            DatagramPacket recPacket = new DatagramPacket(recData, recData.length);

            sSocket.receive(recPacket);

            String msg = new String(recPacket.getData(), 0, recPacket.getLength());

            System.out.println("Received: " + msg);

            if (msg.equals("exit")) {

                System.out.println("Server is going to exit.");

                break;

            }

        }

        sSocket.close();

    }

}

Output:

Client:

C:\raji\blog>javac UDPClientEg.java

C:\raji\blog>java UDPClientEg

Message is sent.

Server:

C:\raji\blog>javac UDPServerEg.java

C:\raji\blog>java UDPServerEg

Received: welcome to the java networking programming

This is a simple client and server implementation using UDP. You can use this code as sample and modify if you need. Keep coding!!!