Friday, December 31, 2021

Livelock in Java Multi-Threading

Livelock in Java multi-threading is a situation where two or more threads are acting on a response to an action of each other and not able to make any progress because of that.

How livelock is different from deadlock in Java multi-threading is that in case of deadlock threads get blocked whereas in case of livelock threads are active but busy responding to each other thus not making any progress.

Livelock Java example

Let’s see example of livelock in Java multi-threading to understand it. A classic example to explain livelock is a multi-threaded application to deposit and withdraw money from accounts with a provision to rollback the transaction if transaction doesn’t go through.

import java.util.concurrent.locks.ReentrantLock;

public class LivelockDemo {
  public static void main(String[] args) {
    Account acct1 = new Account(101, 5000);
    Account acct2 = new Account(102, 7000);
    // Creating two threads
    Thread thread1 = new Thread(new Operation(acct1, acct2, 100));
    Thread thread2 = new Thread(new Operation(acct2, acct1, 100));

    thread1.start();
    thread2.start();
  }
}

class Account{
  int acctNum;
  int balance;
  ReentrantLock lock = new ReentrantLock();
  Account(int acctNum, int balance){
    this.acctNum = acctNum;
    this.balance = balance;
  }
    
  /**
  * Method for depositing amount
  * @param amount
  * @return
  */
  public boolean deposit(int amount){
    System.out.println("In deposit method");
    if(this.lock.tryLock()){
      try {
        // Simulating some delay
        Thread.sleep(500);
      } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      System.out.println("deposit in " + this.acctNum + " for " 
        + Thread.currentThread().getName());
      this.balance = balance + amount;
      return true;
    }
    return false;
  }
    
  /**
   * Method for withdrawing amount
   * @param amount
   * @return
   */
  public boolean withdraw(int amount){
    System.out.println("In withdraw method");
    if(this.lock.tryLock()){
      try {
        // Simulating some delay
        Thread.sleep(500);
      } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
      System.out.println("Withdrawn from " + this.acctNum + " for " 
      + Thread.currentThread().getName());
      this.balance = balance - amount;
      return true;
    }
    return false;
  }
    
  public boolean transact(Account targetAcct, int amount){
    //System.out.println("In transact method " + targetAcct);
    boolean flag = false;
    // If you can withdraw from the source account and
    // deposit it into target account then only return true        
    if(this.withdraw(amount) && targetAcct.deposit(amount)){
      flag = true;
    }else{
      // Rollback and deposit the withdrawn amount back in source account    
      System.out.println("Failed to deposit in " + targetAcct.acctNum + 
        " depositing back in account " + this.acctNum);
      this.deposit(amount);       
    }
    return flag;
  }
}

class Operation implements Runnable{
  Account sourceAccount;
  Account targetAccount;
  int amount;
  Operation(Account sourceAccount, Account targetAccount, int amount){
    this.sourceAccount = sourceAccount;
    this.targetAccount = targetAccount;
    this.amount = amount;
  }

  @Override
  public void run() {      
    sourceAccount.transact(targetAccount, amount);
  }
}

Output

In withdraw method
In withdraw method
Withdrawn from 102 for Thread-1
In deposit method
Withdrawn from 101 for Thread-0
In deposit method
Failed to deposit in 101 depositing back in account 102
In deposit method
Failed to deposit in 102 depositing back in account 101
In deposit method
deposit in 102 for Thread-1
deposit in 101 for Thread-0

Here you can see that you have two threads where one is withdrawing amount from Account 101 and depositing it in 102 and the other thread is withdrawing amount from Account 102 and depositing it in 101. Threads are failing to complete the transaction because of not able to get the lock and rolling back the transaction.

In the above example transaction is not run in the loop so the threads make just one attempt, you can change the run method as follows and see how both threads keep trying and rolling back the transactions without making any real progress.

public void run() {
 while(!sourceAccount.transact(targetAccount, amount)){
  continue;
 } 
}

If you run your code with these changes in run() method you will have to terminate your program to come out of the loop.

Output

In withdraw method
In withdraw method
Withdrawn from 101 for Thread-0
Withdrawn from 102 for Thread-1
In deposit method
In deposit method
Failed to deposit in 101 depositing back in account 102
In deposit method
Failed to deposit in 102 depositing back in account 101
In deposit method
deposit in 102 for Thread-1
In withdraw method
deposit in 101 for Thread-0
In withdraw method
Withdrawn from 101 for Thread-0
In deposit method
Withdrawn from 102 for Thread-1
In deposit method
Failed to deposit in 102 depositing back in account 101
In deposit method
Failed to deposit in 101 depositing back in account 102
In deposit method
deposit in 102 for Thread-1
In withdraw method
deposit in 101 for Thread-0
In withdraw method
Withdrawn from 102 for Thread-1
In deposit method
Withdrawn from 101 for Thread-0
In deposit method
Failed to deposit in 101 depositing back in account 102
In deposit method
Failed to deposit in 102 depositing back in account 101
In deposit method
deposit in 101 for Thread-0
In withdraw method
deposit in 102 for Thread-1
In withdraw method
Withdrawn from 101 for Thread-0
In deposit method
Withdrawn from 102 for Thread-1
In deposit method

That's all for this topic Livelock in Java Multi-Threading. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. Thread Starvation in Java Multi-Threading
  2. Why wait(), notify() and notifyAll() methods are in Object class
  3. Race Condition in Java Multi-Threading
  4. Java ReentrantLock With Examples
  5. Java Multithreading Interview Questions And Answers

You may also like-

  1. Lock Striping in Java Concurrency
  2. AtomicInteger in Java With Examples
  3. Executor And ExecutorService in Java With Examples
  4. How HashSet Works Internally in Java
  5. New Date And Time API in Java With Examples
  6. Heap Memory Allocation in Java
  7. Difference Between Checked And Unchecked Exceptions in Java
  8. Java String substring() Method - Getting Substring

Wednesday, December 29, 2021

Garbage Collection in Java

In the post Heap Memory Allocation in Java I have already explained why heap is divided into generations and how it helps in garbage collection by adopting an approach known as “generational collection”.

In this post we’ll see more details about garbage collection in Java, basic process of garbage collection, garbage collection tuning and types of garbage collectors available in Java.

What is Garbage Collection

Garbage collection in Java is an automatic process of inspecting the heap memory and identifying which objects are in use and which are not and deleting the unused objects after identification.

Here object which is in use (referenced object) means that a part of your program is still holding a reference to the object. Unused object (unreferenced object) means not referenced by any part of your program and can be deleted safely.

Basic Garbage Collection Process

Basic garbage collection process in Java has three steps-

  1. Marking
  2. Sweeping
  3. Compacting

Marking

The first step in the garbage collection process is called marking. In this step GC iterates through the memory and identifies which objects are still in use and which objects are unused.

Sweeping

In this step of sweeping (normal deletion) objects which are already marked as unused in the “marking” step are removed in order to free space.

Compacting

Deleting the unused objects fragments the memory which results in further memory allocation which are not contiguous. That is why there is another step which moves the reference objects together which results in having a contiguous free space thus making the new memory allocation much easier and faster.

garbage collection compacting process
garbage collection in Java

Performance parameters for GC

