Sunday, 27 April 2025

Basic Concepts Apache Kafka:

 Basic Concepts Apache Kafka:

1. Start Zookeeper
C:\ApacheKafka\kafka_2.12-3.5.0>bin\windows\zookeeper-server-start.bat config\zookeeper.properties
2. Start Kafka Server
C:\ApacheKafka\kafka_2.12-3.5.0>bin\windows\kafka-server-start.bat config\server.properties
3. How Topic Created?
C:\ApacheKafka\kafka_2.12-3.5.0>bin\windows\kafka-topics.bat --create --topic employee-topic --bootstrap-server localhost:9092
Created topic employee-topic.
4. How to produce the message ?
C:\ApacheKafka\kafka_2.12-3.5.0>bin\windows\kafka-console-producer.bat --topic employee-topic --bootstrap-server localhost:9092
5. How to consume the Message ?
C:\ApacheKafka\kafka_2.12-3.5.0>bin\windows\kafka-console-consumer.bat --topic employee-topic --from-beginning --bootstrap-server localhost:9092












                                                                     Apache Kafka Example

Example Apache Kafka
deliveryboyapp
enduserapp
package com.app.deliveryboy.config;
import org.apache.kafka.clients.admin.NewTopic;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.config.TopicBuilder;
@Configuration
public class KafkaConfig {
@Bean
public NewTopic topic()
{
return TopicBuilder.name("location-update-topic")
//.partitions()
// .replicas()
.build();
}
}
=========================================
package com.app.deliveryboy.service;
import com.app.deliveryboy.config.AppConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
@Service
public class KafkaService {
private Logger logger=LoggerFactory.getLogger(KafkaService.class);
@Autowired
private KafkaTemplate<String,String> kafkaTemplate;
public boolean updateLocation(String location)
{
this.kafkaTemplate.send(AppConstants.LOCATION_TOPIC_NAME,location);
this.logger.info("message Produced");
return true;
}
}
========================================
package com.app.deliveryboy.config;
public class AppConstants {
public static final String LOCATION_TOPIC_NAME="location-update-topic";
}
==========================================
package com.app.deliveryboy.controller;
import com.app.deliveryboy.service.KafkaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.Map;
@RestController
@RequestMapping("/location")
public class LocationController {
@Autowired
private KafkaService kafkaService;
@PostMapping("/update")
public ResponseEntity<?> updateLocation()
{
for(int i=0;i<=200000;i++)
{
long longitude=Math.round(Math.random()*100);
long latitude=Math.round(Math.random()*100);
kafkaService.updateLocation("("+longitude+","+latitude+")");
}
return new ResponseEntity<>(Map.of("message","location updated"), HttpStatus.OK);
}
}
===========================================
package com.app.deliveryboy;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class DeliveryboyappApplication {
public static void main(String[] args) {
SpringApplication.run(DeliveryboyappApplication.class, args);
}
}
========================================
spring.application.name=deliveryboyapp
server.port=8080
spring.kafka.producer.bootstrap-servers: localhost:9092
spring.kafka.producer.key-serializer: org.apache.kafka.common.serialization.StringSerializer
spring.kafka.producer.value-serializer: org.apache.kafka.common.serialization.StringSerializer
============================================
package com.app.enduserapp;
import com.app.enduserapp.config.AppConstants;
import org.slf4j.Logger;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.KafkaListener;
@Configuration
public class KafkaConfig {
@KafkaListener(topics=AppConstants.LOCATION_TOPIC_NAME,groupId = AppConstants.GROUP_ID)
public void updateLocation(String value)
{
System.out.println(value);
}
}
============================================
package com.app.enduserapp.config;
public class AppConstants {
public static final String LOCATION_TOPIC_NAME="location-update-topic";
public static final String GROUP_ID="groupid-1";
}
=======================================
spring.application.name=enduserapp
server.port=8081
spring.kafka.consumer.bootstrap-servers: localhost:9092
spring.kafka.consumer.group-id: groupid-1
spring.kafka.consumer.auto-offset-reset: earliest
spring.kafka.consumer.key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
spring.kafka.consumer.value-deserializer: org.apache.kafka.common.serialization.StringDeserializer
=========================================
package com.app.enduserapp;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class EnduserappApplication {
public static void main(String[] args) {
SpringApplication.run(EnduserappApplication.class, args);
}
}

Sunday, 26 January 2025

Stream Method Example:

 Stream Method Example:

