Wednesday, June 30, 2021

Angular ngSwitch Directive With Examples

In the post Angular ngIf Directive With Examples we saw how to use ngIf directive but you may have a scenario where you need to render different elements based on different conditions. In such scenario you can use Angular ngSwitch directive rather than using ngIf several times.

Angular ngSwitch directive

The [ngSwitch] directive on a container specifies an expression to match against. The expressions to match are provided by ngSwitchCase directives on views within the container.

Syntax of Angular ngSwitch

<container-element [ngSwitch]="switch_expression">
  <some-element *ngSwitchCase="match_expression_1">...</some-element>
  <some-element *ngSwitchCase="match_expression_2">...</some-element>
  ...
  <some-element *ngSwitchDefault>...</some-element>
</container-element>
  1. Every view that matches is rendered.
  2. If there are no matches, a view with the ngSwitchDefault directive is rendered.
  3. ngSwitchDefault element is optional. If you don't use it, nothing will be rendered when there is no matching value.
  4. Note that asterisk (*) precedes the ngSwitchCase which means it is a structural directive and used to add or remove DOM element.
  5. If the value of the match_expression matches the value of the switch_expression, the corresponding element is added to the DOM. If the expression doesn’t match, then the element is excluded from the DOM.
  6. The element that the ngSwitch directive is applied to is always included in the HTML document, ngSwitch is specified within square brackets.

Tuesday, June 29, 2021

Angular ngFor Directive With Examples

Angular ngFor directive is the looping directive in Angular that iterates over each item in the collection and renders the element (or section of elements) for each item.

Here is an example where ngFor is contained in an <li> element.

<li *ngFor="let item of items>
  ..
  ..
</li>

Note that ngFor is the shorthand form which is internally expanded into a long form that uses the ngForOf selector on an <ng-template> element.

<ng-template ngFor let-item [ngForOf]="items">
  <li>...</li>
</ng-template>

Note that asterisk (*) precedes the ngFor which means it is a structural directive and used to add or remove DOM element.

Monday, June 28, 2021

Java LinkedBlockingDeque With Examples

LinkedBlockingDeque in Java is an implementation of the BlockingDeque interface and it was added in Java 6.

LinkedBlockingDeque is an optionally bounded deque and it stores its elements as linked nodes. Since it is optionally bounded so it has constructor which takes initial capacity as parameter. In case capacity is not specified it is equal to Integer.MAX_VALUE.

Java LinkedBlockingDeque constructors

LinkedBlockingDeque in Java has three constructors-

  • LinkedBlockingDeque()- Creates a LinkedBlockingDeque with a capacity of Integer.MAX_VALUE.
  • LinkedBlockingDeque(Collection<? extends E> c)- Creates a LinkedBlockingDeque with a capacity of Integer.MAX_VALUE, initially containing the elements of the given collection, added in traversal order of the collection's iterator.
  • LinkedBlockingDeque(int capacity)- Creates a LinkedBlockingDeque with the given (fixed) capacity.

Here note that Linked nodes are dynamically created upon each insertion unless this would bring the deque above capacity. In case initial capacity is defined then the blocking method like put(E e) will wait if necessary for space to become available.

Since elements are stored as linked nodes so most of the operations like add(), addFirst(), put(), putFirst() run in constant time (ignoring time spent blocking). Exceptions include remove(object o), removeFirstOccurrence, removeLastOccurrence, contains, iterator.remove(), and the bulk operations, all of which run in linear time.

LinkedBlockingDeque Java Example code

Let's create a produce consumer bounded buffer using LinkedBlockingDeque which is an implmentation of BlockingDeque.

Values will be inserted in the LinkedBlockingDeque using put() method, which will block if the space is full.

Values will be retrieved from the LinkedBlockingDeque using take() method, which retrieves and removes the head of this queue, waiting if necessary until an element becomes available.

Here in the Produce class some delay is induced using sleep() method. You can see that in Consumer class, where it is taking elements out of the deque, no excpetion will be thrown but it will block. If you are using eclipse you can see that delay in the console when it is printing.

import java.util.concurrent.BlockingDeque;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;

public class LinkedBlockingDQDemo {
  public static void main(String[] args) {
    SharedClass buffer = new SharedClass();
    // Starting two threads
    ExecutorService executor = Executors.newFixedThreadPool(2);
    executor.execute(new Producer(buffer));
    executor.execute(new Consumer(buffer));
    executor.shutdown();
  }
}
/**
 * 
 */