There are two goals for any application with respect to garbage collection–

  • Maximum pause time goal
  • Application throughput goal

Maximum Pause Time Goal

All minor garbage collections and major garbage collections are "Stop the World" events which means all application threads are stopped until the garbage collection completes. So, the goal here is to minimize this pause time or restrict it by putting an upper limit.

That is what this parameter does; maximum pause time goal is to limit the longest of these pauses.

Note here that only parallel collector provides a command line option to specify a maximum pause time goal.

Command line option

-XX:MaxGCPauseMillis=<nnn> 

This option is a hint to the garbage collector that pause times of <nnn> milliseconds or less are desired.

Throughput Goal

Since garbage collection is "Stop the world event" stopping all the application threads so we can divide the total time into-

  • The time spent collecting garbage
  • The application time

The throughput goal is measured in terms of the time spent collecting garbage and the time spent outside of garbage collection.

Note here that only parallel collector provides a command line option to specify a throughput goal.

Command line option

-XX:GCTimeRatio=<nnn>

The ratio of garbage collection time to application time is 1 / (1 + <nnn>). For example, -XX:GCTimeRatio=9 sets a goal of 1/10th or 10% of the total time for garbage collection.

Garbage collectors available in Java

The Java HotSpot VM has three different types of collectors-

  1. Serial GC
  2. Parallel GC also known as Throughput Collector.
  3. Mostly Concurrent Collector – Java HotSpot offers two types of mostly concurrent collector.
    • Concurrent Mark Sweep (CMS) Collector
    • Garbage First, Garbage collector (G1 Collector)

Serial Collector

The serial collector uses a single thread to do both minor and major collections. The serial collector is best-suited to single processor machines, because it cannot take advantage of multiprocessor hardware. Since only a single thread performs garbage collection so Serial GC is most suited for applications that do not have low pause time requirements.

Command Line Switches

The serial collector is selected by default on certain hardware (client machines) and operating system configurations. Serial collector can be explicitly enabled with the option

-XX:+UseSerialGC.

Parallel Collector

In parallel collector (also known as the throughput collector) multiple threads are used for garbage collection.

The command line option to enable parallel collector is -XX:+UseParallelGC.

By default, with this option, both minor and major collections are executed in parallel to further reduce garbage collection overhead.

The feature that enables the parallel collector to perform major collections in parallel is known as parallel compaction. If parallel compaction is not enabled then major collections are performed using a single thread.

Command line option to turn off parallel compaction is : -XX:+UseParallelOldGC.

Only parallel collector provides command line options to tune the performance parameters as stated above.

Command Line Switches

  • Maximum Garbage Collection Pause Time: The maximum pause time goal is specified with the command-line option -XX:MaxGCPauseMillis=<N>.
  • Throughput goal: The throughput goal is specified by the command-line option -XX:GCTimeRatio=<N>

Concurrent Mark Sweep (CMS) Collector

Concurrent Mark Sweep (CMS) Collector, as the name suggests, performs garbage collection concurrently while the application is running. Since application also keep running that results in low pause time but the application throughput is affected because processor resources are shared.

This collector should be considered for any application with a low pause time requirement.

Like other available collectors the CMS collector is generational; thus both minor and major collections occur. The CMS collector attempts to reduce pause times due to major collections by using separate garbage collector threads to trace the reachable objects concurrently with the execution of the application threads. CMS (Concurrent Mark Sweep) garbage collection does not do compaction.

Pauses in CMS collector

The CMS collector pauses an application twice during a concurrent collection cycle. The first pause marks those objects as live which are directly reachable from the roots and from elsewhere in the heap. This first pause is referred to as the initial mark pause.

The second pause comes at the end of the concurrent tracing phase and finds objects that were missed by the concurrent tracing due to updates by the application threads of references in an object after the CMS collector had finished tracing that object. This second pause is referred to as the remark pause.

Command Line Switches

  • The command line option to enable CMS collector is -XX:+UseConcMarkSweepGC.
  • Command line option to set the number of threads -XX:ParallelCMSThreads=<n>

Garbage-First Garbage Collector

The Garbage-First (G1) garbage collector is a server-style garbage collector which is suited for multiprocessor machines with large memories. G1 garbage collector minimizes the garbage collection (GC) pause time while achieving high throughput at the same time.

It minimizes the garbage collection (GC) pause time by trying to adhere to pause time goals which is set using the flag MaxGCPauseMillis.

Technique used by G1 collector

Technique used by G1 collector to achieve high performance and pause time goals is explained below-

G1 Collector partitions the heap into a set of equally sized heap regions.

Image credit- https://www.oracle.com/technetwork/tutorials/tutorials-1876574.html

Initially G1 performs a concurrent global marking throughout the heap to determine which objects are still referenced and which are not (unreferenced). Once the marking is done G1 knows which regions are mostly empty. It collects these mostly empty regions first thus the name Garbage-First. By using this method of garbage collection G1 frees the large amount of free space by sweeping only a small region of heap.

G1 tries to adhere to the specified pause time target (defined by using flag MaxGCPauseMillis) by using a pause prediction model. It calculates how many regions can be collected within the given pause time limit and collects only those regions.

G1 is generational in a logical sense

As already stated heap is partitioned into a set of equally sized heap regions. A set of empty regions is designated as the logical young generation. Objects are allocated from that logical young generation and that young generation (those regions of heap) is garbage collected when it is full. In some cases, regions outside the set of young regions (regions designated as tenured generation) can be garbage collected at the same time. This is referred to as a mixed collection.

G1 collector also compacts the memory by copying the live objects to selected, initially empty regions.

G1 collector changes in Java Versions

G1 collector is the default garbage collector Java 9 onward. Till Java 8 default garbage collector was Parallel GC.

Though G1 garbage collector is designed to avoid full collections but a full GC occurs if memory is not reclaimed fast enough with in the pause time target. In Java 9 implementation of the full GC for G1 used a single threaded mark-sweep-compact algorithm which meant an increased pause time.

Java 10 onward G1 collector uses the parallelized mark-sweep-compact algorithm to minimize the impact for users experiencing full GCs.

Command Line Switches

The command line option to enable G1 collector is -XX:+UseG1GC.

Reference-

http://www.oracle.com/technetwork/articles/java/architect-evans-pt1-2266278.html
https://docs.oracle.com/cd/E15289_01/doc.40/e15058/underst_jit.htm

That's all for this topic Garbage Collection in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Just In Time Compiler (JIT) in Java
  2. JVM Run-Time Data Areas - Java Memory Allocation
  3. Heap Memory Allocation in Java
  4. PermGen Space Removal in Java 8
  5. How to run javap programmatically from Java Program

You may also like-

  1. What are JVM, JRE and JDK in Java
  2. Java Reflection API Tutorial
  3. Transient Keyword in Java With Examples
  4. Java Stream API Examples
  5. Busy Spinning in Multi-Threading
  6. How HashMap Works Internally in Java
  7. Callable and Future in Java With Examples
  8. Core Java Basics Interview Questions And Answers

Monday, December 27, 2021

Convert Numbers to Words Java Program

In this post we’ll see a Java program to convert numbers to words. For example, in the Java program if number 5467 is passed then the output in words should be- Five thousand four hundred sixty seven.

Number systems

In Indian system numbers are called differently and even placement is different than in the international system.