package java8stream;
public class Employee {
private String empId;
private String firstName;
private String lastName;
private String email;
private String gender;
private String newJoiner;
private int salary;
private int rating;
public Employee() {
super();
}
public Employee(String empId, String firstName, String lastName, String email, String gender, String newJoiner,
int salary, int rating) {
super();
this.empId = empId;
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.gender = gender;
this.newJoiner = newJoiner;
this.salary = salary;
this.rating = rating;
}
public String getEmpId() {
return empId;
}
public void setEmpId(String empId) {
this.empId = empId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getNewJoiner() {
return newJoiner;
}
public void setNewJoiner(String newJoiner) {
this.newJoiner = newJoiner;
}
public int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
public int getRating() {
return rating;
}
public void setRating(int rating) {
this.rating = rating;
}
@Override
public String toString() {
return "Employee [empId=" + empId + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email
+ ", gender=" + gender + ", newJoiner=" + newJoiner + ", salary=" + salary + ", rating=" + rating + "]";
}
}
===========================================
package java8stream;
import java.util.Arrays;
import java.util.List;
public class EmployeeList {
public static void main(String[] args) {
List<Employee> empList = getEmpList();
System.out.println(empList);
}
public static List<Employee> getEmpList(){
return Arrays.asList(
new Employee("59-385-1088","Govind","Khan","govindkhan@gmail.com","Male","TRUE",101146,0),
new Employee("73-274-6476","Ajit","Kumar","ajitkumar@gmail.com","Male","FALSE",29310,2),
new Employee("85-939-9584","Nitya","kumari","nityakumari@twitter.com","Female","FALSE",62291,4),
new Employee("08-180-8292","Saurabh","Sharma","saurabhsharma@twitter.com","Male","FALSE",142439,4),
new Employee("21-825-2623","Sachin","Raj","sachinraj@gmail.com","Male","FALSE",128764,5),
new Employee("66-708-5539","Nikee","kumari","nikeekumari@gmail.com","Female","FALSE",152924,4),
new Employee("81-697-2363","Rishabh","Verma","rishabhverma@twitter.com","Male","TRUE",128907,0),
new Employee("63-019-1110","Nihal","Shaikh","nihalshaikh@twitter.com","Male","TRUE",25100,0)
);
}
}
===========================================
package java8stream;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collector;
import java.util.stream.Collectors;
public class StreamOperation {
public static void main(String[] args) {
// We have a list of employees with empId, firstName, lastName, email,
// gender,newJoiner, salary and rating.
List<Employee> empList = EmployeeList.getEmpList();
// case :1 We will filter the employees list with gender as Female
empList.stream().filter(s -> s.getGender().equals("Female")).forEach(System.out::println);
// case :2 We will filter the employees list with newJoiner as True
empList.stream().filter(s -> s.getNewJoiner().equals("TRUE")).forEach(System.out::println);
// Case : 3 We will sort the employee list by rating asc.
empList.stream().sorted(Comparator.comparing(Employee::getRating)).forEach(System.out::println);
// case 4: We will sort the employee list by rating desc.
empList.stream().sorted(Comparator.comparing(Employee::getRating).reversed()).forEach(System.out::println);
// case:5 We will sort the employee list by both rating and salary
Comparator<Employee> sortByRating = (e1, e2) -> Double.compare(e1.getRating(), e2.getRating());
Comparator<Employee> sortBySalary = (e1, e2) -> Double.compare(e1.getSalary(), e2.getSalary());
// Sort by Name then Sort by Salary
empList.stream().sorted(sortByRating.thenComparing(sortBySalary)).forEach(e -> System.out.println(e));
// case: 6 Match Method: We will see all employees with salary more than 1000
boolean isSalary = empList.stream().allMatch(s -> s.getSalary() > 1000);
System.out.println(isSalary);
// case :7 We will retrieve employee with max salary
empList.stream().max(Comparator.comparing(Employee::getSalary)).ifPresent(System.out::println);
// case :8 We will retrieve employee with max rating
empList.stream().max(Comparator.comparing(Employee::getRating)).ifPresent(System.out::println);
// case :9 We will retrieve employee with min salary
empList.stream().min(Comparator.comparing(Employee::getSalary)).ifPresent(System.out::println);
// case :10 We will retrieve employee with min rating
empList.stream().min(Comparator.comparing(Employee::getRating)).ifPresent(System.out::println);
// case :11 GroupBy Function : We will group all our employees by Gender
Map<String, List<Employee>> employeesBygender = empList.stream()
.collect(Collectors.groupingBy(Employee::getGender));
employeesBygender.forEach(((k, v) -> {
System.out.println(k);
v.forEach(System.out::println);
}));
}
}

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

                                                                 equals ( ) in java?

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

                                         hashCode() method of object class in java:


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);
  }
}