Get Size of Java HashSet Example

1.Basic java example program to get size of  hashset
  • int size()   This method is used get get size of  hashset

  1. package com.getSizehashset;
  2.  
  3. import java.util.HashSet;
  4. import java.util.Iterator;
  5.  
  6. public class HashsetExample{
  7.  
  8. public static void main(String[] args) {
  9.   
  10. //create object of HashSet
  11.  HashSet<Integer> hashSet = new HashSet();
  12.        
  13.  //add elements to HashSet object
  14.  hashSet.add(1);
  15.  hashSet.add(2);
  16.  hashSet.add(3);
  17.  hashSet.add(4);
  18.  hashSet.add(5);
  19.  hashSet.add(6);
  20.  hashSet.add(7);
  21.  hashSet.add(8);
  22.  
  23. System.out.println("Size of HashSet after addition : " + hashSet.size());
  24.  
  25. System.out.println("Hashset contains");
  26.  
  27. Iterator it=hashSet.iterator();
  28.              
  29. while(it.hasNext()){
  30. System.out.println(it.next());
  31.                      
  32. }   
  33.  
  34. }
  35.  
  36. }
     


Output:

  1. Size of HashSet after addition
  2. 8
  3. hashset contains
  4. 1
  5. 2
  6. 3
  7. 4
  8. 6
  9. 7
  10. 8

Return statement in try catch block java

1.Can we write return statement in try or catch blocks in java

  • Inside method if we have some statements which may proven to raise exceptions we need to keep those statements in side try catch blocks in order to handle the exceptions.

  • There is a situation where a method will have a return type and we can return some value at any part of the method based on the conditions.
  • So mixing these two scenarios we may have a situation to return some value from try block or catch block in such cases we need to follow some basic rules.
  • This is also one of the famous interview question  "can we write return statement in try block ", "can we write return statement in catch block ", "what will happen if we return some value in try block or catch block ", "will catch block execute after return statement " and "what are the basic rules we need to follow when we are returning or our method returning some value in try or catch blocks"
  • We will see the all the scenarios and conclusion.
Return statement in try block:

i) return statement in try block only
  • If we return a value in try block and if we do not return a value at the end of the method it leads to compile time exception 
  • Error: This method must return a result of type int

  1. package com.exceptionhandlingiinterviewquestions;
  2.  
  3. public class TryCatchReturn{
  4.  
  5. int calc(){ // Error:This method must return a result of type int
  6.         
  7. try {
  8.  
  9. return 1;
  10.  
  11. } catch (Exception e) {
  12.  
  13. }
  14.         
  15.  System.out.println("End of the method");
  16. }
  17.     
  18.     
  19. public static void main(String[] args) {
  20.         
  21.         TryCatchReturn obj = new TryCatchReturn();
  22.        
  23.  
  24. }

  25. }
     

ii) return statement in try block and end of the method but after return one statement

  • Even though it in this condition it wont reach end of the method still it asks us for return at end of the method because in some cases there may be a chance of getting exception in try block so it will not completely execute try in this case we don not have return in catch so at end of the method it expects some value to be return because the  method have some return type.
  • If we are keeping return statement in try block only there may be a situation of chance of raising exception and try will not execute completely and it goes to catch block that is the reason it expecting a return at catch or end of the method 
  • So in this scenario we will try to keep return but after return we have written one statement

  1. package com.exceptionhandlingiinterviewquestions;
  2.  
  3. public class TryCatchReturn{
  4.  
  5. int calc(){
  6.         
  7. try {
  8.  
  9. return 1;
  10.  
  11. } catch (Exception e) {
  12.  
  13. }
  14.  
  15. return 10; 
  16.  System.out.println("End of the method"); // Error : Unreachable code
  17. }
  18.     
  19.     
  20. public static void main(String[] args) {
  21.         
  22.         TryCatchReturn obj = new TryCatchReturn();
  23.        
  24.  
  25. }

  26. }
     

  • in the above program last statement will not execute at any condition so it became unreachable code as we know java does not supports unreachable codes so it will raise compile time error.
iii) return statement in try block and end of the method

  • This is the correct and successful scenario with respect to try with return statement in java
  • Lest see a java program on this




  1. package com.exceptionhandlingiinterviewquestions;
  2.  
  3. public class TryCatchReturn{
  4.  
  5. int calc(){
  6.         
  7. try {
  8.  
  9. return 1;
  10.  
  11. } catch (Exception e) {
  12.  
  13. }
  14.  
  15. System.out.println("End of the method");
  16. return 10; 
  17. }
  18.     
  19.     
  20. public static void main(String[] args) {
  21.         
  22.   
  23. TryCatchReturn obj = new TryCatchReturn();
  24.        
  25. System.out.println(obj.calc());
  26.  
  27. }

  28. }
     

Output:

  1. 1

Return statement in catch block:

