Convert Byte Array to String

  • To convert byte array to string we have a constructor in String class which is taking byte array as an argument.
  • So just we need to pass byte array object to string as argument while creating String class object.

  1.  package com.instanceofjavaforus;
  2.  
  3. public class ByteArrayToString {
  4.    /*
  5.    * This method converts a byte array to a String object.
  6.      */
  7.  
  8.     public static void convertByteArrayToString() {
  9.  
  10.         byte[] byteArray = new byte[] {78,73, 67,69};
  11.         String value = new String(byteArray);
  12.        System.out.println(value);
  13.  
  14.     }
  15.  
  16.     public static void main(String[] args) {
  17.         ByteArrayToString.convertByteArrayToString();
  18.     }
  19.  
  20. }

Output:


  1. NICE

 

Convert String to Byte Array:

  1.  package com.instanceofjava;
  2. public class StringTOByteArray{
  3.    /*
  4.    * This example shows how to convert a String object to byte array.
  5.      */

  6.     public static void main(String[] args) {
  7.       
  8.     String data = "Instance of java";
  9.  
  10.     byte[] byteData = data.getBytes();
  11.  
  12.     System.out.println(byteData);
  13.  
  14.     }
  15.  
  16. }



Output:


  1. [B@3b26456a

Convert values of a Map to a List

Java How To Convert Map Values To List In Java Some Different Ways Below are some common methods for doing so:

1. How to use values() with ArrayList

You can convert the values of a Map to a List in Java using various approaches. 

below are a few common methods:

1. Using ArrayList andvalues()

import java.util.*;

public class MapToListExample {
    public static void main(String[] args) {
        Map<Integer, String> map = new HashMap<>();
        map.put(1, "Apple");
        map.put(2, "Banana");
        map.put(3, "Cherry");

        // Convert values to List
        List<String> list = new ArrayList<>(map.values());

        System.out.println(list);  // Output: [Apple, Banana, Cherry]
    }
}

2. Using Java 8 Stream API

import java.util.*;
import java.util.stream.Collectors;

public class MapToListExample {
    public static void main(String[] args) {
        Map<Integer, String> map = Map.of(1, "Apple", 2, "Banana", 3, "Cherry");

        // Convert values to List using Stream
        List<String> list = map.values().stream().collect(Collectors.toList());

        System.out.println(list);  // Output: [Apple, Banana, Cherry]
    }
}

3. Using forEach Loop

import java.util.*;

public class MapToListExample {
    public static void main(String[] args) {
        Map<Integer, String> map = new HashMap<>();
        map.put(1, "Apple");
        map.put(2, "Banana");
        map.put(3, "Cherry");

        List<String> list = new ArrayList<>();
        map.values().forEach(list::add);

        System.out.println(list);  // Output: [Apple, Banana, Cherry]
    }
}

💡 Choose the method based on your Java version:

  • Use ArrayList<>(map.values()) for simple cases.
  • Use Stream API (map.values().stream().collect(Collectors.toList())) in Java 8+ for a functional approach.
  • Use a forEach loop if modifying the list during iteration.


  1. package com.instanceofjavaforus;

  2. import java.util.ArrayList;
  3. import java.util.HashMap;
  4. import java.util.List;
  5. import java.util.Map;
  6.  
  7. public class MapValueToList {
  8.  
  9.  Map<Integer, String> map;
  10.  
  11.  public MapKeyToList(Map<Integer, String> map) {
  12.       this.map = map;
  13.  }
  14.  public List<String> convertValuesToList() {
  15.     return new ArrayList(map.values());
  16.  }
  17.  
  18.  public static void main(String[] args) {           
  19.  Map<Integer, String> map = new HashMap<>();
  20.  
  21.     map.put(1, "one");
  22.     map.put(2, "two");
  23.     map.put(3, "three");
  24.     map.put(4, "Four");
  25.     map.put(5, "Five");
  26.     map.put(6, "Six");
  27.     map.put(7, "Seven");
  28.     map.put(8, "Eight");
  29.     map.put(9, "Nine");
  30.     map.put(10, "Ten");
  31.  
  32.      MapValueToList  conv = new MapValueToList (map);
  33.      List<String> keysList = conv.convertValuesToList();
  34.      System.out.println("Values:");
  35.     for (String val : keysList) {
  36.        System.out.println(val);
  37. }
  38.  
  39.  }
  40. }
  41. OutPut:
  42. Values:
  43. one
  44. two
  45. three
  46. Four
  47. Five
  48. Six
  49. Seven
  50. Eight
  51. Nine
  52. Ten

     


Map to list in java example

  1. package com.instanceofjavaforus;
  2. import java.util.ArrayList;
  3. import java.util.HashMap;
  4. import java.util.List;
  5. import java.util.Map;
  6.  
  7. public class MapKeyToList {
  8.  
  9.  Map<Integer, String> map;
  10.  
  11.  public MapKeyToList(Map<Integer, String> map) {
  12.  this.map = map;
  13. }
  14.  
  15.  public List<Integer> convertKeysToList() {
  16.    return new ArrayList(map.keySet());   
  17. }   

  18. public static void main(String[] args) {
  19.  
  20.  Map<Integer, String> map = new HashMap<>();
  21.     map.put(1, "one");
  22.     map.put(2, "two");
  23.     map.put(3, "three");
  24.     map.put(4, "Four");
  25.     map.put(5, "Five");
  26.     map.put(6, "Six");
  27.     map.put(7, "Seven");
  28.     map.put(9, "Nine");
  29.     map.put(10, "Ten");
  30.  
  31.     MapKeyToList conv = new MapKeyToList(map);
  32.     List<Integer> keysList = conv.convertKeysToList();
  33.  
  34.      System.out.println("Keys:");
  35.  
  36.      for (Integer key : keysList) {
  37.         System.out.println(key);
  38.    }
  39.  
  40.  }
  41. }
  42. OutPut:
  43. Keys:
  44. 1
  45. 2
  46. 3
  47. 4
  48. 5
  49. 6
  50. 7
  51. 8
  52. 9
  53. 10

Marker Interfaces in java

Marker interface:

  • The interfaces using which we explicitly mention or mark certain properties to the object are known as marker interface.
  • An interface that is used to check / mark / tag the given object is of a specific type to perform a special operations on that object.
  • Marker interfaces will not have methods , they are empty interfaces.

 Need of marker interface: 

  • It i used to check , whether we can perform some special operations on the passed object
  • For ex: using serializable  interface we can explicitly mention that object of a class is transferable. else it can not.
  • If a class is deriving form java.lang.Cloneable interface then that object can be cloned, else it can not
  • In side those particular methods , that method developer will check that the passed object is of type the given interface or not by using "instanceof" operator.


Predefined marker interfaces:

  1. java.lang.Cloneable
  2. java.io.Serializable
  3. java.util.RandomAccess
  4. java.util.Eventlistener
  5. java.rmi.Remote
  6. java.servlet.SingleThreadModel




Object class in java

Java.lang.Object class:

  • Object is the root or super class of the class hierarchy. Which is present in java.lang package.
  • All predefined classes and user defined classes are sub classed from Object class

Why object class is super class for all java classes:

  1. Re-usability:
    • Every object has 11 common properties.
    • These properties must be implemented by every class developer.
    • So to reduce burden on developer SUN developed a class called Object by implementing all these 11 properties with 11 methods.
    • All these methods have generic logic common for all sub classes. if this logic is not satisfying subclass requirement then subclass can override it.
     
  2. Run time polymorphism:
    • To achieve run time polymorphism so that we can write single method to receive and send any type of class object as argument and as return type.

Why this class name is chosen as object?

  • As per coding standards , class name must convey the operations doing by that class.
  • So this class name is chosen as Object as it has all operations related to object.
  • These operations are chosen based on real world object's behavior.

Common functionalities of every class object: 

  1. Comparing two objects: 

    • public boolean equals(Object obj)
  2. Retrieving hashcode: 

    • public int hashcode()
  3. Retrieving the run time class object reference:

    • public final Class getClass()
  4. Retrieving object information in String format:

    • public String toString()
  5. Cloning object: 

    • protected Object clone()
                      throws CloneNotSupportedException
  6. Object clean-up code/ resources releasing code: 

    •  protected void finalize()
                       throws Throwable
  7. To wait current thread until another thread invokes the notify():

    • public final void wait()
                      throws InterruptedException
  8. To wait current thread until another thread invokes the notify() specified amount of time:

    • public final void wait(long timeout)
                      throws InterruptedException
  9.  To wait current thread until another thread invokes the notify() specified amount of time

    • public final void wait(long timeout,int nanos)
                      throws InterruptedException
  10. Notify about object lock availability to waiting thread: 

    • public final void notify()
  11. Notify about object lock availability to waiting threads: 

    • public final void notifyAll() 
  • All above operations are implemented with generic logic that is common for all objects, so that developer can avoid implementing these common operations in every class.
  • Also Oracle ensures that all these operations are overridden by developers with the same method prototype. This feature will provide run time polymorphism.

What are the methods we can override in sub class from Object class:

  1. equals()
  2. hashCode()
  3. toString()
  4. clone()
  5. finalize()

Example program on toString() method :

  1. package com.instanceofjavaforus;
  2.  
  3. public class ToStringDemo {
  4.     int id;
  5.    String name;
  6.  
  7. public String toString(){
  8.  return id+" "+name;
  9.  }
  10.  
  11.  public int getId() {
  12.    return id;
  13.  }
  14.  
  15. public void setId(int id) {
  16.   this.id = id;
  17.  }
  18.  
  19.  public String getName() {
  20.       return name;
  21.  }
  22.  
  23.  public void setName(String name) {
  24.     this.name = name;
  25.   }
  26.  
  27.   public static void main(String[] args) {
  28.  
  29.    ToStringDemo obj = new ToStringDemo();
  30.      obj.setId(1);
  31.      obj.setName("abc");
  32.     System.out.println(obj);
  33.  
  34.  }
  35. }

  36. OutPut:
  37. 1 abc


Example program on clone() method:

  1.  
  2. package com.instanceofjava;
  3.  
  4. public class CloneDemo  implements Cloneable  {
  5.   int a=0;
  6.    String name="";
  7.   CloneDemo (int a,String name){
  8.  this.a=a;
  9.  this.name=name;
  10.  }
  11.   public CloneDemo clone() throws CloneNotSupportedException{
  12.  return (CloneDemo ) super.clone();
  13. }
  14.  public static void main(String[] args) {
  15.  CloneDemo e=new CloneDemo (2,"abc");
  16.  System.out.println(e.name);
  17.     try {
  18.  CloneDemo b=e.clone();
  19.  System.out.println(b.name);
  20. } catch (CloneNotSupportedException e1) {
  21.  // TODO Auto-generated catch block
  22.   e1.printStackTrace();
  23. }
  24. }
  25.  
  26. }
  27.  
  28. OutPut:
  29. abc
  30. abc

Remove duplicates from an array java

Removing duplicate elements form an array using collections:

  1. package com.instanceofjavaTutorial;
  2.  
  3. import java.util.Arrays;
  4. import java.util.HashSet;
  5. import java.util.List;
  6. import java.util.Set;
  7.  
  8. public class RemoveDupArray {
  9.  
  10.   public static void main(String[] args) {
  11.  
  12.   // A string array with duplicate values
  13.    String[] data = { "E", "C", "B", "E", "A", "B", "E", "D", "B", "A" };
  14.  
  15. System.out.println("Original array         : " + Arrays.toString(data));
  16.  
  17.  List<String> list = Arrays.asList(data);
  18.  Set<String> set = new HashSet<String>(list);
  19.  
  20.   System.out.print("After removing duplicates: ");
  21.   String[] resarray= new String[set.size()];
  22.    set.toArray(resarray);
  23.  
  24.  for (String ele: resarray) {
  25.  
  26.  System.out.print(ele + ", ");
  27.  
  28.  }
  29.  
  30. }
  31.  
  32. }



  1. OutPut:
  2. Original array         : [E, C, B, E, A, B, E, D, B, A]
  3. After removing duplicates: D, E, A, B, C




You Might Like:

1. Java Interview Programs On Core Java

2. Java Interview Programs On Collections 

3. What is The Output Of Following Programs Java Interview:

4. Java Concept and Example Program

VarArgs in java

  • The full form of var-arg is variable length arguments.
  • Till JDK 1.4 we must define overloaded methods to pass different list of arguments .
  • But using this feature we can define method to pass ZERO to 'n'  number of arguments.
  • Syntax: After data type we must place three dots.


  1.          void method(int... i){
  2.          }
  • Internally Var-arg is a single dimensional array. So we can also pass single dimensional array as argument.
  1. package instanceofjavaforus;
  2. public class VDemo{ 
  3.  void print(int... args){
  4. for(int i=0;i<args.length;i++){
  5. System.out.println(args[i]);
  6. }
  7. System.out.println();
  8. }
  9. public static void main(String args[]){
  10.  Vdemo obj= new Vdemo();
  11. int x={1,2};
  12. obj.print(x);// works fine
  13. obj.print(1,2,3,4);// works fine
  14. obj.print();// works fine
  15. //int... var=new int[5]; compile time error: not a valid statement
  16.  
  17. Output:
  18. 1
  19. 2

  20. 1
  21. 2
  22. 3
  23. 4

It must be last argument:

  1. package instanceofjavaforus;
  2. public class VDemo{ 
  3. void print(int x){
  4.  System.out.println("int x");
  5. }
  6.  
  7. void print(int x, int y){
  8.  System.out.println("int x, int y");
  9.  void print(int x, int y,int... args){
  10. System.out.println("int x, int y,int... args");
  11. }
  12. void print(int... args){
  13. System.out.println("int x, int y");
  14. }
  15.  public static void main(String args[]){
  16.  Vdemo obj= new Vdemo();
  17. int x={1,2};
  18. obj.print(1);
  19. obj.print(x);// works fine
  20. obj.print(1,2,3,4);// works fine
  21. obj.print();// works fine
  22. //int... var=new int[5]; compile time error: not a valid statement

  23. Output:
  24. int x
  25. int x, int y
  26. int x, int y,int... args
  • if we declared  placed any type after var-arg in the arguments list of a method then it throws a compile time error.

  1. void print(int x, int y, int...args, int z){// compile time error
  2. // throws Compile time error:The variable argument type int of the method print must be the
  3.  // last parameter
  4.  System.out.println("int x, int y");
  5.  void print(int x, int y,int... args){  // valid
  6. System.out.println("int x, int y,int... args");
  7. }
Overloading method with normal and varargs types :

  1. package instanceofjavaforus;
  2. public class VDemo{ 
  3.  void print(int... args){
  4. System.out.println("var arg method");
  5. }
  6. void print(int args){
  7. System.out.println("normal method");
  8. }
  9.  
  10. public static void main(String args[]){
  11.  Vdemo obj= new Vdemo();
  12. obj.print(1);// works fine
  13.  }
  14. Output:
  15. normal method

Overloading method with normal and varargs types in super and sub classes:

var args Program 1:

  1. package instanceofjavaforus;
  2. public class VDemo{ 
  3.  void print(int... args){
  4. System.out.println("super class method");
  5. }

  1. package instanceofjavaforus;
  2. public class Test extends VDemo{ 
  3.  void print(int args){
  4. System.out.println("sub class method");
  5. }
  6. public static void main(String args[]){
  7.  VDemo vobj= new VDemo();
  8. vobj.print(10);
  9. Test tobj= new Test();
  10. tobj.print(10);
  11. }
  12. }
  13. OutPut:
  14. Super class method
  15. Sub class method

var args Program 2:

  1. package instanceofjavaforus;
  2. public class VDemo{ 
  3.  void print(int args){
  4. System.out.println("super class method");
  5. }
  6. }



  1. package instanceofjavaforus;
  2.  
  3. public class Test extends VDemo{ 
  4.  
  5.  void print(int... args){
  6. System.out.println("sub class method");
  7. }
  8. public static void main(String args[]){
  9.  
  10.  VDemo vobj= new VDemo();
  11. vobj.print(10);
  12. Test tobj= new Test();
  13. tobj.print(10);
  14.  
  15. }
  16. }
  17. OutPut:
  18. Super class method
  19. Super class method
Select Menu