For example-

11,23,45,657- Eleven crore twenty three lakhs forty five thousand six hundred fifty seven

As you can see the numbers here are Crore, Lakhs also the digits are grouped in twos except the hundreds where three digits are grouped.

In international system same number will be written as-

112,345,657- One hundred twelve million three hundred forty five thousand six hundred fifty seven

Here you can notice that the digits are grouped in threes and the digit group separator (hundred, thousand, million...) is placed after every three digits.

We’ll have Java program for converting numbers to words for both Indian and international system and how digits are grouped forms the logic for the programs.

Converting number to words in Java – International System

As already stated above, in the program we’ll have to get the three digits of the number in each iteration and put the correct place value after those three digits.

In the program we’ll also have different arrays for the numbers.

public class ConvertNumToWord {
  private static final String[] units = {
    "",
    " one",
    " two",
    " three",
    " four",
    " five",
    " six",
    " seven",
    " eight",
    " nine"
  }; 
  private static final String[] twoDigits = {
    " ten",
    " eleven",
    " twelve",
    " thirteen",
    " fourteen",
    " fifteen",
    " sixteen",
    " seventeen",
    " eighteen",
    " nineteen"
  };
  private static final String[] tenMultiples = {
    "",
    "",
    " twenty",
    " thirty",
    " forty",
    " fifty",
    " sixty",
    " seventy",
    " eighty",
    " ninety"
  };
  private static final String[] placeValues = {
    " ",
    " thousand",
    " million",
    " billion",
    " trillion"
  };
        
  private static String convertNumber(long number) {    
    String word = "";    
    int index = 0;
    do {
      // take 3 digits in each iteration
      int num = (int)(number % 1000);
      if (num != 0){
        String str = ConversionForUptoThreeDigits(num);
        word = str + placeValues[index] + word;
      }
      index++;
      // next 3 digits
      number = number/1000;
    } while (number > 0);
    return word;
  }
    
  private static String ConversionForUptoThreeDigits(int number) {
    String word = "";    
    int num = number % 100;
    if(num < 10){
      word = word + units[num];
    }
    else if(num < 20){
      word = word + twoDigits[num%10];
    }else{
      word = tenMultiples[num/10] + units[num%10];
    }
    
    word = (number/100 > 0)? units[number/100] + " hundred" + word : word;
    return word;
  }
    
  public static void main(String[] args) {
    System.out.println("1234123456789- " + convertNumber(1234123456789L));
    System.out.println("123456789- " + convertNumber(123456789));
    System.out.println("37565820- " + convertNumber(37565820));
    System.out.println("9341947- " + convertNumber(9341947));
    System.out.println("37000- " + convertNumber(37000));
    System.out.println("1387- " + convertNumber(1387));
    System.out.println("10- " + convertNumber(10));
    System.out.println("41- " + convertNumber(41));
  }
}

Output

1234123456789-  one trillion two hundred thirty four billion one hundred twenty three million four hundred fifty six thousand seven hundred eighty nine 
123456789-  one hundred twenty three million four hundred fifty six thousand seven hundred eighty nine 
37565820-  thirty seven million five hundred sixty five thousand eight hundred twenty 
9341947-  nine million three hundred forty one thousand nine hundred forty seven 
37000-  thirty seven thousand
1387-  one thousand three hundred eighty seven 
10-  ten 
41-  forty one 

Converting number to words in Java – Indian System

As already stated above, for Indian system in the program we’ll have to get the three digits of the number in first iteration and then two digits in each iteration and put the correct place value after each iteration.

The array for placeValues will change as per Indian system.

public class ConvertNumToWord {
  private static final String[] units = {
    "",
    " one",
    " two",
    " three",
    " four",
    " five",
    " six",
    " seven",
    " eight",
    " nine"
  }; 
  private static final String[] twoDigits = {
    " ten",
    " eleven",
    " twelve",
    " thirteen",
    " fourteen",
    " fifteen",
    " sixteen",
    " seventeen",
    " eighteen",
    " nineteen"
  };
  private static final String[] tenMultiples = {
    "",
    "",
    " twenty",
    " thirty",
    " forty",
    " fifty",
    " sixty",
    " seventy",
    " eighty",
    " ninety"
  };
  private static final String[] placeValues = {
    "",
    " thousand",
    " lakh",
    " crore",
    " arab",
    " kharab"
  };
        
  private static String convertNumber(long number) {    
    String word = "";    
    int index = 0;
    boolean firstIteration = true;
    int divisor;
    do {
      divisor = firstIteration ? 1000 : 100;
      // take 3 or 2 digits based on iteration
      int num = (int)(number % divisor);          
      if (num != 0){
        String str = ConversionForUptoThreeDigits(num);
        word = str + placeValues[index] + word;
      }
      index++;
      // next batch of digits
      number = number/divisor;
      firstIteration = false;
    } while (number > 0);
    return word;
  }
    
  private static String ConversionForUptoThreeDigits(int number) {
    String word = "";    
    int num = number % 100;
    if(num < 10){
      word = word + units[num];
    }
    else if(num < 20){
      word = word + twoDigits[num%10];
    }else{
      word = tenMultiples[num/10] + units[num%10];
    }
    
    word = (number/100 > 0)? units[number/100] + " hundred" + word : word;
    return word;
  }
    
  public static void main(String[] args) {
    System.out.println("1234123456789- " + convertNumber(1234123456789L));
    System.out.println("326776756- " + convertNumber(326776756));
    System.out.println("37565820- " + convertNumber(37565820));
    System.out.println("9341947- " + convertNumber(9341947));
    System.out.println("37000- " + convertNumber(37000));
    System.out.println("1387- " + convertNumber(1387));
    System.out.println("10- " + convertNumber(10));
    System.out.println("5- " + convertNumber(5));
  }
}

Output

1234123456789-  twelve kharab thirty four arab twelve crore thirty four lakh fifty six thousand seven hundred eighty nine
326776756-  thirty two crore sixty seven lakh seventy six thousand seven hundred fifty six
37565820-  three crore seventy five lakh sixty five thousand eight hundred twenty
9341947-  ninety three lakh forty one thousand nine hundred forty seven
37000-  thirty seven thousand
1387-  one thousand three hundred eighty seven
10-  ten
5-  five

That's all for this topic Convert Numbers to Words Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Convert double to int in Java
  2. Arrange Non-Negative Integers to Form Largest Number - Java Program
  3. Split a String Java Program
  4. Converting String to int in Java
  5. Converting String to Enum Type in Java

You may also like-

  1. Printing Numbers in Sequence Using Threads Java Program
  2. How to Create PDF in Java Using OpenPDF
  3. Difference Between Two Dates in Java
  4. Creating Tar File And GZipping Multiple Files in Java
  5. How to Pass Command Line Arguments in Eclipse
  6. static Import in Java With Examples
  7. Java String Interview Questions And Answers
  8. Spring MVC Pagination Example Using PagedListHolder

Sunday, December 26, 2021

Access Modifiers in Java - Public, Private, Protected and Default

Access level modifiers in Java (public, private, protected, default) are used to control the visibility of the class or the members of the class i.e. fields and methods. These access modifiers determine whether other classes can use a particular field, invoke a particular method or create object of any given class.