i) return statement in catch block only
  • If we return a value in catch block and if we do not return a value at the end of the method it leads to compile time exception 
  • Error: This method must return a result of type int

  1. package com.exceptionhandlingiinterviewquestions;
  2.  
  3. public class TryCatchReturn{
  4.  
  5. int calc(){ // Error:This method must return a result of type int
  6.         
  7. try {
  8.  

  9.  
  10. } catch (Exception e) {
  11.  return 1;
  12. }
  13.         
  14.  System.out.println("End of the method");
  15. }
  16.     
  17.     
  18. public static void main(String[] args) {
  19.         
  20.         TryCatchReturn obj = new TryCatchReturn();
  21.        
  22.  
  23. }

  24. }
     

ii) return statement in catch block and end of the method but after return one statement

  1. package com.exceptionhandlingiinterviewquestions;
  2.  
  3. public class TryCatchReturn{
  4.  
  5. int calc(){
  6.         
  7. try {
  8.  
  9.  
  10. } catch (Exception e) {
  11.  
  12. return 1;
  13. }
  14.  
  15. return 10; 
  16.  System.out.println("End of the method"); // Error : Unreachable code
  17. }
  18.     
  19.     
  20. public static void main(String[] args) {
  21.         
  22.         TryCatchReturn obj = new TryCatchReturn();
  23.        
  24.  
  25. }

  26. }
     

  • in the above program last statement will not execute at any condition so it became unreachable code as we know java does not supports unreachable codes so it will raise compile time error.
ii) return statement in catch block and end of the method





  1. package com.exceptionhandlingiinterviewquestions;
  2.  
  3. public class TryCatchReturn{
  4.  
  5. int calc(){
  6.         
  7. try {
  8.  
  9.  int x=12/0;
  10. } catch (Exception e) {
  11.  
  12. return 1;
  13. }
  14.  
  15. return 10; 
  16. }
  17.     
  18.     
  19. public static void main(String[] args) {
  20.         
  21. TryCatchReturn obj = new TryCatchReturn();
  22.        
  23.  System.out.println(obj.calc());
  24.  
  25. }

  26. }
     
Output:

  1. 1


Return statement with try catch block

try catch with return statement in java


try catch block with return statement
 

Java program to Copy all elements of Java HashSet to an Object Array

1.Basic java example program to Copy all elements of Java HashSet to an Object Array
  • Object[] toArray()   This method is used To copy all elements of java HashSet object into array use

  1. package com.copyelementhashset;
  2.  
  3. import java.util.HashSet;
  4. import java.util.Iterator;
  5.  
  6. public class HashsetExample{
  7.  
  8. public static void main(String[] args) {
  9.   
  10. //create object of HashSet
  11.  HashSet<Integer> hashSet = new HashSet();
  12.        
  13.  //add elements to HashSet object
  14.  hashSet.add(1);
  15.  hashSet.add(2);
  16.  hashSet.add(3);
  17.  hashSet.add(4);
  18.  hashSet.add(5);
  19.      
  20. Object[] objArray = hashSet.toArray();
  21.  
  22. //display contents of Object array
  23. System.out.println("HashSet elements are copied into an Array. Now Array Contains..");
  24.  
  25.  for(int index=0; index < objArray.length ; index++)
  26.   System.out.println(objArray[index]);

  27.  
  28. System.out.println("Hashset contains");
  29.  
  30. Iterator it=hashSet.iterator();
  31.              
  32. while(it.hasNext()){
  33. System.out.println(it.next());
  34.                      
  35. }   
  36.  
  37. }
  38.  
  39. }
     



Output:

  1. HashSet elements are copied into an Array. Now Array Contains..
  2. 1
  3. 2
  4. 3
  5. 4
  6. 5
  7. Hashset contains
  8. 1
  9. 2
  10. 3
  11. 4
  12. 5

Check if a particular element exists in Java HashSet Example

1.Basic java example program to check particular element is exists in hashset
  • boolean contains(Object o)   This method Returns true if this set contains the specified element

  1. package com.checkelementhashset;
  2.  
  3. import java.util.HashSet;
  4. import java.util.Iterator;
  5.  
  6. public class HashsetExample{
  7.  
  8. public static void main(String[] args) {
  9.   
  10. //create object of HashSet
  11.  HashSet<Integer> hashSet = new HashSet();
  12.        
  13.  //add elements to HashSet object
  14.  hashSet.add(1);
  15.  hashSet.add(2);
  16.  hashSet.add(3);
  17.  hashSet.add(4);
  18.  hashSet.add(5);
  19.      
  20.  /*
  21.  To check whether a particular value exists in HashSetwe need to use
  22.   boolean contains(Object value) method of HashSet class.
  23.  this method returns true if the HashSet contains the value, otherwise returns false.
  24.  */
  25.        
  26.         boolean isExists = hashSet.contains(5);
  27.         System.out.println("5 exists in HashSet ? : " + isExists);    
  28.  

  29.  
  30. Iterator it=hashSet.iterator();
  31.              
  32. while(it.hasNext()){
  33. System.out.println(it.next());
  34.                      
  35. }   
  36.  
  37. }
  38.  
  39. }
     



