Stream Method Example:
Top Most Interview Question Of Java Technology
Sunday, 26 January 2025
Wednesday, 1 September 2021
StringJoiner class in java (JDK 1.8 Version Concept)
Java added a new final class StringJoiner in java.util package. It is used to construct a sequence of characters separated by a delimiter. Now, you can create string by passing delimiters like comma(,), hyphen(-) etc. You can also pass prefix and suffix to the char sequence.
Constructors :
StringJoiner(CharSequence delimiter) : Constructs a StringJoiner with no characters in it, with no prefix or suffix, and a copy of the supplied delimiter.
Syntax :
public StringJoiner(CharSequence delimiter)
Parameters :
delimiter - the sequence of characters to be used between
each element added to the StringJoiner value
Throws:
NullPointerException - if delimiter is null
Syntax :
public StringJoiner(CharSequence delimiter,
CharSequence prefix, CharSequence suffix)
Parameters :
delimiter - the sequence of characters to be used between
each element added to the StringJoiner value
prefix - the sequence of characters to be used at the beginning
suffix - the sequence of characters to be used at the end
Throws:
NullPointerException - if prefix, delimiter, or suffix is null
Methods : There are 5 methods in StringJoiner class.
String toString() : This method returns String object of this StringJoiner.
Syntax :
public String toString()
Parameters : NA
Returns :the string representation of this StringJoiner
Overrides :
toString in class Object
StringJoiner add(CharSequence newElement) : This method adds a copy of the given CharSequence value as the next element of the StringJoiner value. If newElement is null, then “null” is added.
Syntax :
public StringJoiner add(CharSequence newElement)
Parameters :
newElement - The element to add
Returns :
a reference to this StringJoiner
StringJoiner merge(StringJoiner other) : This method adds the contents of the given StringJoiner without prefix and suffix as the next element if it is non-empty. If the given StringJoiner is empty, the call has no effect.
If the other StringJoiner is using a different delimiter, then elements from the other StringJoiner are concatenated with that delimiter and the result is appended to this StringJoiner as a single element.
Syntax :
public StringJoiner merge(StringJoiner other)
Parameters :
other - The StringJoiner whose contents should be merged
into this one
Returns :
This StringJoiner
Throws :
NullPointerException - if the other StringJoiner is null
int length() : This method returns the length of the String representation of this StringJoiner.
Syntax :
public int length()
Parameters :
NA
Returns :
This StringJoiner
StringJoiner setEmptyValue(CharSequence emptyValue) : This method sets string to be used when determining the string representation of this StringJoiner and no elements have been added yet, that is, when it is empty.
Syntax :
public StringJoiner setEmptyValue(CharSequence emptyValue)
Parameters :
emptyValue - the characters to return as the value
of an empty StringJoiner
Returns :
this StringJoiner itself so the calls may be chained
Throws:
NullPointerException - when the emptyValue parameter is null
//Wap to demonstrate the concept of StringJoiner Class in java 8 ?
package java8concept;
import java.util.StringJoiner;
public class StringJoinerDemo {
public static void main(String[] args) {
StringJoiner sj = new StringJoiner(",");
//StringJoiner sj = new StringJoiner("_");
StringJoiner sjnew = new StringJoiner(",", "[", "]"); // passing comma(,) and square-brackets as delimiter
sj.add("Java");
sj.add("Technology");
sj.add("Govind");
sj.add("Sir");
System.out.println(sj);
sjnew.add("Java");
sjnew.add("Technology");
sjnew.add("Govind");
sjnew.add("Sir");
System.out.println(sjnew);
}
}
o/p:-----------
Java,Technology,Govind,Sir
[Java,Technology,Govind,Sir]
========================================================================
Wap to merge two StringJoiner object.
package java8concept;
import java.util.StringJoiner;
public class StringJoinerMergedemo {
public static void main(String[] args) {
StringJoiner sj = new StringJoiner(",", "[", "]");
sj.add("Govind");
sj.add("Sir");
StringJoiner sjnew = new StringJoiner(":", "[", "]");
sjnew.add("Java");
sjnew.add("Technology");
StringJoiner merge= sj.merge(sjnew);
System.out.println(merge);
}
}
o/p--------------
[Govind,Sir,Java:Technology]
============================================================================
//wap to demonstrate the method of StringJoiner class?
package java8concept;
import java.util.StringJoiner;
public class StringJoinerMethodDemo {
public static void main(String[] args) {
StringJoiner sj=new StringJoiner(",");
System.out.println(sj);
sj.setEmptyValue("It Is empty");
System.out.println(sj);
sj.add("Java");
sj.add("Technology");
System.out.println(sj);
// Returns length of StringJoiner
int length = sj.length();
System.out.println(length);
// Returns StringJoiner as String type
String stringdata = sj.toString();
System.out.println(stringdata);
// Now, we can apply String methods on it
char chardata = stringdata.charAt(3);
System.out.println(chardata);
sj.add("Govind Sir");
System.out.println(sj);
int newleggth = sj.length();
System.out.println(newleggth);
}
}
o/p:----------------
Java,Technology
15
Java,Technology
a
Java,Technology,Govind Sir
26
Thursday, 18 April 2019
We can use this method to check equivalence of two objects.
If our class doesn't contain .equals() method then object class .equals() method will be executed which is always meant for reference comparison[address comparison]. i.e., if two references pointing to the same object then only .equals( ) method returns true .
class StudentDemo
{
String name;
int rollno;
StudentDemo(String name,int rollno)
{
this.name=name;
this.rollno=rollno;
}
public static void main(String[] args){
StudentDemo s1=new StudentDemo("govind",101);
StudentDemo s2=new StudentDemo("ballabh",102);
StudentDemo s3=new StudentDemo("govind",101);
StudentDemo s4=s1;
System.out.println(s1.equals(s2));
System.out.println(s1.equals(s3));
System.out.println(s1.equals(s4));
}}
Output:
False
False
True
In the above program Object class .equals() method got executed which is always meant for reference comparison that is if two references pointing to the same object then only .equals(() method returns true.
In object class .equals() method is implemented as follows which is meant for reference comparison.
public boolean equals(Object obj) {
return (this == obj);
}
Based on our programming requirement we can override .equals() method for content comparison purpose.
When ever we are overriding .equals() method we have to consider the following things :
Meaning of content comparison i.e., whether we have to check the names are equal (or) roll numbers (or) both are equal.
If we are passing different type of objects (heterogeneous object) our .equals() method should return false but not ClassCastException i.e., we have to handle ClassCastException to return false.
If we are passing null argument our .equals() method should return false but not NullPointerException i.e., we have to handle NullPointerException to return false.
The following is the proper way of overriding .equals() method for content comparison in StudentTest class.
class StudentTest
{
String name;
int rollno;
StudentTest(String name,int rollno)
{
this.name=name;
this.rollno=rollno;
}
public boolean equals(Object obj)
{
try
{
String name1=this.name;
int rollno1=this.rollno;
StudentTest s2=(StudentTest)obj;
String name2=s2.name;
int rollno2=s2.rollno;
if(name1.equals(name2) && rollno1==rollno2)
{
return true;
}
else return false;
}
catch(ClassCastException e)
{
return false;
}
catch(NullPointerException e)
{
return false;
}
}
public static void main(String[] args){
StudentTest s1=new StudentTest("govind",101);
StudentTest s2=new StudentTest ("ballabh",102);
StudentTest s3=new StudentTest("govind",101);
StudentTest s4=s1;
System.out.println(s1.equals(s2));
System.out.println(s1.equals(s3));
System.out.println(s1.equals(s4));
System.out.println(s1.equals("govind"));
System.out.println(s1.equals("null"));
}
}
Output:
False
True
True
False
False
Simplified version of .equals() method:
public boolean equals(Object o){
try{
Student s2=(Student)o;
if(name.equals(s2.name) && rollno==s2.rollno){
return true;
}
else return false;
}
catch(ClassCastException e) {
return false;
}
catch(NullPointerException e) {
return false;
}
}
More simplified version of .equals() method :
public boolean equals(Object o) {
if(this==o)
return true;
if(o instanceof Student) {
Student s2=(Student)o;
if(name.equals(s2.name) && rollno==s2.rollno)
return true;
else
return false;
}
return false;
}
class StudentTestDemo {
String name;
int rollno;
StudentTestDemo (String name,int rollno) {
this.name=name;
this.rollno=rollno;
}
public boolean equals(Object o) {
if(this==o)
return true;
if(o instanceof StudentTestDemo ) {
StudentTestDemo s2=(StudentTestDemo)o;
if(name.equals(s2.name) && rollno==s2.rollno)
return true;
else
return false;
}
return false;
}
public static void main(String[] args){
StudentTestDemo s=new StudentTestDemo ("govind",101);
Integer i=new Integer(10);
StudentTestDemo s2=new StudentTestDemo ("govind",101);
System.out.println(s.equals(i));
System.out.println(s.equals(s2));
}
}
output:
false
true
To make .equals() method more efficient we have to place the following code at the top inside .equals() method.
if(this==o)
return true;
If 2 references pointing to the same object then .equals() method return true directly without performing any content comparison this approach improves performance of the system
String s1 = new String("ashok");
String s2 = new String("ashok");
System.out.println(s1==s2); //false
System.out.println(s1.equals(s2) ); //true
In String class .equals( ) is overridden for content comparision hence if content is same .equals( ) method returns true , even though ths objects are different.
StringBuffer s1 = new StringBuffer("ashok");
StringBuffer s2 = new StringBuffer("ashok");
System.out.println(s1==s2); //false
System.out.println(s1.equals(s2) ); //false
In StringBuffer class .equals( ) is not overriden for content comparision hence Object class .equals( ) will be executed which is meant for reference comparision , hence if objects are different .equals( ) method returns false , even though content is same.
Relationship between .equals() method and ==(double equal operator) :
If r1==r2 is true then r1.equals(r2) is always true i.e., if two objects are equal by == operator then these objects are always equal by .equals( ) method also.
If r1==r2 is false then we can't conclude anything about r1.equals(r2) it may return true (or) false.
If r1.equals(r2) is true then we can't conclude anything about r1==r2 it may returns true (or) false.
If r1.equals(r2) is false then r1==r2 is always false.
For any object reference r, r==null is always false.
Note : In String class , Wrapper classes and all collection classes .equals( ) method is overriden for content comparision
Differences between == (double equal operator) and .equals() method?
== (double equal operator)
It is an operator applicable for both primitives and object references.
In the case of primitives == (double equal operator) meant for content comparison, but in the case of object references == operator meant for reference comparison.
We can't override== operator for content comparison in object references.
If there is no relationship between argument types then we will get compile time error saying incompatible types.(relation means child to parent or parent to child or same type)
.equals() method
It is a method applicable only for object references but not for primitives.
By default .equals() method present in object class is also meant for reference comparison.
We can override .equals() method for content comparison.
If there is no relationship between argument types then .equals() method simply returns false and we won't get any compile time error and runtime error.
For any object reference r, r.equals(null) is also returns false.
String s = new String("govind");
StringBuffer sb = new StringBuffer("govind");
System.out.println(s == sb); // CE : incomparable types : String and StringBuffer
System.out.println(s.equals(sb)); //false
Contract between .equals() method and hashCode() method:
If 2 objects are equal by .equals() method compulsory their hashcodes must be equal (or) same. That is If r1.equals(r2) is true then r1.hascode()==r2.hashcode( ) must be true.
If 2 objects are not equal by .equals() method then there are no restrictions on hashCode() methods. They may be same (or) may be different. That is If r1.equals(r2) is false then r1.hashCode()==r2.hashCode() may be same (or) may be different.
If hashcodes of 2 objects are equal we can't conclude anything about .equals() method it may returns true (or) false. That is If r1.hashCode()==r2.hashCode() is true then r1.equals(r2) method may returns true (or) false.
If hashcodes of 2 objects are not equal then these objects are always not equal by .equals() method also. That is If r1.hashCode()==r2.hashCode() is false then r1.equals(r2) is always false.
To maintain the above contract between .equals() and hashCode() methods whenever we are overriding .equals() method compulsory we should override hashCode() method. Violation leads to no compile time error and runtime error but it is not good programming practice.
class Person {
String name;
int age;
Person(String name,int age) {
this.name=name;
this.age=age;
}
public boolean equals(Object o) {
if(this==o)
return true;
if(o instanceof Person) {
Person p2=(Person)o;
if(name.equals(p2.name) && age==p2.age)
return true;
else
return false;
}
return false;
}
public static void main(String[] args){
Person p1=new Person("govind",101);
Person p2=new Person("govind",101);
Integer i=new Integer(102);
System.out.println(p1.equals(p2));
System.out.println(p1.equals(i));
}
}
true
false
Which of the following is appropriate way of overriding hashCode() method?
public int hashCode()
{
returb age;
}
public int hashCode()
{
return age+height;
}
//Incorrect
public int hashCode()
{
return age+height;
}
//Incorrect
public int hashCode()
{
return name.hashCode()+age;
}
//correct
any of the above
Based on whatever the parameters we override ".equals() method" we should use same parameters while overriding hashCode() method also.
Note: in all wrapper classes, in string class, in all collection classes .equals() method is overridden for content comparison in our classes also it is highly recommended to override .equals() method.
case:1 If hash Codes of 2 objects are not equal then .equals() method always return false.(valid)
class Test1{
int i;
Test1(int i) {
this.i=i;
}
public int hashCode() {
return i;
}
public String toString() {
return i+"";
}
public static void main(String[] args) {
Test1 t1=new Test1(10);
Test1 t2=new Test1(20);
System.out.println(t1.hashCode());//10
System.out.println(t2.hashCode());//20
System.out.println(t1.hashCode()==t2.hashCode());//false
System.out.println(t1.equals(t2));//false
}
}
o/p:-------------
10
20
false
false
case2:-If 2 objects are equal by == operator then their hash codes must be same.(valid)
class Test2 {
int i;
Test2(int i) {
this.i=i;
}
public int hashCode() {
return i;
}
public String toString() {
return i+"";
}
public static void main(String[] args) {
Test2 t1=new Test2(10);
Test2 t2=t1;
System.out.println(t1.hashCode());//10
System.out.println(t2.hashCode());//10
System.out.println(t1==t2);//true
}
}
o/p:------------
10
10
true
case:-3 If == operator returns false then their hash codes(may be same (or) may be different) must be different.(invalid)
class Test3 {
int i;
Test3(int i) {
this.i=i;
}
public int hashCode() {
return i;
}
public String toString() {
return i+"";
}
public static void main(String[] args) {
Test3 t1=new Test3(10);
Test3 t2=new Test3(10);
System.out.println(t1.hashCode());//10
System.out.println(t2.hashCode());//10
System.out.println(t1==t2);//false
}
}
o/p:----------
10
10
false
case:-4
If hashcodes of 2 objects are equal then these objects are always equal by == operator also.(invalid)
Note: in all wrapper classes, in string class, in all collection classes .equals() method is overridden for content comparison in our classes also it is highly recommended to override .equals() method.
Monday, 15 April 2019
For every object jvm will generate a unique number which is nothing but hashCode.
Jvm will using hashCode while saving objects into hashing related data structures like HashSet, HashMap, and Hashtable etc.
If the objects are stored according to hashCode searching will become very efficient (The most powerful search algorithm is hashing which will work based on hashCode).
If we didn't override hashCode() method then Object class hashCode() method will be executed which generates hashCode based on address of the object but it doesn't mean hashCode represents address of the object.
Based on our programming requirement we can override hashCode() method to generate our own hashcode.
Overriding hashCode() method is said to be proper if and only if for every object we have to generate a unique number as hashcode for every object.
class Student
{
public int hashCode()
{
return 100;
}
}
It is improper way of overriding hashCode() method because for every object we are generating same hashcode.
class Student
{
int rollno;
public int hashCode()
{
return rollno;
}
}
It is proper way of overriding hashcode() method because for every object we are generating a different hashcode.
class Test
{
int i;
Test(int i)
{
this.i=i;
}
public static void main(String[] args){
Test t1=new Test(10);
Test t2=new Test(100);
System.out.println(t1);
System.out.println(t2);
}
}
Object==>toString() called.
Object==>hashCode() called.
In this case Object class toString( ) method got executed which is internally calls Object class hashCode( ) method.
class Test{
int i;
Test(int i){
this.i=i;
}
public int hashCode(){
return i;
}
public static void main(String[] args){
Test t1=new Test(10);
Test t2=new Test(100);
System.out.println(t1);
System.out.println(t2);
}}
Object==>toString() called.
Test==>hashCode() called.
In this case Object class toString( ) method got executed which is internally calls Test class hashCode( ) method.
class Test
{
int i;
Test(int i)
{
this.i=i;
}
public int hashCode(){
return i;
}
public String toString()
{
return i+"";
}
public static void main(String[] args){
Test t1=new Test(10);
Test t2=new Test(100);
System.out.println(t1);
System.out.println(t2);
}
}
Output:
10
100
In this case Test class toString() method got executed.
Note :
if we are giving opportunity to Object class toString() method it internally calls hashCode() method. But if we are overriding toString() method it may not call hashCode() method.
We can use toString() method while printing object references and we can use hashCode() method while saving objects into HashSet or Hashtable or HashMap.
class TestHashCode
{
int i;
TestHashCode(int i)
{
this.i=i;
}
public static void main(String[] args){
TestHashCode t1=new TestHashCode(10);
TestHashCode t2=new TestHashCode(100);
System.out.println(t1);
System.out.println(t2);
}
}
class TestWithHashCodeOnly{
int i;
TestWithHashCodeOnly(int i){
this.i=i;
}
public int hashCode(){
return i;
}
public static void main(String[] args){
TestWithHashCodeOnly t1=new TestWithHashCodeOnly(10);
TestWithHashCodeOnly t2=new TestWithHashCodeOnly(100);
System.out.println(t1);
System.out.println(t2);
}}
class TestWithHashAndtoStringMethod
{
int i;
TestWithHashAndtoStringMethod(int i)
{
this.i=i;
}
public int hashCode(){
return i;
}
public String toString()
{
return i+"";
}
public static void main(String[] args){
TestWithHashAndtoStringMethod t1=new TestWithHashAndtoStringMethod(10);
TestWithHashAndtoStringMethod t2=new TestWithHashAndtoStringMethod(100);
System.out.println(t1);
System.out.println(t2);
}
}
Saturday, 13 April 2019
toString( ) method :
We can use this method to get string representation of an object.
Whenever we are try to print any object reference internally toString() method will be executed.
If our class doesn't contain toString() method then Object class toString() method will be executed.
Example:
System.out.println(s1); => super(s1.toString());
class Student
{
String name;
int rollno;
Student(String name, int rollno)
{
this.name=name;
this.rollno=rollno;
}
public static void main(String args[]){
Student s1=new Student("Govind",101);
Student s2=new Student("Ajit",102);
System.out.println(s1);
System.out.println(s1.toString());
System.out.println(s2);
}
}
In the above program Object class toString() method got executed which is implemented as follows.
In the above program Object class toString() method got executed which is implemented as follows.
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
here getClass().getName() => classname@hexa_decimal_String_representation_of_hashCode
class Student1
{
String name;
int rollno;
Student1(String name, int rollno)
{
this.name=name;
this.rollno=rollno;
}
public String toString(){
return name+"........"+rollno;
}
public static void main(String args[]){
Student1 s1=new Student1("Govind",101);
Student1 s2=new Student1("Ajit",102);
System.out.println(s1);
System.out.println(s1.toString());
System.out.println(s2);
}
}
To provide our own String representation we have to override toString() method in our class.
Ex : For example whenever we are try to print student reference to print his a name and roll no we have to override toString() method as follows.
public String toString(){
return name+"........"+rollno;
}
In String class, StringBuffer, StringBuilder, wrapper classes and in all collection classes toString() method is overridden for meaningful string representation. Hence in our classes also highly recommended to override toString() method.
class TestDemo{
public String toString(){
return "Test";
}
public static void main(String[] args){
Integer i=new Integer(10);
String s=new String("javatechnology");
TestDemo t=new TestDemo();
System.out.println(i);
System.out.println(s);
System.out.println(t);
}
}
Thursday, 21 March 2019
Singleton pattern restricts the instantiation of a class and ensures that only one instance of the class exists in the java virtual machine.
The singleton class must provide a global access point to get the instance of the class.
Singleton pattern is used for logging, drivers objects, caching and thread pool.
Singleton design pattern is also used in other design patterns like Abstract Factory, Builder, Prototype, Facade etc.
Singleton design pattern is used in core java classes also, for example java.lang.Runtime, java.awt.Desktop.
To implement a Singleton pattern, we have different approaches but all of them have the following common concepts.
Private static variable of the same class that is the only instance of the class.
Public static method that returns the instance of the class, this is the global access point for outer world to get the instance of the singleton class.
private EagerInitializedSingleton(){}
{
return s1;
}
return instance;
}
Govind Ballabh Khan
=========================================================================================================================================================================================
Static block initialization implementation is similar to eager initialization, except that instance of class is created in the static block that provides option for exception handling.
{
return s1;
}
static{
try{
instance = new StaticBlockSingleton();
}catch(Exception e){
throw new RuntimeException("Exception occured in creating singleton instance");
}
}
return instance;
}
Govind Ballabh Khan
Lazy Initialization
Lazy initialization method to implement Singleton pattern creates the instance in the global access method. Here is the sample code for creating Singleton class with this approach.
{
return s1;
}
if(instance == null){
instance = new LazyInitializedSingleton();
}
return instance;
}
Govind Ballabh Khan
The easier way to create a thread-safe singleton class is to make the global access method synchronized, so that only one thread can execute this method at a time. General implementation of this approach is like the below class.
Above implementation works fine and provides thread-safety but it reduces the performance because of the cost associated with the synchronized method, although we need it only for the first few threads who might create the separate instances (Read: Java Synchronization).
{
return s1;
}
public static synchronized ThreadSafeSingleton getInstance(){
if(instance == null){
instance = new ThreadSafeSingleton();
}
return instance;
}
}
Govind Ballabh Khan