Types of Access Modifiers in Java

  • private- private modifier specifies that the member can only be accessed in its own class.
  • default (or package-private)- If no specifier is used (which is known as default access) member is visible only within its own package.
  • protected- protected modifier specifies that the member can only be accessed within its own package and by a subclass of its class in another package.
  • public- public modifier specifies that member is visible to all classes everywhere.

Access modifiers in Java can be used with-

  • Class
  • Fields
  • Methods
  • Constructors

Access modifier with Java classes

In Java programming language only two of the access modifiers can be used at the class level- public or default.

  • If a class is declared with the access modifier as public, that class is visible to all classes everywhere.
  • If a class has no modifier (the default), it is visible only within its own package.

Example of Java default access modifier

If there is one class DefaultClass in package org.netjs.examples

package org.netjs.examples;

class DefaultClass {
 public void display(){
  System.out.println("display method : Default class");
 }
}

Then if you try to create object of this class in another class which resides in different package (org.netjs.prog) it will result in compile time error.

package org.netjs.prog;

public class Test {
 public static void main(String[] args) {
  // ERROR
  DefaultClass dc = new DefaultClass();
 }
}

Java Access modifiers with fields

All the four types of access modifiers in Java- public, protected, default, private can be used with variables declared in the class.

  • If a field is declared as public then it is visible to all classes in the same package or other packages.
  • If a fields is declared with no access specifier (default) then it can be accessed by any class in the same package.
  • If a field is defined as protected then it is accessible to any class in the same package or to any subclass (of the class where field is declared) in different package.
  • If a field is defined private then that field can only be accessed in its own class.

Let's take an example when a field is protected-

If there is class DefaultClass in package org.netjs.examples

package org.netjs.examples;

public class DefaultClass {
 protected String item;
 public void display(){
  System.out.println("display method : Default class");
 }
}
Then in Test class in another package org.netjs.examples item variable won't be accessible. It will give "field not visible" error.
package org.netjs.examples;

public class Test {
  public static void main(String[] args) {
    DefaultClass dc = new DefaultClass();
    //Error
    dc.item = "laptop";
  }
}

If Test class extends DefaultClass then item variable will be accessible with the Test class object.

package org.netjs.examples;

public class Test extends DefaultClass {
 public static void main(String[] args) {
  Test t = new Test();
  t.item = "laptop";
 }
}

Java Access modifier with methods

All the four types of access modifiers- public, protected, default, private can be used with methods of the class and access modifier for the methods work the same way as for the fields.

Access modifier with Constructors

All four types of access modifiers in Java- public, protected, default, private can be used with constructors of the class.

In case constructor of the class is private then the object of that class can be created by that class only. You might have seen that in Singleton design pattern.

In case no modifier is used (default) then the object of the class can be created by the classes with in the same package.

As example if there is a class DefaultClass within the package org.netjs.examples

public class DefaultClass {
  // Constructor
  DefaultClass(){
    System.out.println("In DefaultClass constructor ");
  }
  protected String item;
  public void display(){
    System.out.println("display method : Default class");
  }
}

Then trying to access constructor of DefaultClass in the class Test (sub class of DefaultClass) which resides in org.netjs.prog package will result in compile time error- "The constructor DefaultClass() is not visible"

package org.netjs.prog;

import org.netjs.examples.DefaultClass;

public class Test extends DefaultClass{
  Test(){
    super();
  }
  public static void main(String[] args) {
    Test t = new Test();
  }
}

In case DefaultClass' constructor is marked as protected then the above program will work. As subclass in different package can access the protected constructor.

If constructor of the class is public then its object can be created from anywhere- class residing in the same package or in a different package.

Class member access summary

Following table shows the access levels for the class members with different access modifiers in Java.

Private No Modifier Protected Public
Same class Yes Yes Yes Yes
Same package subclass No Yes Yes Yes
Same package another class No Yes Yes Yes
Different package subclass No No Yes Yes
Different package another class No No No Yes

That's all for this topic Access Modifiers in Java - Public, Private, Protected and Default. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related Topics

  1. Object in Java
  2. Encapsulation in Java
  3. Constructor chaining in Java
  4. Inheritance in Java
  5. Core Java Basics Interview Questions And Answers

You may also like-

  1. super Keyword in Java With Examples
  2. Difference Between Abstract Class And Interface in Java
  3. Fail-Fast Vs Fail-Safe Iterator in Java
  4. equals() And hashCode() Methods in Java
  5. Interface Static Methods in Java
  6. Java CountDownLatch With Examples
  7. Count Number of Words in a String Java Program
  8. Print Odd-Even Numbers Using Threads And wait-notify Java Program

Saturday, December 25, 2021

Spring Object XML Mapping (OXM) JAXB Example

In this post we’ll see how to serialize an object graph to XML (marshalling) and how to deserialize the XML to an object graph (unmarshalling) using JAXB and Spring OXM module.

Spring Object-XML mapping support

Spring framework provides support for converting an XML document to/from an object using Spring-OXM module.

Spring-OXM provides abstractions to the O/X mapping frameworks through two interfaces - Marshaller and Unmarshaller.

These abstractions allow you to switch O/X mapping frameworks with relative ease, with little or no changes required on the classes that do the marshalling.

The implementation classes provided by Spring-OXM for these interfaces are-

  1. Jaxb2Marshaller- For object-XML mapping using JAXB.
  2. CastorMarshaller- For object-XML mapping using Castor. Refer Spring Object XML Mapping Support - Castor Example to see an example of XML marshalling-unmarshalling in Spring using Castor.
  3. JibxMarshaller- For object-XML mapping using JIBX.

Object to XML mapping using JAXB – Spring Example

In this example we’ll see how to do XML marshalling and unmarshalling using JAXB and Spring-OXM.

Maven dependencies

Along with Spring core dependencies you’ll need following dependencies for JAXB and Spring-OXM.

<properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <java.version>10</java.version>
  <spring.version>5.0.8.RELEASE</spring.version>
</properties>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-oxm</artifactId>
  <version>${spring.version}</version>
</dependency>
<dependency>
  <groupId>javax.xml.bind</groupId>
  <artifactId>jaxb-api</artifactId>
  <version>2.3.0</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-impl</artifactId>
  <version>2.3.0</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-core</artifactId>
  <version>2.3.0</version>
</dependency>

Bean classes

Two classes are used in this XML marshalling and unmarshalling example, User class whose objects are returned in the XML form and UserListContainer class which contains the List of objects of type User.

User.java

import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;

@XmlRootElement
@XmlType(propOrder = {"firstName", "lastName", "email"})
public class User {
  private int id;
  private String firstName;
  private String lastName;
  private String email;
  public User() {
    
  }
  public User(int id, String firstName, String lastName, String email) {
    this.id = id;
    this.firstName = firstName;
    this.lastName = lastName;
    this.email = email;
  }
  @XmlAttribute(name="id")
  public int getId() {
    return id;
  }
  public void setId(int id) {
    this.id = id;
  }

  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;
  }
  @Override
  public String toString() {
    return "id- " + getId() + " First Name- " + getFirstName() + 
      " Last Name- " + getLastName() + " Email- " + getEmail();
  }
}

UserListContainer.java

@XmlRootElement(name="users")
public class UserListContainer {
  private List<User> userList;