class Producer implements Runnable{
  SharedClass buffer;
  Producer(SharedClass buffer){
    this.buffer = buffer;
  }
  @Override
  public void run() {
    for(int i = 0; i < 10; i++){
      buffer.put(i);
      if(i == 4){
        try {
          // introducing some delay using sleep
          Thread.sleep(1000);
        } catch (InterruptedException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
    }
  }
}
/**
 * 
 */
class Consumer implements Runnable{
  SharedClass buffer;
  Consumer(SharedClass buffer){
    this.buffer = buffer;
  }
  @Override
  public void run() {
    for(int i = 0; i < 10; i++){
      buffer.get();;
    }
  }    
}

//Shared class used by threads
class SharedClass{
  int i;
  // Bounded LinkedBlockingDeque of size 10
  BlockingDeque<Integer> linkedBlockingDeque = new LinkedBlockingDeque<Integer>(10);
    
  public void get(){
    try {
      // take method to get from blockingdeque
      System.out.println("Consumer recd - " + linkedBlockingDeque.take());
    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
    
  public void put(int i){
    this.i = i;
    try {
      // putting in blocking deque
      linkedBlockingDeque.put(i);
      System.out.println("Putting - " + i);
    }
    catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } 
  }
}

Output

Putting - 0
Putting - 1
Putting - 2
Putting - 3
Putting - 4
Consumer recd - 0
Consumer recd - 1
Consumer recd - 2
Consumer recd - 3
Consumer recd - 4
Putting - 5
Consumer recd - 5
Putting - 6
Consumer recd - 6
Putting - 7
Consumer recd - 7
Putting - 8
Consumer recd - 8
Putting - 9
Consumer recd - 9

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


Related Topics

  1. Java BlockingDeque With Examples
  2. Java BlockingQueue With Examples
  3. Java LinkedBlockingQueue With Examples
  4. Java Phaser With Examples
  5. Java Concurrency Interview Questions And Answers

You may also like-

  1. Race Condition in Java Multi-Threading
  2. Why wait(), notify() And notifyAll() Methods Are in Object Class And Not in Thread Class
  3. Java ThreadLocal Class With Examples
  4. Functional Interfaces in Java
  5. Java Stream API Tutorial
  6. Heap Memory Allocation in Java
  7. static Keyword in Java With Examples
  8. Data Access in Spring Framework

Sunday, June 27, 2021

How to Iterate a HashMap of ArrayLists of String in Java

This Java program shows how to iterate a HashMap that contains arraylists of String.

In the Java program to iterate a HashMap containing ArrayLists there is a method getMap() where 3 lists are created and stored in the HashMap.

First you need to iterate the HashMap, though there are several ways to iterate over a HashMap, but here I have used the for-each loop for iterating the created HashMap. Each Map.Entry object is a key-value pair where value is the ArrayList stored with the given key. That's the list retrieved using listEntry.getValue() method.

In the second for-each loop List that is retrieved using listEntry.getValue() is iterated and the elements that are in the list are displayed.

Java Program to Iterate HashMap of ArrayLists

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MapLoop {

  public static void main(String[] args) {
    MapLoop mapLoop = new MapLoop();
    Map<String, List<String>> cityMap = mapLoop.getMap();
    int i = 0;
    // iterating over a map
    for(Map.Entry<String, List<String>> listEntry : cityMap.entrySet()){
      System.out.println("Iterating list number - " + ++i);
      // iterating over a list
      for(String cityName : listEntry.getValue()){
        System.out.println("City - " + cityName);
      }
    }
  }
    
  /**
   * A method to create a list and store it in a Map
   * @return
  */
  private Map<String, List<String>> getMap(){
    Map<String, List<String>> cityMap = new HashMap<String, List<String>>();
    // First List
    List<String> temp = new ArrayList<String>();  
    temp.add("Delhi");
    temp.add("Mumbai");
    // Putting first list in the map
    cityMap.put("1", temp);
    // Second List
    temp = new ArrayList<String>();  
    temp.add("Hyderabad");
    temp.add("Bangalore");
    // Putting second list in the map
    cityMap.put("2", temp);
    // Third List
    temp = new ArrayList<String>();
    temp.add("Kolkata");
    temp.add("Chennai");
    // Putting third list in the map
    cityMap.put("3", temp);
    return cityMap;
  }
}
Output
Iterating list number - 1
City - Delhi
City - Mumbai
Iterating list number - 2
City - Hyderabad
City - Bangalore
Iterating list number - 3
City - Kolkata
City - Chennai

That's all for this topic How to iterate a Hash map of arraylists of String 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. How HashMap Internally Works in Java
  2. How to Loop Through a Map in Java
  3. How to Loop or Iterate an Arraylist in Java
  4. How to Sort ArrayList of Custom Objects in Java
  5. Count Number of Times Each Character Appears in a String Java Program

You may also like-

  1. Method Overloading in Java
  2. Dependency Injection in Spring Framework
  3. Race Condition in Java Multi-Threading
  4. Java ReentrantLock With Examples
  5. CopyOnWriteArrayList in Java With Examples
  6. Java Exception Handling Interview Questions And Answers
  7. Java Collections Interview Questions And Answers
  8. Producer-Consumer Java Program Using wait notify

Thursday, June 24, 2021

Producer-Consumer Java Program Using ArrayBlockingQueue

This Java program solves the Producer-Consumer problem using threads and ArrayBlockingQueue which is an implementation of the BlockingQueue interface.

Initial capacity of the ArrayBlockingQueue will be kept one so that producer and consumer both get a chance alternatively.

Values will be inserted in the ArrayBlockingQueue using put() method, which will block if the space is full.

Values will be retrieved from the ArrayBlockingQueue using take() method, which retrieves and removes the head of this queue, waiting if necessary until an element becomes available.

In the program there is a class Buffer which is shared by both threads. In comparison to produce-consumer using wait notify this version using blocking queue is much simpler as you don't need to write the logic for making the thread wait or notifying the waiting thread.

Producer-Consumer program in Java Using ArrayBlockingQueue

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ArrayBQDemo {
  public static void main(String[] args) {
    Buffer buffer = new Buffer();
    // Starting two threads
    ExecutorService executor = Executors.newFixedThreadPool(2);
    executor.execute(new ProdTask(buffer));
    executor.execute(new ConTask(buffer));
    executor.shutdown();
  }
}

class ProdTask implements Runnable{
  Buffer buffer;
  ProdTask(Buffer buffer){
    this.buffer = buffer;
  }
  @Override
  public void run() {
    for(int i = 0; i < 5; i++){
      buffer.put(i);
    }
  }
}

class ConTask implements Runnable{
  Buffer buffer;
  ConTask(Buffer buffer){
    this.buffer = buffer;
  }
  @Override
  public void run() {
    for(int i = 0; i < 5; i++){
      buffer.get();;
    }
  }    
}

//Shared class used by threads
class Buffer{
  int i;
  // Bouded ArrayBlockingQueue of size 1
  BlockingQueue<Integer> arrayBlockingQ = new ArrayBlockingQueue<Integer>(1);
  public void get(){
    try {
      // take method to get from blockingqueue
      System.out.println("Consumer recd - " + arrayBlockingQ.take());
    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
    
  public void put(int i){
    this.i = i;
    try {
      // putting in blocking queue
      arrayBlockingQ.put(i);
      System.out.println("Putting - " + i);
    } catch (InterruptedException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}

Output

Putting - 0
Consumer recd - 0
Putting - 1
Consumer recd - 1
Putting - 2
Consumer recd - 2
Putting - 3
Consumer recd - 3
Putting - 4
Consumer recd - 4

That's all for this topic Producer-Consumer Java Program Using ArrayBlockingQueue. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Print Odd-Even Numbers Using Threads And Semaphore Java Program
  2. Java ArrayBlockingQueue With Examples
  3. How to Run Threads in Sequence in Java
  4. Setting And Getting Thread Name And Thread ID in Java
  5. Java Multithreading Interview Questions And Answers

You may also like-

  1. How to Sort Elements in Different Order in TreeSet
  2. Convert int to String in Java
  3. Connection Pooling Using Apache DBCP in Java
  4. How to Create PDF From XML Using Apache FOP
  5. Race Condition in Java Multi-Threading
  6. Abstraction in Java
  7. Interface Default Methods in Java
  8. Bean Scopes in Spring With Examples

Wednesday, June 23, 2021

Java String Interview Questions And Answers

In this post some of the Java String Interview Questions are listed. This compilation will help the Java developers in preparing for their interviews.

  1. What is String in Java?

    In Java String class represents character strings which means; Strings in Java are objects and all strings are instances of the String class. Internally in String class Strings are stored as character array.

    Read more about String in Java here.

  2. In how many ways String object can be created?

    Since strings are objects so strings can of course be created using new operator. String class has more than 10 constructors to create Strings which ranges from taking nothing as parameter to taking char array, StringBuffer, StringBuilder, another String as argument.
    Another and more preferred way to create Strings is to assign String literal directly to a String reference as you will do for any primitive type. For every string literal Java will automatically constructs a String object.

    As example- String str = “abc”; 
    

    Read more about String in Java here.

  3. If String can be created using String str = “test” then String is a primitive data type.Yes/No?

    No. For every string literal Java automatically constructs a String object.


  4. What is String pool? Where is it created in memory?

    When String literals are created they are stored in a String pool and that is a common pool; which means if there are two strings literals having the same content then those string will share the space in the pool.
    When String object is created by assigning a string literal, pool will be checked to verify if there is any existing object with the same content if there is then that existing reference is used, no new object is created in that case. If no object is found with the same content then this new literal will be added in the pool.
    String pool is stored in the heap.

    Read more about String Pool in Java here.

  5. What is immutable object? Is String object immutable?

    An immutable object is an object that would not be able to change its state after creation. Thus immutable object can only be in one state and that state can not be changed after creation of the object.
    Yes String object is immutable. Once you create a String object the content of that string cannot be modified.


  6. Why is String class immutable?

    Since Java maintains a string pool where String references are shared thus changing content of any of the String will also affect the other strings sharing the same references that’s one reason why string is immutable.

    Read more about String immutability here.

  7. Why is String class final in Java?

    Since String is immutable, whenever you perform any operation on string which alters its content a new string object is created containing the modified string. Which means all the methods of the String class that modify the content in any way return a new String object with the modified content.
    Now, What if you can override the method of the String class so that it modifies and return the original string reference itself? In that case all the other strings having the same data in the string pool will also get affected as the reference is shared for the String literals having the same content.
    To avoid these kind of scenarios String class is declared as final and it can’t be overridden.


  8. Which operator is overloaded for String?

    ‘+’ operator is overloaded in Java for String. It is used for concatenating two strings.


  9. How many objects will be created if two Strings are created this way?

    String s1 = “test”; 
    String s2 =  “test”;
    

    Since s1 and s2 are string literals and having the same content object reference will be shared by them in the string pool. Therefore only one object is created.


  10. How many objects will be created if two Strings are created this way?

    String s1 = “test”;
    String s2 =  new String(“test”);
    

    In this case string literal goes to string pool and s2 is another object created using new. So, in this case two objects are created even if content is same.


  11. How many objects will be created if two Strings are created this way?

    String s1 = new String(“test”);
    String s2 =  new String(“test”);
    

    Two separate objects are created.
    If you check it using the following code

    if(s1 == s2){
      System.out.println("s1 and s2 are same");
    }else{
      System.out.println("s1 and s2 are not same");
    }
    
    s1 and s2 are not same will be displayed.


  12. How many object will be created if Strings are created this way?

    String s1 = “test”;
    String s2 =  new String(“test”);
    String s3 = new String(“test”).intern();
    

    s1 will go to string pool, for s2 new object is created. S3, though created using new will still search in the string pool for any reference having the same content as intern() method is used. So two objects will be created.


  13. What is intern() method in String?

    Using intern() method you can still get string object from the pool (if it exists) even if new operator is used to create a string.
    When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

    Read more about intern() method in Java here.

  14. Is String thread safe in Java?

    Yes string is thread safe in Java as String is immutable.

    Read more about String and thread safety in Java here.

  15. What is StringBuffer in Java?

    StringBuffer class is the companion class of String. StringBuffer is a mutable(modifiable) sequence of characters which is in contrast to String class which is an immutable sequence of characters. Thus in case of StringBuffer length and content of the sequence can be changed through certain method calls.
    Since StringBuffer is mutable a new String object is not created every time string is modified, which in turn results in less memory consumptions and not having lots of intermediate String object for garbage collection.

    Read more about StringBuffer in Java here.

  16. What is StringBuilder in Java?

    StringBuilder class (Added in Java 5),just like StringBuffer, is a mutable(modifiable) sequence of characters which is in contrast to String class which is an immutable sequence of characters. Thus in case of StringBuilder length and content of the sequence can be changed through certain method calls.

    Read more about StringBuilder in Java here.

  17. Differences among String, StringBuffer and StringBuilder in Java?

    String is immutable where as both StringBuffer and StringBuilder are mutable.
    String and StringBuffer are thread safe where as StringBuilder is not thread safe.

    Read more about String Vs StringBuffer Vs StringBuilder in Java here.

  18. Is StringBuffer class also immutable in Java?

    No, StringBuffer is not immutable.

    Read more about StringBuffer in Java here.

  19. Is StringBuffer class also final in Java?

    Yes, StringBuffer class is final in Java.


  20. Is StringBuffer class thread safe?

    Yes StringBuffer class is thread safe. Methods in StringBuffer class are synchronized.


  21. Is StringBuilder class thread safe?

    No StringBuilder class is not thread safe. That makes it faster than StringBuffer.


  22. Is StringBuilder class also final in Java?

    Yes StringBuilder class is final in Java.

    Read more about StringBuilder in Java here.

  23. How to compare two strings in Java?

    equals() method can be used for comparing two strings in Java. If you want to ignore case then you can use equalsIgnoreCase(String anotherString) method.
    There are also compareTo() and compareToIgnoreCase() methods for comparing two strings lexicographically. Returns an integer indicating whether this string is greater than (result is > 0), equal to (result is = 0), or less than (result is < 0) the argument.
    You can also use matches() method where you can pass a regular expression for matching strings.

    Read more about String comparison in Java here.

  24. What will happen if “==” operator is used to compare two strings in Java?

    “==” operator will compare the references of the strings not the content.

    String str1 = "abc";
    String str4 = new String("abc");
    
    Comparing these two strings using “==” operator
     if(str1 == str4)
    
    will return false as the references are different.


  25. How to get characters and substrings by index with in a String?

    You can get the character at a particular index within a string by invoking the charAt() accessor method.

    String str = "Example String";
    char resChar = str.charAt(3);
    
    Will give char ‘m’. If you want to get more than one consecutive character from a string, you can use the substring method. The substring method has two versions -
    • String substring(int beginIndex, int endIndex) - Returns a new string that is a substring of this string.
    • String substring(int beginIndex) - Returns a new string that is a substring of this string.

    Read more about String charAt() and subString() methods in Java here.
  26. How can you find characters or substrings within a string?

    To find characters or substrings with in a string indexOf() and lastIndexOf() methods can be used.
    You can also use contains() method
    public boolean contains(CharSequence s) - Returns true if and only if this string contains the specified sequence of char values. Otherwise it returns false.

    Read more about charAt() and subString() methods in Java here.
  27. How can you split a string in Java?

    String provides a split method in order to split the string into one or more substring based on the given  regular expression.
    As example If you have a string where one (or more) spaces are used and you want to split it around those spaces.

    String str1 = "split example    program";
    String[] strArray = str1.split("\\s+");
    

    Read more about Splitting a String using split() method in Java here.
  28. How can you join strings in Java?

    With Java 8 join() method has been added in the String class which makes it very easy to join the multiple strings.
    join method has two overloaded versions -

    • public static String join(CharSequence delimiter, CharSequence... elements) - Returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter.
    • public static String join(CharSequence delimiter, Iterable<? extends CharSequence> elements) – Here elements is an Iterable that will have its elements joined together and delimiter is a sequence of characters that is used to separate each of the elements in the resulting String.

    Read more about String join() method in Java 8 here.
  29. Can we use String in switch case statement?

    Yes from Java 7 string can be used in switch case statement.


Related Topics

  1. Java OOP Interview Questions And Answers
  2. Core Java Basics Interview Questions And Answers
  3. Java Exception Handling Interview Questions And Answers
  4. Java Multithreading Interview Questions And Answers
  5. Java Collections Interview Questions And Answers
  6. Java Concurrency Interview Questions And Answers
  7. Java Lambda Expressions Interview Questions And Answers
  8. Java Stream API Interview Questions And Answers

Monday, June 21, 2021

How to Create Immutable Class in Java

In this tutorial we will learn how to create an immutable class in Java.

Immutable class, as the name suggests, is a class whose object can’t be modified in anyway once created. Once an object of the immutable class is created and initialized the content of any field of that object can’t be changed in anyway and remains same throughout the life of the object. If there are methods that modify the content in some way then a new object is created with the modified content and returned, original object does not change.

As example String in Java is an immutable class though there are methods with in String class like substring or replace which modify the created String object. You can see in the code of the String class that for all these type of methods a new string is created with the modified data and returned. Other examples of immutable classes in Java are all the wrapper classes for primitive types like Integer, Long etc. BigDecimal and BigInteger are also immutable classes.

How to create an immutable class in Java

There are certain steps that are to be followed for creating an immutable class in Java–

  1. Methods of the class should not be overridden by the subclasses. You can ensure that by making your class final.

  2. Make all fields final and private. Marking fields as final ensures that their value is not changed. If the field is of primitive type, then it’s value can’t be changed as it is final. If field is holding a reference to another object, then declaring that field as final means its reference can’t be changed.
    Having access modifier as private for the fields ensure that fields are not accessed outside the class.

  3. Initialize all the fields in a constructor.

  4. Don’t provide setter methods or any method that can change the state of the object. Only provide methods that can access the value (like getters).

  5. In case any of the fields of the class holds reference to a mutable object any change to those objects should also not be allowed, for that–
    • Make sure that there are no methods with in the class that can change those mutable objects (change any of the field content).
    • Don’t share reference of the mutable object, if any of the methods of your class return the reference of the mutable object then its content can be changed.
    • If reference must be returned create copies of your internal mutable objects and return those copies rather than the original object. The copy you are creating of the internal mutable object must be a deep copy not a shallow copy.

In case you are wondering why such elaborate procedure for the fields holding references when fields are already final and references can’t be changed. Remember that even if reference cannot be changed you can still change the content of the fields with in a mutable object which goes against what you want to achieve by making your class immutable.

Creating Immutable class Java example

In the example we'll create an immutable class that holds another class object too along with fields of other types. There are two classes, Address class is the mutable class whose object is there in the immutable class ImmutableEmployee.

Address.java

public class Address {
 private String addressLine1;
 private String addressLine2;
 private String city;
 public String getAddressLine1() {
  return addressLine1;
 }
 public void setAddressLine1(String addressLine1) {
  this.addressLine1 = addressLine1;
 }
 public String getAddressLine2() {
  return addressLine2;
 }
 public void setAddressLine2(String addressLine2) {
  this.addressLine2 = addressLine2;
 }
 public String getCity() {
  return city;
 }
 public void setCity(String city) {
  this.city = city;
 }
 public String toString() {
  return "AddressLine1 " + addressLine1 + " AddressLine2 " + addressLine2 + " City " + city;
 }
}

ImmutableEmployee

public class ImmutableEmployee {
 private final String name;
 private final int age;
 private final Address empAddress;
 ImmutableEmployee(String name, int age, String add1, String add2, String city){
  this.name = name;
  this.age = age;
  // don't pass reference around create a new object with in constructor
  empAddress = new Address();
  empAddress.setAddressLine1(add1);
  empAddress.setAddressLine2(add2);
  empAddress.setCity(city);
 }
 
 public String getName() {
  return name;
 }
 public int getAge() {
  return age;
 }
 
 public Address getEmpAddress() {
  // creating copy of the mutable object for returning
  Address adr = new Address();
  adr.setAddressLine1(empAddress.getAddressLine1());
  adr.setAddressLine2(empAddress.getAddressLine2());
  adr.setCity(empAddress.getCity());
  return adr;
  /*return empAddress;*/
 }
 
 public String toString() {
  return "Name " + name + " Age " + age + " Address " + empAddress;
 }

 public static void main(String[] args) {
  ImmutableEmployee ie = new ImmutableEmployee("Jack", 32, "34, Hunter's Glen", "Pine Street", "Brooklyn");
  System.out.println("Employee information " + ie);
  Address adr = ie.getEmpAddress();
  adr.setCity("London");
  System.out.println("Employee information " + ie);
 }
}

Output

Employee information Name Jack Age 32 Address AddressLine1 34, Hunter's Glen AddressLine2 Pine Street City Brooklyn
Employee information Name Jack Age 32 Address AddressLine1 34, Hunter's Glen AddressLine2 Pine Street City Brooklyn

Here notice that in the line Address adr = ie.getEmpAddress(); I get the address object and change the city in the object but that change is not reflected in the Employee object because getEmpAddress() method creates and returns a new Address object.

You can change that method to return the original Address object, in that case your getEmpAddress() method will look like this–

 public Address getEmpAddress() {
  /*Address adr = new Address();
  adr.setAddressLine1(empAddress.getAddressLine1());
  adr.setAddressLine2(empAddress.getAddressLine2());
  adr.setCity(empAddress.getCity());
  return adr;*/
  return empAddress;
 }

Now if you execute the code and see the output-

Output

Employee information Name Jack Age 32 Address AddressLine1 34, Hunter's Glen AddressLine2 Pine Street City Brooklyn
Employee information Name Jack Age 32 Address AddressLine1 34, Hunter's Glen AddressLine2 Pine Street City London

You can see that Employee information is changed, you are now able to change the content of the Employee class object which should not be happening as it’s an immutable class. That’s why the point as mentioned above “If reference must be returned create copies of your internal mutable objects and return those copies rather than the original object.” is important.

If your class has any mutable object or using any of the modifiable collections like ArrayList, HashSet, HashMap same steps are to be followed.

Advantages of using immutable class

  1. One of the advantage of an immutable class is it is thread safe and its object can be shared among many threads without any fear of content of the original object getting changed. Refer String and thread safety to have more clarity on this point.

  2. Another advantage is you can cache immutable class objects as you know content won’t change once the object is created so no fear of dirty read. This ability to cache and reuse reduces overhead.

  3. If you ever wondered why do you see mostly String as a key for HashMap, yes, it is mostly because of String being immutable. So, if you are somehow required to use your own custom object as key and want to make sure that the object is not changed by any means (like any other thread) making that class immutable will be an option.

Disadvantages of using immutable class

  1. If the second point in the advantages of using immutable class has impressed you to make as many immutable classes in your Java application as possible just take a pause and think of the disadvantage too. Any get method where you are supposed to return the immutable class object or any field that holds a reference to a mutable object you do need to create a new object every time, copy the content from the original object and then return it. Which results in creation of many new objects and performing deep copies which again is expensive.

That's all for this topic How to Create Immutable Class in Java. 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 Deadlock in Java
  2. Print Odd-Even Numbers Using Threads And wait-notify Java Program
  3. Remove Duplicate Elements From an Array in Java
  4. Is String Thread Safe in Java
  5. String Comparison in Java equals(), compareTo(), startsWith() Methods

You may also like-

  1. Java ReentrantLock With Examples
  2. Difference Between HashMap And ConcurrentHashMap in Java
  3. Invoking Getters And Setters Using Reflection in Java
  4. Java Stream API Tutorial
  5. Serialization Proxy Pattern in Java
  6. Nested class and Inner class in Java
  7. Ternary Operator in Java With Examples
  8. Type Casting in Java

Sunday, June 20, 2021

Java Program to Get All DB Schemas

In this post we’ll see a Java program to list all the schemas in a DB. Database used here is MySQL.

List all DB schemas using Java

To get all the database schemas in Java you can use the getCatalogs() method provided by the DatabaseMetaData interface in the JDBC API.

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DBMetaData {
  public static void main(String[] args) {
    Connection connection = null;
    try {
      // Loading driver
      Class.forName("com.mysql.jdbc.Driver");
      // Creating connection
      connection = DriverManager.getConnection("jdbc:mysql://localhost:3306", 
                        "root", "admin");
      // Getting DatabaseMetaData object
      DatabaseMetaData dbMetaData = connection.getMetaData();
    
      // getting Database Schema Names
      ResultSet rs = connection.getMetaData().getCatalogs();
      while (rs.next()) {
        System.out.println("Schema Name - " + rs.getString("TABLE_CAT"));
      }
      
   } catch (ClassNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
   } catch (SQLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
   }finally{
      if(connection != null){
       //closing connection 
       try {
         connection.close();
       } catch (SQLException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
       }
      } // if condition
    }// finally
  }
}

Two points to note here are-

  • In the DB URL you are providing for connection, you don’t have to provide any specific schema. So your URL would be like this– jdbc:mysql://localhost:3306
  • getCatalogs() method returns a resultset which has only one column “TABLE_CAT” so you can use that column to get value or column index as 1 to get the value. i.e. rs.getString("TABLE_CAT") or rs.getString(1). By iterating through that result set you can get the list of all DB schemas.

That's all for this topic Java Program to Get All DB Schemas. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Java Program to Get All The Tables in a DB Schema
  2. Connection Pooling Using Apache DBCP in Java
  3. Connection Pooling Using C3P0 in Java
  4. Batch Processing in Java JDBC - Insert, Update Queries as a Batch
  5. CallableStatement Interface in Java-JDBC

You may also like-

  1. Remove Duplicate Elements From an Array in Java
  2. Convert float to String in Java
  3. Configuring DataSource in Spring Framework
  4. Spring JdbcTemplate Insert, Update And Delete Example
  5. Garbage Collection in Java
  6. Java Stream API Tutorial
  7. ConcurrentHashMap in Java With Examples
  8. Synchronization in Java - Synchronized Method And Block

Saturday, June 19, 2021

Java Program to Get All The Tables in a DB Schema

In this post we’ll see a Java program to get all the tables in a schema in a DB. Database used here is MySQL.

For listing DB schema tables in Java you can use getTables(String catalog, String schemaPattern, String tableNamePattern, String[] types) method provided by the DatabaseMetaData interface in the JDBC API. You can provide null as value for all the parameters, that way you don’t narrow the search and all the tables are returned. If you want to narrow your search to get specific tables then you can provide values for these parameters.

Listing DB schema tables Java example

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DBMetaData {
  public static void main(String[] args) {
    Connection connection = null;
    try {
      // Loading driver
      Class.forName("com.mysql.jdbc.Driver");

      // Creating connection
      connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/world", 
                          "root", "admin");
      // Getting DatabaseMetaData object
      DatabaseMetaData dbMetaData = connection.getMetaData();
     
      ResultSet rs = dbMetaData.getTables(null, null, null, null);       
      
      while (rs.next()){
        System.out.println(""Table name - " " + rs.getString(3));
      }    
    } catch (ClassNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (SQLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }finally{
      if(connection != null){
        //closing connection 
        try {
          connection.close();
        } catch (SQLException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      } // if condition
    }// finally
  }
}

Points to note here are-

  • Here connection is made to the “world” schema in the MySQL DB ( jdbc:mysql://localhost:3306/world) so program will list all the table names in the world schema.
  • Returned resultset has table description rows where each row has following columns -
Table Descrition Columns
Column NameTypeDescription
TABLE_CAT String table catalog (may be null)
TABLE_SCHEM String table schema (may be null)
TABLE_NAME String table name
TABLE_TYPE String table type. Typical types are "TABLE", "VIEW" etc.
REMARKS String explanatory comment on the table (may be null)
TYPE_CAT String the types catalog (may be null)
TYPE_SCHEM String the types schema (may be null)
TYPE_NAME String type name (may be null)
SELF_REFERENCING_COL_NAME String name of the designated "identifier" column of a typed table (may be null)
REF_GENERATION String specifies how values in SELF_REFERENCING_COL_NAME are created.

That’s why column index is 3 while getting result from ResultSet in the Java code as TABLE_NAME is at number 3.

That's all for this topic Java Program to Get All The Tables in a DB Schema. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Programs Page


Related Topics

  1. Connection Pooling Using C3P0 in Java
  2. Connection Pooling Using Apache DBCP in Java
  3. Java Program to Get All DB Schemas
  4. DataSource in Java-JDBC
  5. CallableStatement Interface in Java-JDBC

You may also like-

  1. Count Total Number of Times Each Character Appears in a String - Java Program
  2. Add Double Quotes to a String Java Program
  3. How to Run a Shell Script From Java Program
  4. Difference Between Two Dates in Java
  5. Interface Default Methods in Java
  6. Try-With-Resources in Java With Examples
  7. Java ThreadLocal Class With Examples
  8. Method Reference in Java

Friday, June 18, 2021

Format Date in Java Using SimpleDateFormat

If you want to create your own customized formats to format a date in Java, you can do that using the SimpleDateFormat class.

When you create a SimpleDateFormat object, you specify a pattern String. The contents of the pattern String determine the format of the date and time.

For example-
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");

Here the specified pattern is "MM/dd/yyyy" so the date will be formatted in that pattern.

Formatting date using SimpleDateFormat Java examples

In the example code several String patterns are used to create SimpleDateFormat object which are then used to format date. Comment along with the pattern shows how date is displayed using that pattern.

import java.text.SimpleDateFormat;
import java.util.Date;

public class FormatDate {

 public static void main(String[] args) {
  FormatDate fd = new FormatDate();
  
  // For date in format Wed, Jun 8, '16
  fd.getFormattedDate("EEE, MMM d, ''yy");

  // For date in format Wednesday, June 08, 2016
  fd.getFormattedDate("EEEE, MMMM dd, yyyy");

  // For date in format 05/08/2016
  fd.getFormattedDate("MM/dd/yyyy");

  // For date in format 08/05/2016
  fd.getFormattedDate("dd/MM/yyyy");

  // For date in format 2016-05-08 AD at 09:42:54 IST
  // with era designator (AD in this case) and 
  // timezone info (IST in this case)
  fd.getFormattedDate("yyyy-MM-dd G 'at' hh:mm:ss z");

  //For date in format 08/May/2016 AD 21:47:28:889 PM
  //with AM/PM marker, time in 24 Hr fmt, miliseconds
  // also included
  fd.getFormattedDate("dd/MMMMM/yyyy GGG HH:mm:ss:SSS a");

  // Only time like 21:52:14:096 PM
  // in 24 hr format, with mili seconds and AM/PM marker
  fd.getFormattedDate("HH:mm:ss:SSS a");

 }
 
 public void getFormattedDate(String pattern){
  Date today;
  String result;
  SimpleDateFormat formatter;
  // Creating the date format using the given pattern
  formatter = new SimpleDateFormat(pattern);
  // Getting the date instance
  today = new Date();
  // formatting the date
  result = formatter.format(today);
  System.out.println("Pattern: " + pattern + 
    " Formatted Date - " + result);
 }

}

Output

Pattern: EEE, MMM d, ''yy Formatted Date - Sun, May 8, '16
Pattern: EEEE, MMMM dd, yyyy Formatted Date - Sunday, May 08, 2016
Pattern: MM/dd/yyyy Formatted Date - 05/08/2016
Pattern: dd/MM/yyyy Formatted Date - 08/05/2016
Pattern: yyyy-MM-dd G 'at' hh:mm:ss z Formatted Date - 2016-05-08 AD at 10:13:46 IST
Pattern: dd/MMMMM/yyyy GGG HH:mm:ss:SSS a Formatted Date - 08/May/2016 AD 22:13:46:090 PM
Pattern: HH:mm:ss:SSS a Formatted Date - 22:13:46:092 PM

Symbols used for creating date patterns in Java

Symbol Meaning Presentation Example
G era designator Text AD
y year Number 2009
M month in year Text & Number July & 07
d day in month Number 10
h hour in am/pm (1-12) Number 12
H hour in day (0-23) Number 0
m minute in hour Number 30
s second in minute Number 55
S millisecond Number 978
E day in week Text Tuesday
D day in year Number 189
F day of week in month Number 2 (2nd Wed in July)
w week in year Number 27
W week in month Number 2
a am/pm marker Text PM
k hour in day (1-24) Number 24
K hour in am/pm (0-11) Number 0
z time zone Text Pacific Standard Time
' escape for text Delimiter (none)
' single quote Literal '

Date Format Pattern Syntax

The number of symbol letters you specify also determines the format.

As exp. symbol for which the presentation style is text if length is 1-3 then abbreviated form is used if length is >= 4 then full form is used. In the above code it can be seen when 'EEE' is given it shows SUN as the day of the week, when 'EEEE' is given then Sunday is displayed.

Same way for month for which presentation style is text/number if length is 1-2 then number form is used when length is 3 (or more) then text form is used.

Source: https://docs.oracle.com/javase/tutorial/i18n/format/simpleDateFormat.html

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

>>>Return to Java Programs Page


Related Topics

  1. How to Convert Date And Time Between Different Time-Zones in Java
  2. How to Display Time in AM-PM Format in Java
  3. Difference Between Two Dates in Java
  4. How to Find Last Modified Date of a File in Java
  5. How to Convert String to Date in Java

You may also like-

  1. How to Read File From The Last Line in Java
  2. How to Sort ArrayList of Custom Objects in Java
  3. How to Untar a File in Java
  4. Split a String Java Program
  5. Marker interface in Java
  6. Difference Between Checked And Unchecked Exceptions in Java
  7. Java ThreadLocal Class With Examples
  8. CopyOnWriteArrayList in Java With Examples

Thursday, June 17, 2021

Spring p-namespace For Shorter XML Configuration in Spring

While using Spring XML configuration for wiring beans you would have used <property> element several times for providing property values and/or providing reference for beans. If you are looking for any shorter alternative to nested <property> element you can use p-namespace in Spring.

The p-namespace enables you to use the bean element’s attributes, instead of nested <property/> elements.

As example–

If you have a XML configuration for bean employee with property officeAddress of type Address which refers to another bean address like this–

<bean id="employee" class="org.netjs.model.Employee">
    <property name="officeAddress" ref="address"/>
</bean>
You can use p-namespace in Spring to shorten it like this–
<bean id="employee" class="org.netjs.model.Employee" p:officeAddress-ref="address">
    <!-- <property name="officeAddress" ref="address"/> -->
</bean>

You can see here that instead of using nested <property> element you can use bean element’s attribute itself.

In this way of using p-namespace for injection of bean reference p:officeAddress-ref="address", p: denotes the use of p-namespace, officeAddress is the property name with in the employee class where value is injected, -ref indicates injection of bean reference.

Using p-namespace with literals

Same way p-namespace can be used for injecting literal values.

As example

If you have a XML configuration for bean employee which has a property empName then you can provide a literal value to empName property like this-

<bean id="employee" class="org.netjs.model.Employee">
    <property name="empName" value="Ram"/>
</bean>

Using p-namespace you can shorten it like this–

<bean id="employee" class="org.netjs.model.Employee" p:empName="Ram">
    <!-- <property name="empName" value="Ram"/> -->
</bean>

Spring p-namespace example

As we have already seen there are two classes Address and Employee where Address class bean is referred in Employee.

Address class

public class Address {
 private String number; 
 private String street; 
 private String city; 
 private String state; 
 private String pinCode; 
 public String getNumber() {
  return number;
 }
 public void setNumber(String number) {
  this.number = number;
 }
 public String getStreet() {
  return street;
 }
 public void setStreet(String street) {
  this.street = street;
 }
 public String getCity() {
  return city;
 }
 public void setCity(String city) {
  this.city = city;
 }
 public String getState() {
  return state;
 }
 public void setState(String state) {
  this.state = state;
 }
 public String getPinCode() {
  return pinCode;
 }
 
 public void setPinCode(String pinCode) {
  this.pinCode = pinCode;
 }
}

Employee class

public class Employee {
 private int empId;
 private String empName;
 private int age;
 private Address officeAddress;
 
 public Address getOfficeAddress() {
  return officeAddress;
 }
 public void setOfficeAddress(Address officeAddress) {
  this.officeAddress = officeAddress;
 }
 public int getEmpId() {
  return empId;
 }
 public void setEmpId(int empId) {
  this.empId = empId;
 }
 public String getEmpName() {
  return empName;
 }
 public void setEmpName(String empName) {
  this.empName = empName;
 }
 public int getAge() {
  return age;
 }
 public void setAge(int age) {
  this.age = age;
 }
}

XML Configuration

<?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:aop="http://www.springframework.org/schema/aop"
  xmlns:context="http://www.springframework.org/schema/context"
  xmlns:p="http://www.springframework.org/schema/p"
  xsi:schemaLocation="http://www.springframework.org/schema/beans 
  http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
  http://www.springframework.org/schema/context
  http://www.springframework.org/schema/context/spring-context.xsd">
   
  <bean id="address" class="org.netjs.model.Address" p:number="101" p:street="M I Road" 
    p:city="Jaipur" p:state="Rajasthan" p:pinCode="302001"> 
  </bean>
  <bean id="employee" class="org.netjs.model.Employee" p:empId="1001" p:age="25" 
    p:empName="Ram" p:officeAddress-ref="address">
    <!-- <property name="empName" value="Ram"/> -->
  </bean>   
</beans>

Here notice the inclusion of xmlns:p="http://www.springframework.org/schema/p in XML configuration for p-namespace.

Test Class

You can run this code using the following code-
public class App {
 public static void main(String[] args) {
  ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext
    ("appcontext.xml");
  Employee emp = (Employee)context.getBean("employee");  
  Address addr = emp.getOfficeAddress();
  System.out.println("Name " + emp.getEmpName());
  System.out.println("Age " + emp.getAge());
  System.out.println("city " + addr.getCity());
  context.close(); 
 }
}

Output

Name Ram
Age 25
city Jaipur

Points to remember

  1. The p-namespace is not as flexible as the standard XML format. For example, the format for declaring property references clashes with properties that end in Ref, whereas the standard XML format does not. If you want to reference bean named address and you also have the property named as address-ref then it will result in a clash if you use p-namespace.
  2. You can’t use p-namespace while wiring a collection.

That's all for this topic Spring p-namespace For Shorter XML Configuration in Spring. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Spring Tutorial Page


Related Topics

  1. Using c-namespace in Spring
  2. Spring Profiles With Examples
  3. registerShutdownHook() Method in Spring Framework
  4. How to Inject Prototype Scoped Bean into a Singleton Bean in Spring
  5. Lazy Initialization in Spring Using lazy-init And @Lazy Annotation

You may also like-

  1. Wiring Collections in Spring
  2. How to Read Properties File in Spring Framework
  3. Difference Between component-scan And annotation-config in Spring
  4. Configuring DataSource in Spring Framework
  5. How to Sort ArrayList of Custom Objects in Java
  6. How HashMap Works Internally in Java
  7. Callable and Future in Java With Examples
  8. Is String Thread Safe in Java

Tuesday, June 15, 2021

Package in Java

In this tutorial you'll learn how to create packages in Java and how to import them.


Benefits of using packages

A package in Java is a namespace that organizes a set of related classes and interfaces. Packages also help in preventing naming conflicts.

Conceptually you can think of packages as being similar to folders in OS. You can have files with similar names in different folders same way in different packages there can be Java classes with the same name thus preventing name collision as class is qualified with package name.

Packages in Java also provide visibility control mechanism. You can define classes and class members inside a package that are not visible to the classes in other packages.

So to summarize the advantages of package in Java-

  • Packages are used to organize set of related classes and interface which makes its easy to find a specific class, interface.
  • Packages provide visibility/access control mechanism. With default access a member is visible only within its own package. Protected modifier specifies that the member can only be accessed within its own package and by a subclass of its class in another package.
  • Packages prevent naming collision. Since class is qualified with package name so you can have class with same name in different packages, for example org.netjs.Test and org.netjs.examples.Test.

Types of packages

Packages in Java can be of two types-

  • Built-in packages- In Java there are many built-in packages where classes are grouped according to the functionality. As example- java.lang which provides classes that are fundamental to the design of the Java programming language, java.io which provided classes for system input and output, java.util which contains collections framework among other things.
  • User defined packages- Packages created by users to group their classes/interfaces according to the functionality.

Creating a package in Java

To create a package just include package command as a first statement in your Java source file.

General form of a package in Java is as follows-

package package_name;

Java package creation example

package testpackage;
public class Test{
 public static void main(String[] args) {
  Test t = new Test();
 }
}

In this example code first statement package testpackage; creates the package testpackage if it is not already created. If package is already there then the class Test will also become part of that package, here note that more than one file can belong to the same package.

If you are using some editor like Eclipse then you can create package using new package option with in a Java project.

Hierarchy of packages in Java

You can also have hierarchy of packages where a sub-package resides inside another package. In that case package names will be separated by a period (.).

package org.netjs.prog;
public class Test{
 public static void main(String[] args) {
  Test t = new Test();
 }
}

In this case Test.java will be stored under the folder structure \org\netjs\prog in windows environment.

Importing packages in Java

Packages are a good way to group set of related classes and interfaces, but you do need to use classes/interfaces from one package in another package. If you want to access classes with in the package then you need to use the fully qualified name i.e. class name along with package name. That will mean a lot of typing just to access a class as example - pkg1.pkg2.pkg3.ClassName

To avoid that Java has import statement which can make visible a specific class or a whole package. In Java source file import statement must be written directly after package statement.

To sum it up there are three options when you want to use classes/interfaces from another package -

  • Import the whole package
  • Import specific classes
  • Use the fully qualified name

Import the whole package

As example if you want to use List interface, which resides in java.util, in your class then you can import the whole util package.

import java.util.*;

In that case whole java.util package is imported which apart from List interface contains many other classes and interfaces.

Import specific classes

If you have a statement like this in your source file

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

Then you need to have two import statements for importing classes from the package.

import java.util.ArrayList;
import java.util.List;

Use the fully qualified name

You can also use the fully qualified name of the class which includes the package name along with the class. In that case the same statement will look like-

java.util.List<String> ls = new java.util.ArrayList<String>();

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

>>>Return to Java Basics Tutorial Page


Related Topics

  1. Class 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. Difference Between Abstract Class And Interface in Java
  2. final Keyword in Java With Examples
  3. Difference Between equals() Method And equality Operator == in Java
  4. How HashMap Works Internally in Java
  5. Interface Default Methods in Java
  6. Callable and Future in Java With Examples
  7. Count Number of Words in a String Java Program
  8. Print Odd-Even Numbers Using Threads And wait-notify Java Program

Sunday, June 13, 2021

Convert int to String in Java

In the post converting String to int we have already seen ways to convert string to int in Java, this post is about doing just the reverse; convert int to string in Java.

Concatenating with an empty String

Easiest way to convert an int to a string in Java is to concatenate int with an empty string. That will give you a string value, conversion is handled for you.

public class IntToString {

 public static void main(String[] args) {
  int num = 7;
  String value = "" + num;
  System.out.println("Value is " + value);
 }
}

Output

Value is 7

Convert int to string in Java using valueOf() method

String class has valueOf() method which is overloaded and those variants take int, float, double, long data types as parameters. You can use valueOf(int i) method to convert int to String by passing int value as an argument to the method which returns the string representation of the int argument.

public class IntToString {

 public static void main(String[] args) {
  int num = 7;
  String value = String.valueOf(num);
  System.out.println("Value is " + value);
 }
}

Output

Value is 7

Conversion of int to String using toString() method

Each of the Number subclasses (Integer, Float, Double etc.) includes a class method, toString(), that will convert its primitive type to a string. You can use use Integer.toString(int i) method of the Integer wrapper class to convert int to String in Java. The method returns a String object representing the passed integer.

public class IntToString {

 public static void main(String[] args) {
  int num = 7;
  String value = Integer.toString(num);
  System.out.println("Value is " + value);
 }
}

Output

Value is 7

That's all for this topic Convert int to String 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 float to int in Java
  2. Arrange Non-Negative Integers to Form Largest Number - Java Program
  3. Find All Permutations of a Given String Java Program
  4. Java Program to Find The Longest Palindrome in a Given String
  5. Java String Interview Questions And Answers

You may also like-

  1. How to Find Common Elements Between Two Arrays Java Program
  2. How to Display Time in AM-PM Format in Java
  3. How to Count Lines in a File in Java
  4. String Vs StringBuffer Vs StringBuilder in Java
  5. Ternary Operator in Java With Examples
  6. How HashSet Works Internally in Java
  7. ConcurrentHashMap in Java With Examples
  8. Deadlock in Java Multi-Threading

Saturday, June 12, 2021

Zipping Files And Folders in Java

In this post we'll see how to zip files in Java and also how to zip a directory in Java where files and sub-directories are compressed recursively.

In Java, java.util.zip package provides classes for data compression and decompression. For compressing data to a ZIP file ZipOutputStream class can be used. The ZipOutputStream writes data to an output stream in zip format.


Steps to zip a file in Java

  • First you need to create a ZipOutputStream object, to which you pass the output stream of the file you wish to use as a zip file.
  • Then you also need to create an InputStream for reading the source file.
  • Create a ZipEntry for file that is read.
    ZipEntry entry = new ZipEntry(FILENAME)
    Put the zip entry object using the putNextEntry method of ZipOutputStream
  • That's it now you have a connection between your InputStream and OutputStream. Now read data from the source file and write it to the ZIP file.
  • Finally close the streams.

Java Program to zip a single file

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipFileDemo {
  static final int BUFFER = 1024;

  public static void main(String[] args) {
   zipFile();
  }
  // Method to zip file
  private static void zipFile(){
    ZipOutputStream zos = null;
    BufferedInputStream bis = null;
    try{
      // source file
      String fileName = "G:\\abc.txt";
      File file = new File(fileName);
      FileInputStream fis = new FileInputStream(file);
      bis = new BufferedInputStream(fis, BUFFER);
          
      // Creating ZipOutputStream
      FileOutputStream fos = new FileOutputStream("G:\\abc.zip");
      zos = new ZipOutputStream(fos);                  
          
      // ZipEntry --- Here file name can be created using the source file
      ZipEntry ze = new ZipEntry(file.getName());
      // Putting zipentry in zipoutputstream
      zos.putNextEntry(ze);
      byte data[] = new byte[BUFFER];
      int count;
      while((count = bis.read(data, 0, BUFFER)) != -1) {
        zos.write(data, 0, count);
      }
    }catch(IOException ioExp){
      System.out.println("Error while zipping " + ioExp.getMessage());
    }finally{
      if(zos != null){
        try {
          zos.close();
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
      if(bis != null){
        try {
          bis.close();
        } catch (IOException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }
      }
    }
  }
}
 

Java Program to zip multiple files

In this Java example multiple files are zipped in Java using ZipOutputStream. Each source file is added as a ZipEntry to the ZipOutputStream.

public class ZipFileDemo {
  public static void main(String[] args) {
    try {
      //Source files
      String file1 = "G:/abc.txt";
      String file2 = "G:/Test/abn.txt";
      //Zipped file
      String zipFilename = "G:/final.zip";
      File zipFile = new File(zipFilename);
      FileOutputStream fos  = new FileOutputStream(zipFile);            
      ZipOutputStream zos = new ZipOutputStream(fos);
          
      zipFile(file1, zos);
      zipFile(file2, zos);
      zos.close();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
    
  // Method to zip file
  private static void zipFile(String fileName, ZipOutputStream zos) throws IOException{
    final int BUFFER = 1024;
    BufferedInputStream bis = null;
    try{
      File file = new File(fileName);
      FileInputStream fis = new FileInputStream(file);
      bis = new BufferedInputStream(fis, BUFFER);          

      // ZipEntry --- Here file name can be created using the source file
      ZipEntry zipEntry = new ZipEntry(file.getName());        
      zos.putNextEntry(zipEntry);
      byte data[] = new byte[BUFFER];
      int count;
      while((count = bis.read(data, 0, BUFFER)) != -1) {
        zos.write(data, 0, count);
      }  
      // close entry every time
      zos.closeEntry();
    } finally{
      try {
        bis.close();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }  
    }
  }
}

Zipping Directory recursively in Java

If you have a folder structure as given below and you want to zip all the files in the parent folder and its sub folders recursively, then you need to go through the list of files and folders and compress them.

zipping files in Java

For zipping directory in Java two approaches are given here.

  1. You can use Files.walkFileTree() method (Java 7 onward) which recursively visit all the files in a file tree.
  2. You can read files in the folder with in the code and add them to a list and then compress the files with in that list.

Zipping Directory recursively in Java Using Files.walkFileTree()

If you are using Java 7 or higher then you can use Path and Files.walkFileTree() method to recursively zip the files. Using Files.walkFileTree() method makes the code shorter and leaves most of the work to API.

You need to implement FileVisitor interface which is one of the argument of the walkFileTree() method, implementation of two of the methods of FileVisitor is required-

preVisitDirectory- For directories you just need to make entry of the directory path.
visitFile- Zip each visited file.

Here try-with-resources in Java 7 is also used for managing resources automatically.

import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipFolderSeven {
  // Source folder which has to be zipped
  static final String FOLDER = "G:\\files";
  public static void main(String[] args) {
    ZipFolderSeven zs = new ZipFolderSeven();
    zs.zippingInSeven();
  }
  private void zippingInSeven(){
    // try with resources - creating outputstream and ZipOutputSttream
    try (FileOutputStream fos = new FileOutputStream(FOLDER.concat(".zip"));
        ZipOutputStream zos = new ZipOutputStream(fos)) {            
      Path sourcePath = Paths.get(FOLDER);
      // using WalkFileTree to traverse directory
      Files.walkFileTree(sourcePath, new SimpleFileVisitor<Path>(){
        @Override
        public FileVisitResult preVisitDirectory(final Path dir, final BasicFileAttributes attrs) throws IOException {
          // it starts with the source folder so skipping that 
          if(!sourcePath.equals(dir)){
            //System.out.println("DIR   " + dir);
            zos.putNextEntry(new ZipEntry(sourcePath.relativize(dir).toString() + "/"));            
            zos.closeEntry();    
          }
          return FileVisitResult.CONTINUE;
        }
        @Override
        public FileVisitResult visitFile(final Path file, final BasicFileAttributes attrs) throws IOException {
          zos.putNextEntry(new ZipEntry(sourcePath.relativize(file).toString()));
          Files.copy(file, zos);
          zos.closeEntry();
          return FileVisitResult.CONTINUE;
        }
      });
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}

Java code to zip files recursively using list() method

Here is the Java code that goes through the folder structure and zips all files and subfolders recursively. It will even take care of the empty folders in the source folder. In this example list() method of the File class is used.

  • list()- Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname.
Get the list of files and directories with in the parent directory using list() method and then iterate it, for each sub-directory keep calling list() method recursively to compress files in sub-directories.

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipFolderDemo {

  static final int BUFFER = 1024;
  // Source folder which has to be zipped
  static final String FOLDER = "G:\\files";
  List<File> fileList = new ArrayList<File>();
  public static void main(String[] args) {    
    ZipFolderDemo zf = new ZipFolderDemo();
    // get list of files
    List<File> fileList = zf.getFileList(new File(FOLDER));
    //go through the list of files and zip them 
    zf.zipFiles(fileList);    
  }
    
  private void zipFiles(List<File> fileList){
    try{
      // Creating ZipOutputStream - Using input name to create output name
      FileOutputStream fos = new FileOutputStream(FOLDER.concat(".zip"));
      ZipOutputStream zos = new ZipOutputStream(fos);
      // looping through all the files
      for(File file : fileList){
        // To handle empty directory
        if(file.isDirectory()){
          // ZipEntry --- Here file name can be created using the source file
          ZipEntry ze = new ZipEntry(getFileName(file.toString())+"/");
          // Putting zipentry in zipoutputstream
          zos.putNextEntry(ze);
          zos.closeEntry();
        }else{
          FileInputStream fis = new FileInputStream(file);
          BufferedInputStream bis = new BufferedInputStream(fis, BUFFER);
          // ZipEntry --- Here file name can be created using the source file
          ZipEntry ze = new ZipEntry(getFileName(file.toString()));
          // Putting zipentry in zipoutputstream
          zos.putNextEntry(ze);
          byte data[] = new byte[BUFFER];
          int count;
          while((count = bis.read(data, 0, BUFFER)) != -1) {
              zos.write(data, 0, count);
          }
          bis.close();
          zos.closeEntry();
        }               
      }                
      zos.close();    
    }catch(IOException ioExp){
      System.out.println("Error while zipping " + ioExp.getMessage());
      ioExp.printStackTrace();
    }
  }
    
  /**
   * This method will give the list of the files 
   * in folder and subfolders
   * @param source
   * @return
   */
  private List<File> getFileList(File source){      
    if(source.isFile()){
      fileList.add(source);
    }else if(source.isDirectory()){
      String[] subList = source.list();
      // This condition checks for empty directory
      if(subList.length == 0){
        //System.out.println("path -- " + source.getAbsolutePath());
        fileList.add(new File(source.getAbsolutePath()));
      }
      for(String child : subList){
        getFileList(new File(source, child));
      }
    }
    return fileList;
  }
    
  /**
   * 
   * @param filePath
   * @return
   */
  private String getFileName(String filePath){
    String name = filePath.substring(FOLDER.length() + 1, filePath.length());
    //System.out.println(" name " + name);
    return name;      
  }
}

That's all for this topic Zipping Files And Folders 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. Unzip File in Java
  2. Creating Tar File And GZipping Multiple Files in Java
  3. Reading File in Java Using BufferedReader
  4. How to Read File From The Last Line in Java
  5. Reading File in Java Using Scanner

You may also like-

  1. Java Program to Convert a File to Byte Array
  2. Format Date in Java Using SimpleDateFormat
  3. How to Display Pyramid Patterns in Java - Part1
  4. equals() And hashCode() Methods in Java
  5. final Keyword in Java With Examples
  6. Deadlock in Java Multi-Threading
  7. Lambda Expressions in Java 8
  8. Java ArrayBlockingQueue With Examples