Output:

  1. 3 exists in HashSet ? : true
  2. 1
  3. 2
  4. 3
  5. 4
  6. 5

Java program to remove key value from hashmap

1.Basic java example program to remove value from hashmap.

  • using  Object remove(Object key) method we can remove key value pair of hashmap.


  1. package com.javaremovevaluehashmap;
  2.  
  3. import java.util.Hashmap;
  4. import java.util.Iterator;
  5. import java.util.Map;
  6. import java.util.Map.Entry;
  7.  
  8. public class HashmapExample{
  9.  
  10. public static void main(String[] args) {
  11.   
  12. //create an Hashmap object
  13. HashMap<String, String> hashmap = new HashMap();
  14.        
  15. //Add key values pairs to hashmap
  16.         
  17. hashmap.put("1","One");
  18. hashmap.put("2","Two");
  19. hashmap.put("3","Three");
  20. hashmap.put("4","Four");
  21. hashmap.put("5","Five");
  22. hashmap.put("6","Six");       
  23.       String key=null;
  24.       String value="java programming basics Interview questions";   
  25. hashmap.put(key,value);
  26.  
  27. /*
  28. To remove a key value pair from HashMap use
  29. Object remove(Object key) method of HashMap class.
  30. It returns either the value mapped with the key or null if no value
  31. was mapped.    
  32.  */      
  33.  
  34.  Object object = hashmap.remove("4");
  35.         System.out.println(object + " Removed from HashMap");
  36.     
  37.  
  38. if(!hashmap.isEmpty()){
  39.  
  40. Iterator it=hashmap.entrySet().iterator();
  41.              
  42. while(it.hasNext()){

  43. Map.Entry obj=(Entry) it.next();
  44. System.out.print(obj.getKey()+" ");
  45. System.out.println(obj.getValue());
  46.              
  47. }           
  48. }   
  49.  
  50. }
  51.  
  52. }
     



Output:

  1. Four Removed from HashMap
  2. null java programming basics Interview questions
  3. 1 One
  4. 2 Two
  5. 3 Three
  6. 5 Five
  7. 6 Six

Java Example program to restrict a class from creating not more than three objects

Question: How to restrict a class from creating multiple objects?

  • Restring a class from creating multiple objects or restricting class from creating not more than three objects this type of interview questions will come for experience interview or written tests.

  • Yes we can restrict a class from creating multiple objects.
  • As we know using singleton we can restrict a class from creating multiple objects it will create single object and share it.
  • Same design pattern we can apply here with counter 
  • In this we will take a static variable counter to check how many objects created
  • As we can access static variables in constructor and static variables are class level we can stake help of static variable to count number object created.
  • First three time we will create new objects and forth time we need to return 3rd object reference. if we don't want same object 4th time we can return null
  • By printing the hashcode() of the object we can check how many objects created. 
  •  

Basic java example program to restrict a class from not to create more than three instances




  1. package com.instanceofjava;
  2.  
  3. public class RestrictObjectCreation{

  4. private static RestrictObjectCreationobject;
  5. public static int objCount = 0;
  6.  
  7. private RestrictObjectCreation()
  8. {
  9.      System.out.println("Singleton(): Private constructor invoked");
  10.  
  11. objCount  ++;
  12. }
  13.  
  14. public static RestrictObjectCreation getInstance()
  15. {
  16.  
  17. if (objCount < 3)
  18. {
  19.  
  20. object = new RestrictObjectCreation();
  21.  
  22.  }
  23.  
  24. return object;
  25.  
  26. }
  27.  
  28. }
     

  1. package instanceofjava;
  2.  
  3. public class Test{

  4. public static void main(String args[]) {
  5.  
  6. RestrictObjectCreation obj1= RestrictObjectCreation.getInstance();
  7. RestrictObjectCreation obj2= RestrictObjectCreation.getInstance();
  8. RestrictObjectCreation obj3= RestrictObjectCreation.getInstance();
  9. RestrictObjectCreation obj4= RestrictObjectCreation.getInstance();
  10. RestrictObjectCreation obj5= RestrictObjectCreation.getInstance();
  11.  
  12. System.out.println(obj1.hashCode());
  13. System.out.println(obj2.hashCode());
  14. System.out.println(obj3.hashCode());
  15. System.out.println(obj4.hashCode());
  16. System.out.println(obj5.hashCode());
  17.  
  18. }
  19. }



Output:

  1. RestrictObjectCreation(): Private constructor invoked
  2. RestrictObjectCreation(): Private constructor invoked
  3. RestrictObjectCreation(): Private constructor invoked
  4. 705927765
  5. 366712642
  6. 1829164700
  7. 1829164700
  8. 1829164700


restrict  from creating multiple objects


You Might Like:

1.Five Different places to create object of a class




3.Six different ways to iterate list in java
Select Menu