  @XmlElement(name = "user")
  public List<User> getUserList() {
    return userList;
  }

  public void setUserList(List<User> userList) {
    this.userList = userList;
  }
}

As you can see in these classes JAXB annotations are used-

@XmlRootElement- To specify the root element for the XML.
@XmlElement- To specify the elements in XML.
@XmlAttribute- To specify the element attribute.
@XmlType(propOrder = ..)- Specifies the order for XML Schema elements.

Spring XML Configuration for JAXB2Marshaller

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:task="http://www.springframework.org/schema/task"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/task
    http://www.springframework.org/task/spring-task.xsd">


  <bean id="jaxb2Marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
    <property name="classesToBeBound">
      <list>
        <value>org.netjs.model.User</value>
        <value>org.netjs.model.UserListContainer</value>
      </list>
    </property>
  </bean>  
  <bean id="objXmlmapper" class="org.netjs.service.ObjXMLMapper">
    <property name="marshaller" ref="jaxb2Marshaller" />
    <property name="unmarshaller" ref="jaxb2Marshaller" />
  </bean>
</beans>

With JAXB2Marshaller bean you can define the classes which are used in Marshalling. Since JAXB2Marshaller class implements both the Marshaller and Unmarshaller interfaces so the same bean is provided as reference for both marshaller and unmarshaller properties in ObjXMLMapper bean.

ObjXMLMapper.java

This is the class where marshalling and unmarshalling is done using the JAXB2Marshaller class in Spring-OXM. In the class Marshaller and Unmarshaller interfaces are used which are set to JAXB2Marshaller instance using the Spring configuration.
public class ObjXMLMapper {
  private static final String FILE_NAME = "users.xml";
  private Marshaller marshaller;
  private Unmarshaller unmarshaller;
  public void setMarshaller(Marshaller marshaller) {
    this.marshaller = marshaller;
  }
  public void setUnmarshaller(Unmarshaller unmarshaller) {
    this.unmarshaller = unmarshaller;
  }
  // Converting object graph to XML (marshalling)
  public void objToXML() throws IOException {
    // call to get object graph
    UserListContainer userList = getUsers();
    try (FileOutputStream os = new FileOutputStream(FILE_NAME)) {            
      this.marshaller.marshal(userList, new StreamResult(os));        
    } 
  }
  // Converting XML to an object graph (unmarshalling) 
  public void XMLToObj() throws IOException {
    UserListContainer userList = new UserListContainer();
    try (FileInputStream is = new FileInputStream(FILE_NAME)) {            
      userList = (UserListContainer)this.unmarshaller.unmarshal(new StreamSource(is));        
    } 
    userList.getUserList().forEach(System.out::println);
  }
    
  public UserListContainer getUsers(){
    List<User> users = getListOfUsers();
    UserListContainer userList = new UserListContainer();
    userList.setUserList(users);
    return userList;
  }
  // Dummy method for adding List of Users
  private List<User> getListOfUsers() {
    List<User> users = new ArrayList<User>();
    users.add(new User(1, "Jack", "Reacher", "abc@xyz.com"));
    users.add(new User(2, "Remington", "Steele", "rs@cbd.com"));
    users.add(new User(3, "Jonathan", "Raven", "jr@sn.com"));
    return users;
  }
}
Class used to run the applications.
public class App {
  public static void main( String[] args ){  
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext
                                               ("appcontext.xml");
    ObjXMLMapper objXMLMapper = context.getBean("objXmlmapper", ObjXMLMapper.class);

    try {
      objXMLMapper.objToXML();
      objXMLMapper.XMLToObj();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    context.close();
  }
}

On running you get the XML as follows after the object graph is serialized to XML-

<?xml version="1.0" encoding="UTF-8" standalone="true"?>
<users>
  <user id="1">
    <firstName>Jack</firstName>
    <lastName>Reacher</lastName>
    <email>abc@xyz.com</email>
  </user>
  <user id="2">
    <firstName>Remington</firstName>
    <lastName>Steele</lastName>
    <email>rs@cbd.com</email>
  </user>
  <user id="3">
    <firstName>Jonathan</firstName>
    <lastName>Raven</lastName>
    <email>jr@sn.com</email>
  </user>
</users>
Deserializing the XML to object graph displays the object fields on the console-
id- 1 First Name- Jack Last Name- Reacher Email- abc@xyz.com
id- 2 First Name- Remington Last Name- Steele Email- rs@cbd.com
id- 3 First Name- Jonathan Last Name- Raven Email- jr@sn.com

That's all for this topic Spring Object XML Mapping (OXM) JAXB Example. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Spring Tutorial Page


Related Topics

  1. Spring MVC Pagination Example Using PagedListHolder
  2. Spring MVC Generate Response as XML Example
  3. Connection Pooling Using C3P0 Spring Example
  4. Spring Integration With Quartz Scheduler
  5. Spring Web Reactive - Spring WebFlux Example Using Annotation-Based Programming

You may also like-

  1. Spring Asynchronous Method Execution Support Using @Async Annotation
  2. Sending Email Using Spring Framework Example
  3. Circular Dependency in Spring Framework
  4. Autowiring Using Annotations in Spring
  5. ThreadPoolExecutor - Java Thread Pooling With ExecutorService
  6. TypeWrapper Classes in Java
  7. How to Format Date in Java Using SimpleDateFormat
  8. Installing Ubuntu Along With Windows

Friday, December 24, 2021

Spring Object XML Mapping (OXM) Castor Example

In this post we’ll see how to serialize an object graph to XML (marshalling) and how to deserialize the XML to an object graph (unmarshalling) using Castor and Spring OXM module.

Spring Object-XML mapping support

Spring framework provides support for converting an XML document to/from an object using Spring-OXM module.

Spring-OXM provides abstractions to the O/X mapping frameworks through two interfaces.

  • Marshaller
  • Unmarshaller

These abstractions allow you to switch O/X mapping frameworks with relative ease, with little or no changes required on the classes that do the marshalling.

The implementation classes provided by Spring-OXM for these interfaces are-

  1. CastorMarshaller- For object-XML mapping using Castor.
  2. Jaxb2Marshaller- For object-XML mapping using JAXB. Refer Spring Object XML Mapping Support - JAXB Example to see an example of XML marshalling-unmarshalling in Spring using JAXB.
  3. JibxMarshaller- For object-XML mapping using JIBX.

Object to XML mapping using Castor – Spring Example

In this example we’ll see how to do XML marshalling and unmarshalling using Castor and Spring-OXM.

Maven dependencies

Along with Spring core dependencies you’ll need following maven dependencies for Castor and Spring-OXM.

<properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <java.version>10</java.version>
  <spring.version>5.0.8.RELEASE</spring.version>
</properties>
<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-oxm</artifactId>
  <version>${spring.version}</version>
</dependency>
<dependency>
  <groupId>org.codehaus.castor</groupId>
  <artifactId>castor-core</artifactId>
  <version>1.4.1</version>
</dependency>
<dependency>
  <groupId>org.codehaus.castor</groupId>
  <artifactId>castor-xml</artifactId>
  <version>1.4.1</version>
</dependency>

Bean classes

Two classes are used in this XML marshalling and unmarshalling example, User class whose objects are returned in the XML form and UserListContainer class which contains the List of objects of type User.

User.java

public class User {
  private int id;
  private String firstName;
  private String lastName;
  private String email;
  public User() {
    
  }
  public User(int id, String firstName, String lastName, String email) {
    this.id = id;
    this.firstName = firstName;
    this.lastName = lastName;
    this.email = email;
  }
  public int getId() {
    return id;
  }
  public void setId(int id) {
    this.id = id;
  }

  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;
  }
  @Override
  public String toString() {
  
    return "id- " + getId() + " First Name- " + getFirstName() + 
    " Last Name- " + getLastName() + " Email- " + getEmail();
  }
}

UserListContainer.java

public class UserListContainer {
  private List<User> userList;

  public List<User> getUserList() {
    return userList;
  }

  public void setUserList(List<User> userList) {
    this.userList = userList;
  }
}

Spring XML Configuration for CastorMarshaller

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:task="http://www.springframework.org/schema/task"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/task
    http://www.springframework.org/task/spring-task.xsd">


  <bean id="castorMarshaller" class="org.springframework.oxm.castor.CastorMarshaller">
    <property name="targetPackage" value="org.netjs.model" />
    <property name="mappingLocation" value="classpath:mapping.xml" />
  </bean>  
  <bean id="objXmlmapper" class="org.netjs.service.ObjXMLMapper">
    <property name="marshaller" ref="castorMarshaller" />
    <property name="unmarshaller" ref="castorMarshaller" />
  </bean>
</beans>

With CastorMarshaller bean you can define the target classes which are used in Marshalling or you can define the package where the POJOs reside.

Mapping information for the object fields to XML element or attribute conversion can be provided using a Castor mapping file that information is provided to the CastorMarshaller bean using the mappingLocation property.

Since CastorMarshaller class implements both the Marshaller and Unmarshaller interfaces so the same bean is provided as reference for both marshaller and unmarshaller properties in ObjXMLMapper bean.

ObjXMLMapper.java

This is the class where marshalling and unmarshalling is done using the CastorMarshaller class in Spring-OXM. In the class Marshaller and Unmarshaller interfaces are used which are set to CastorMarshaller instance using the Spring configuration.
public class ObjXMLMapper {
  private static final String FILE_NAME = "users.xml";
  private Marshaller marshaller;
  private Unmarshaller unmarshaller;
  public void setMarshaller(Marshaller marshaller) {
    this.marshaller = marshaller;
  }
  public void setUnmarshaller(Unmarshaller unmarshaller) {
    this.unmarshaller = unmarshaller;
  }
  // Converting object graph to XML (marshalling)
  public void objToXML() throws IOException {
    // call to get object graph
    UserListContainer userList = getUsers();
    try (FileOutputStream os = new FileOutputStream(FILE_NAME)) {            
      this.marshaller.marshal(userList, new StreamResult(os));        
    } 
  }
  // Converting XML to an object graph (unmarshalling) 
  public void XMLToObj() throws IOException {
    UserListContainer userList = new UserListContainer();
    try (FileInputStream is = new FileInputStream(FILE_NAME)) {            
      userList = (UserListContainer)this.unmarshaller.unmarshal(new StreamSource(is));        
    } 
    userList.getUserList().forEach(System.out::println);
  }
    
  public UserListContainer getUsers(){
    List<User> users = getListOfUsers();
    UserListContainer userList = new UserListContainer();
    userList.setUserList(users);
    return userList;
  }
  // Dummy method for adding List of Users
  private List<User> getListOfUsers() {
    List<User> users = new ArrayList<User>();
    users.add(new User(1, "Jack", "Reacher", "abc@xyz.com"));
    users.add(new User(2, "Remington", "Steele", "rs@cbd.com"));
    users.add(new User(3, "Jonathan", "Raven", "jr@sn.com"));
    return users;
  }
}

Castor mapping file (Mapping.xml)

In order to have more control over how the object to/from XML conversion happens a mapping file is provided which Castor uses as a reference.

<?xml version="1.0" encoding="UTF-8"?>
<mapping>
  <class name="org.netjs.model.UserListContainer">   
    <map-to xml="Users"  />     
    <field name="userList" type="org.netjs.model.User" collection="arraylist">
      <bind-xml name="user" node="element" />
    </field>
  </class>
  <class name="org.netjs.model.User">
    <field name="id" type="integer">
         <bind-xml name="id" node="attribute" />
    </field>    
    <field name="firstName" type="string" />
    <field name="lastName" type="string" />
    <field name="email" type="string" />
  </class>
</mapping>

Since we want a parent element as Users which holds the list of users so two class definitions are given in castor mapping file. First class definition is for UserListContainer, which tells that the it contains elements of type User in an ArrayList which are to be bound as User element in XML.

Second class definition is for User type, it tells how fields of User are to be mapped.

Class used to run the application

public class App {
  public static void main( String[] args ){  
    ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext
                                               ("appcontext.xml");
    ObjXMLMapper objXMLMapper = context.getBean("objXmlmapper", ObjXMLMapper.class);

    try {
      objXMLMapper.objToXML();
      objXMLMapper.XMLToObj();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
    context.close();
  }
}
On running you get the XML as follows after the object graph is serialized to XML-
<?xml version="1.0" encoding="ISO-8859-1"?>
<Users>
  <user id="1">
    <first-name>Jack</first-name>
    <last-name>Reacher</last-name>
    <email>abc@xyz.com</email>
  </user>
  <user id="2">
    <first-name>Remington</first-name>
    <last-name>Steele</last-name>
    <email>rs@cbd.com</email>
  </user>
  <user id="3">
    <first-name>Jonathan</first-name>
    <last-name>Raven</last-name>
    <email>jr@sn.com</email>
  </user>
</Users>

Deserializing the XML to object graph displays the object fields on the console-

id- 1 First Name- Jack Last Name- Reacher Email- abc@xyz.com
id- 2 First Name- Remington Last Name- Steele Email- rs@cbd.com
id- 3 First Name- Jonathan Last Name- Raven Email- jr@sn.com

That's all for this topic Spring Object XML Mapping (OXM) Castor Example. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Spring Tutorial Page


Related Topics

  1. Spring MVC Generate Response as XML Example
  2. Spring Transaction Management JDBC Example Using @Transactional Annotation
  3. Spring Web Reactive Framework - Spring WebFlux Tutorial
  4. Spring Thread Pooling Support Using TaskExecutor
  5. Spring Email Scheduling Example Using Quartz Scheduler

You may also like-

  1. Spring Component Scan Example
  2. @Import Annotation in Spring JavaConfig
  3. Spring Bean Life Cycle
  4. How to Inject Prototype Scoped Bean in Singleton Bean
  5. Java ScheduledThreadPoolExecutor - Task Scheduling in Java
  6. Functional Interfaces in Java
  7. Java Exception Handling Interview Questions And Answers
  8. How to Create PDF in Java Using OpenPDF

Thursday, December 23, 2021

Reflection in Java - Getting Field Information

Reflection in Java-class gives a good idea about how class is an entry point to all the Reflection APIs. Once you have Class object you can get information about members of the class fields, constructors, methods. In this post we'll see how to get information about class fields using Java reflection API.

Class fields have a type and a value, the java.lang.reflect.Field class provides methods for accessing type information, field’s modifier and setting and getting values of a field on a given object.


Member Interface in Java Reflection API

With in the Reflection hierarchy an interface java.lang.reflect.Member is defined which is implemented by java.lang.reflect.Field, java.lang.reflect.Method, and java.lang.reflect.Constructor. Thus Member is an interface that reflects identifying information about a single member (a field or a method) or a constructor.

How to get Field object using reflection

There are 4 methods for getting fields of the class.

  • getField(String name)- Returns a Field object that reflects the specified public member field of the class or interface represented by this Class object.
  • getFields()- Returns an array containing Field objects reflecting all the accessible public fields of the class or interface represented by this Class object.
  • getDeclaredField(String name)- Returns a Field object that reflects the specified declared field of the class or interface represented by this Class object.
  • getDeclaredFields()- Returns an array of Field objects reflecting all the fields declared by the class or interface represented by this Class object.

So getFields() methods will only return object for public fields where as getDeclaredField() methods will return all the fields.

Getting field information using Java reflection example

In this example generic class ReflectField is used which has few fields with access modifier as public or private.

import java.lang.reflect.Field;
import java.util.Arrays;
import java.util.List;

public class ReflectField<T> {
  public String name = "Test";
  private int i = 10;
  public List<Integer> numList;
  public T val;
     
  public static void main(String arg[]){
    try {
      Class<?> c = Class.forName("org.netjs.prog.ReflectField");
      try {
        Field f = c.getField("name");
        System.out.println("Name field " + f.getName());
      
        Field[] fields = c.getFields();
        System.out.println("All Fields - " + Arrays.toString(fields));
        
        fields = c.getDeclaredFields();      
        System.out.println("Declared Fields - " + Arrays.toString(fields));
      } catch (NoSuchFieldException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (SecurityException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }    
    }catch (ClassNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}

Output

Name field name

All Fields - [public java.lang.String org.netjs.prog.ReflectField.name, public java.util.List org.netjs.prog.ReflectField.numList, 
public java.lang.Object org.netjs.prog.ReflectField.val]

Declared Fields - [public java.lang.String org.netjs.prog.ReflectField.name, private int org.netjs.prog.ReflectField.i, 
public java.util.List org.netjs.prog.ReflectField.numList, public java.lang.Object org.netjs.prog.ReflectField.val]

You can see here getFields() return array of all public fields in the class where as getDeclaredFields() return all the fields (field i is having access modifier as private).

Getting field type using reflection

If you want to know the types of fields in any class using Java reflection API you can do it using the methods getType() and getGenericType().

Class<?> c = Class.forName("org.netjs.prog.ReflectField");
fields = c.getDeclaredFields();
for(Field field : fields){
  System.out.println("Field name - " + field.getName() 
      + " has Field Type " + field.getType());
  System.out.println("Field name - " + field.getName() 
      + " has Generic Field Type " + field.getGenericType());
}

Output

Field name - name has Field Type class java.lang.String
Field name - name has Generic Field Type class java.lang.String
Field name - i has Field Type int
Field name - i has Generic Field Type int
Field name - numList has Field Type interface java.util.List
Field name - numList has Generic Field Type java.util.List<java.lang.Integer>
Field name - val has Field Type class java.lang.Object
Field name - val has Generic Field Type T

Here notice that the type for the field val is displayed as java.lang.Object because generics are implemented via type erasure which removes all information regarding generic types during compilation. Thus T is replaced by the upper bound of the type variable, in this case, java.lang.Object.

Getting field modifiers using reflection

You can get the field modifiers by using the getModifiers() method. This method returns the Java language modifiers for the field represented by this Field object, as an integer. The Modifier class should be used to decode the modifiers.

Class<?> c = Class.forName("org.netjs.prog.ReflectField");
fields = c.getDeclaredFields();
for(Field field : fields){     
    System.out.println("Field name - " + field.getName() + " has modifier " 
       + Modifier.toString(field.getModifiers()));
}

Output

Field name - name has modifier public
Field name - i has modifier private
Field name - numList has modifier public
Field name - val has modifier public

Getting and Setting Field Values using reflection

If you have an object of a class, using Java reflection API you can set the values of fields in that class. This is typically done only in special circumstances when setting the values in the usual way is not possible. Because such access usually violates the design intentions of the class, it should be used with the utmost discretion.

Given a public field name which is of type String here the new value is set to the field name.

public String name = "Test";
Class<?> c = Class.forName("org.netjs.prog.ReflectField");
ReflectField rf = new ReflectField();
Field f = c.getField("name");
// getting the field value
System.out.println("Value of field name " + f.get(rf));
// setting the new field value
f.set(rf, "New Value");
System.out.println("Value of field name " + rf.name);

Output

Value of field name Test
Value of field name New Value

That's all for this topic Reflection in Java - Getting Field Information. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Java Reflection API Tutorial
  2. Reflection in Java - Getting Class Information
  3. Invoking Getters And Setters Using Reflection in Java
  4. Java Object Cloning - clone() Method
  5. Serialization and Deserialization in Java

You may also like-

  1. Java Nested Class And Inner Class
  2. Serialization Proxy Pattern in Java
  3. How to Pass Command Line Arguments in Eclipse
  4. Try-With-Resources in Java With Examples
  5. Type Casting in Java With Conversion Examples
  6. Lambda Expressions in Java 8
  7. Optional Class in Java With Examples
  8. ConcurrentHashMap in Java With Examples

Wednesday, December 22, 2021

Converting Char to String And String to Char in Java

In this post we’ll see Java programs for char to String and String to char conversions.

Converting char to String in Java

For converting char to String you can use any of the following methods.

  1. Character.toString(char c)- Returns a String object representing the specified char.
  2. String.valueOf(char c)- Returns the string representation of the char argument.

Java program

public class CharToString {

 public static void main(String[] args) {
  char ch = 'x';
  // Using toString() method
  String str = Character.toString(ch);
  System.out.println("Converted String - " + str);
  
  // Using valueOf() method
  str = String.valueOf(ch);
  System.out.println("Converted String - " + str);
 }
}

Output

Converted String - x
Converted String – x

Converting String to char in Java

For converting String to char you can use one of the following options.

  1. Using charAt(int index) method of the String class. This method returns the char value at the specified index.
  2. Using toCharArray() method of the String class you can convert the String to char array and then get the char out of that array using the array index.
public class StringToChar {

 public static void main(String[] args) {
  String str = "Test";
  // getting the 3rd char in the String 
  // index is 0 based
  char ch = str.charAt(2);
  System.out.println("Character is- " + ch);
  
  // By getting char array
  System.out.println("----------------");
  char[] charArr = str.toCharArray();
  for(char c : charArr) {
   System.out.println("Character is- " + c);
  }
 }
}

Output

Character is- s
----------------
Character is- T
Character is- e
Character is- s
Character is- t

That's all for this topic Converting Char to String And String to Char in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Convert Numbers to Words Java Program
  2. Converting Enum to String in Java
  3. Convert String to float in Java
  4. How to Iterate a HashMap of ArrayLists of String in Java
  5. Find Duplicate Characters in a String With Repetition Count Java Program

You may also like-

  1. How to Read Excel File in Java Using Apache POI
  2. Compress And Decompress File Using GZIP Format in Java
  3. Find Largest and Second Largest Number in Given Array Java Program
  4. Difference Between Two Dates in Java
  5. Map.Entry Interface in Java
  6. Java Collections Interview Questions And Answers
  7. Type Casting in Java With Conversion Examples
  8. Spring Web MVC Tutorial

Tuesday, December 21, 2021

Find The Maximum Element in Each Row of a Matrix Java Program

In this post we’ll see a Java program to find the maximum element in each row of a matrix.

For example if the matrix is as follows-

3  7  9 
12 89 23 
1  17 32

Then the output should be-

Maximum element in row 1- 9
Maximum element in row 2- 89
Maximum element in row 3- 32

Java program to find maximum element in each row of a matrix

Initially user will be prompted to enter the matrix elements to create a matrix. Also create an array having the same length as the number of rows in the matrix.

Then iterate the matrix one row at a time and compare each column element with the max number if max number is less than the column element then assign column element to the max number. After the row is iterated (outer loop finishes one iteration) assign the maximum number to the corresponding index of the created array.

public class MatrixMax {
  public static void main(String[] args) {
    //create matrix by taking input from user
    int rows; 
    int columns;
    Scanner scanner = new Scanner(System.in);
    // 
    System.out.println("Enter number of rows: ");
    rows = scanner.nextInt(); 
    
    System.out.println("Enter number of columns: "); 
    columns = scanner.nextInt(); 
    
    int[][] matrix = new int [rows][columns];
      
    System.out.println("Enter matrix numbers: "); 
    for (int i = 0; i < rows; i++) {
      System.out.println("Enter numbers for row - " + (i+1) + " and press enter"); 
      for (int j = 0; j < columns; j++) {
        matrix[i][j] = scanner.nextInt();
      }
    }
    scanner.close();
    // Displaying entered matrix
    System.out.println("Matrix as entered");
    for (int i = 0; i < matrix .length; i++) {
      System.out.println();
      for (int j = 0; j < matrix[i].length; j++) {
        System.out.print(matrix[i][j] + " ");
      }
    }
    System.out.println();
    // call method to find max element per row
    findMaxEachRow(matrix);
  }

  private static void findMaxEachRow(int[][] matrix){ 
    int[] result = new int[matrix.length];
    for (int i = 0; i < matrix.length; i++) {
      // Assign first element of the row as 
      // maximum in first iteration
      int maxNum = matrix[i][0];
      for (int j = 0; j < matrix[i].length; j++) {
        if(maxNum < matrix[i][j]){
          maxNum = matrix[i][j];
        }
        result[i] = maxNum;
      }     
    }
      
    // Display results
    for (int i = 0; i < result.length; i++) {
      System.out.println("Maximum element in row " + (i + 1) + "- " + result[i]);
    }
  }
}

Output

Enter number of rows: 
3
Enter number of columns: 
3
Enter matrix numbers: 
Enter numbers for row - 1 and press enter
12 20 67
Enter numbers for row - 2 and press enter
56 34 55
Enter numbers for row - 3 and press enter
1 2 78
Matrix as entered

12 20 67 
56 34 55 
1  2  78 
Maximum element in row 1- 67
Maximum element in row 2- 56
Maximum element in row 3- 78

If you are asked to find the minimum element in each row of a matrix then you need to change just this line-

if(maxNum < matrix[i][j]) to if(minNum > matrix[i][j])

Variable maxNum is changed to minNum for readability.

That's all for this topic Find The Maximum Element in Each Row of a Matrix Java Program. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Matrix Subtraction Java Program
  2. Find Largest And Smallest Number in a Given Array Java Program
  3. How to Display Pyramid Patterns in Java - Part1
  4. Java Program to Display Prime Numbers
  5. Reverse Each Word in a String Java Program

You may also like-

  1. How to Convert Date to String in Java
  2. Invoking Getters And Setters Using Reflection in Java
  3. Producer-Consumer Java Program Using volatile
  4. How to Read Excel File in Java Using Apache POI
  5. Java Multithreading Interview Questions And Answers
  6. Is String Thread Safe in Java
  7. Java Object Cloning - clone() Method
  8. Dependency Injection in Spring Framework

Monday, December 20, 2021

Why Java String is Immutable

String in Java is immutable which means once you create a String object the content of that string cannot be modified. If you modify that string then a new String object is created with the modified value, leaving the original string intact.

For example-

String str = "Test";
str.concat(" String");
System.out.println("Original String- " + str);

Output

Original String- Test

As you can see in String str another String is concatenated but that creates a new String object, original string can’t be altered as String is immutable. Since the new string “Test String” is not referenced so it is eligible for garbage collection.

Java String immutable

Even though you can’t modify a String but you can change the reference, so following is valid.

String str = "Test";
str = str.concat(" String");
System.out.println("Original String- " + str);

Output

Original String- Test String

As you can see now str references the modified string.

String reference change

Why is String immutable in Java

Why is String immutable in Java is one of the frequently asked String interview question. Here are some of the points to explain the reason behind the design decision to make String immutable in Java.

1. Usage of constant String pool- Since String class is one of the most used classes in Java so certain optimizations have been done to make String class more efficient. One of that optimization is to use String Pool in Java so that the String objects having same value share the same memory rather than creating new objects. That helps in reducing memory usage of string objects. This usage of String pool is possible only because String is immutable in Java.

Consider the scenario where two or more objects are sharing a reference in string pool. If one of those objects is modified then a new object is created because of String immutability leaving the original object intact to be shared by other objects.

String pool

Here both str1 and str2 are sharing the reference, now value of str2 is modified. Because of String immutability a new object is created, if it were not the case and original value was modified then str1 would reference a changed value which is not correct.

2. Making Strings thread safe- Making String immutable in Java also makes String objects thread safe. String objects can be shared among multiple threads even if any thread modify the original object it will get a new object because of immutability, so original object remains intact.

3. Good candidate as hash keys- Making String immutable in Java also makes them a good candidate as a hash key in hash based data structures like HashMap. Since String can’t be modified once value is assigned to it that means hash code once calculated for any string also won’t change. This facilitates the caching of hashcode rather than calculating hashcode each time, making hashing more efficient.

Drawback of String immutability in Java

One drawback of String immutability is any modification results in creation of new object. Thus a code as given below results in creation of many intermediate objects which are later discarded.

String str = "Test";
str = str.concat(" String").concat("Another").concat("String");

In the case string is modified frequently consider using StringBuffer or StringBuilder classes which are mutable.

That's all for this topic Why Java String is Immutable. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Basics Tutorial Page


Related topics

  1. How to Create Immutable Class in Java
  2. String Vs StringBuffer Vs StringBuilder in Java
  3. String join() Method And StringJoiner Class in Java
  4. Java String Search Using indexOf(), lastIndexOf() And contains() Methods
  5. Find All Permutations of a Given String Java Program

You may also like-

  1. Convert String to float in Java
  2. Java Variable Types With Examples
  3. Java do-while Loop With Examples
  4. Fail-Fast Vs Fail-Safe Iterator in Java
  5. Externalizable Interface in Java
  6. Java Collections Interview Questions And Answers
  7. Magic Methods in Python With Examples
  8. Sending Email Using Spring Framework Example