What are the oops concepts in java?

  • Oops concepts are the rules which are supposed to be satisfied by a programming language in order to call that programming language as an Object Oriented Programming Language
  • The three oops concepts are
            i.Encapsulation
            ii. Polymorphism
            iii.Inheritance
  • Encapsulation:
    The process of binding the data with corresponding functions.
  • Polymorphism:
    Defining multiple methods with same name.
  • Inheritance:
    Getting the properties from one class object to another class object 

What happens When System.out.println(null)?

  • Compilation Error -This is because you can pass an Object or a String or char[]. Since null can fit in both, the compiler doesn't know which method to use, leading to compile error.

  • Method Overloading:
        1.public void prinltln(String str) { }
        2.public void prinltln(char[] ch){ }
        3.public void prinltln(Object ch){ 
  •  It seems the call System.out.print(null) is ambiguous to compiler because print(null) here will find the two best specific matches i.e. print(String) and print(char[]) . So compiler is unable to determine which method to call here .
  • Compilation Error:
       System.out.println(null)

Program #1: what will happen when we print System.out.println(null)


System out prinln null

  • Compile Fine:
         System.out.println((String)null);//null
         System.out.println((char[])null);
         System.out.println((Object)null);//null
  • It's the compiler type-checking the parameters of the method call.
  • But here we need to know one more thing  System.out.println((char[])null); will compile fine but at run time will throw runtime exception.

 Program #2: what will happen when we print System.out.println(null) by type casting
  

  1. package com.systemoutprintn;
  2. public class Test {
  3.  
  4.     /**
  5.      * @Website: www.instanceofjava.com
  6.      * @category: System.out.println(null)
  7.      */
  8.  
  9. public static void main(String[] args) {
  10.  
  11.          System.out.println((String)null);//null
  12.          System.out.println((Object)null);//null
  13.          System.out.println((char[])null);
  14.             
  15.  
  16. }
  17.  
  18. }

 Output:
 

  1. null
  2. null
  3. Exception in thread "main" java.lang.NullPointerException
  4.     at java.io.Writer.write(Unknown Source)
  5.     at java.io.PrintStream.write(Unknown Source)
  6.     at java.io.PrintStream.print(Unknown Source)
  7.     at java.io.PrintStream.println(Unknown Source)
  8.     at com.systemoutprintn.Test.main(Test.java:13)


Explain System.out.println()?


  • System is a class Which is present in java.lang package.
    Out is a static final field (variable) of  Printstream class
    Println(): method of Printstream Class
  • Class System{
    public static final Printstream Out;
    }
  • Class Printstream{
    public void println(){}}




Final ,finally and finalize()?

Final:

  • Any variable declare along with final modifier then those variables treated as final variable.
  •  if we declare final variables along with static will became constants.
  • public final String name = "foo"; //never change this value
  • If you declare method as final that method also known as final methods.Final methods are not overridden.means we can't overridden that method in anyway.
  • public final void add(){
     }
     public class A{
     void add(){
     //Can't override
     }

     }
  • If you declare class is final that class is also known as final classes.Final classes are not extended.means we can't extens that calss in anyway.
  • public final class indhu{
     }
     public class classNotAllowed extends indhu {...} //not allowed

Finally:

  • Finally blocks are followed by try or catch.finally blocks are complasary executable blocks.But finally is useful for more than just exception handling.
  •  it allows the programmer to avoid having cleanup code accidentally bypassed by a return,
     continue, or break,Closing streams, network connection, database connection. Putting cleanup  code in a finally block is always a good practice even when no exceptions are anticipated
  •  where finally doesn't execute e.g. returning value from finally block, calling System.exit from try block etc
  • finally block always execute, except in case of JVM dies i.e. calling System.exit() .

     lock.lock();
    try {
      //do stuff
    } catch (SomeException se) {
      //handle se
    } finally {
      lock.unlock(); //always executed, even if Exception or Error or se
      //here close the database connection and any return statements like that we have to write
    }

Finalize():

  • finalize() is a method which is present in Java.lang.Object class.
  •  Before an object is garbage collected, the garbage collector calls this finalize() of object.Any unreferncebefore destorying if that object having any connections with databse or anything..It will remove  the connections and it will call finalize() of object.It will destroy the object.
  • If you want to Explicitly call this garbage collector you can use System.gc() or Runtime.gc() objects are there from a long time the garbage collector will destroy that objects.
  • public void finalize() {
      //free resources (e.g. unallocate memory)
      super.finalize();
    }

Differences between HashMap and Hash-table



Java provides different types of Map implementations, two of the most commonly used being HashMap and Hashtable. Both of these classes implement the Map< interface and store key-value pairs, but they differ significantly in terms of synchronization, performance, and usage. In this article, we will explore the differences in detail.

Introduction

Map in Java is a collection of key-value pairs where each key is unique. Both HashMap and Hashtable use a hashing mechanism to store and retrieve data efficiently. However, they have different characteristics that make them suitable for different use cases.

Key Differences Between HashMap and Hashtable

The table below provides a summary of the key differences between HashMap and Hashtable:

FeatureHashMapHashtable
SynchronizationNot synchronized (not thread-safe)Synchronized (thread-safe)
PerformanceFaster (no overhead of synchronization)Slower (due to synchronization)
Null Keys/ValuesAllows one null key and multiple null valuesDoes not allow null keys or values
IterationUses Iterator (fail-fast)Uses Enumerator (legacy, not fail-safe)
InheritanceExtends AbstractMapExtends Dictionary (legacy class)
Thread SafetyRequires external synchronization for multi-threadingThread-safe, but may impact performance
Use CaseBest for non-threaded applicationsSuitable for multi-threaded environments


Differences between HashMap and Hash-table
  •  Synchronization or Thread Safe : One of the major differences between HashMap and Hashtable is that HashMap is non-synchronized whereas Hashtable is synchronized, which means Hashtable is thread-safe and can be shared between multiple threads but HashMap cannot be shared between multiple threads without proper synchronization. Java 5 introduced ConcurrentHashMap which is an alternative of Hashtable and provides better scalability than Hashtable in Java.Synchronized means only one thread can modify a hash table at one point of time. Basically, it means that any thread before performing an update on a hashtable will have to acquire a lock on the object while others will wait for lock to be released.
  • Null keys and null values : The HashMap class is roughly equivalent to Hashtable, except that it permits nulls. (HashMap permits one null key and multiple null values.
    Hashtable doesn't permit any sort of nulls (key or values).).
  • Iterating the values: The third significant difference between HashMap vs Hashtable is that Iterator in the HashMap is a fail-fast iterator while the enumerator for the Hashtable is not and throw ConcurrentModificationException if any other Thread modifies the map structurally by adding or removing any element except Iterator’s own remove() method. But this is not a guaranteed behavior and will be done by JVM on best effort. This is also an important difference between Enumeration and Iterator in Java.
  • Default Capacity: 
  •  Hashmap: static final int DEFAULT_INITIAL_CAPACITY =16  static final float DEFAULT_LOAD_FACTOR = 0.75f;  
  • Hashtable:  static final int DEFAULT_INITIAL_CAPACITY = 11;   static final float DEFAULT_LOAD_FACTOR = 0.75f;
  • HashMap does not guarantee that the order of the map will remain constant over time.
HashMap can be synchronized by using Collections.synchronizedMap() method
Map m = Collections.synchronizedMap(hashMap);
Example:

Here is example of a C program that uses a for loop to calculate the sum of 'n' numbers:

  1. import java.util.HashMap;
  2. import java.util.Hashtable;

  3. public class HashMapHashtableExample {
  4.    
  5.     public static void main(String[] args) {      

  6.  

  7.         Hashtable<String,String> hashtableobj = new Hashtable<String, String>();
  8.         hashtableobj.put("name", "ramu");
  9.         hashtableobj.put("petname", "ram");
  10.         System.out.println("Hashtable object output :"+ hashtableobj);



  11.         HashMap hashmapobj = new HashMap();
  12.         hashmapobj.put("name", "ramu"); 
  13.         hashmapobj.put("pertname", "ram");
  14.         System.out.println("HashMap object output :"+hashmapobj);

  15.  }
  16. }




hashmap vs hashtable

HashMap in Java

What is HashMap?

HashMap<K, V> is a part of the java.util package and implements the Map<K, V> interface. It stores key-value pairs using a hashing mechanism, which allows efficient insertion, deletion, and retrieval operations.

Characteristics of HashMap

  • Not synchronized: Multiple threads can access a HashMap concurrently, but this can lead to inconsistent data if modifications occur.

  • Allows null values and a single null key.

  • Unordered: Does not guarantee any specific order of keys.

  • Performance: Fast for most operations since there is no synchronization overhead.

Hashtable in Java

 What is Hashtable?

Hashtable<K, V> is a legacy class from Java 1.0 that implements the Map<K, V> interface and extends the Dictionary<K, V> class. It stores key-value pairs using hashing and provides built-in synchronization, making it thread-safe.

Characteristics of Hashtable

  • Synchronized: All methods are thread-safe but can lead to performance bottlenecks.

  • Does not allow null keys or values.

  • Unordered: Similar to HashMap, it does not guarantee the order of keys.

  • Uses Enumerator instead of Iterator (legacy mechanism, should be avoided).


Java String

String:

  • Series of characters is known as string.
  • String is final class in java.
    public final class String
    extends Object
    implements Serializable, Comparable<String>, CharSequence.
  • We can create a String object in two ways.
  • 1. By using new operator
        String str= new String("Java");
    2.By using String literal.
       String str= "Java".

Difference between string object and string literal  :


     
  • Whenever you call new() in JAVA it create an object in heap.
  • String literals will go into String Constant Pool.
  • For objects JVM used String constant pool which is for efficient memory management in java. Unlike other Java Objects, instead of managing String object on heap area, they introduced String constant pool. One of important characteristic of String constant pool is that it does not create same String object if there is already String constant in the pool.
Example program:

  1. public class StringCreationDemo {     
  2.                                                                                   
  3. public static void main (String args[]) {
  4.  
  5.     String str1 = "Hello"; 
  6.     String str2 = "Hello";
  7.  
  8.     System.out.println("str1 and str2 : literal");   
  9.     System.out.println("str1 == str2 is " + (str1 == str2)); 
  10.  
  11.     String str3 = new String("Hello"); 
  12.     String str4 = new String("Hello");
  13.  
  14.     System.out.println("str3 and str4 : new operator");   
  15.     System.out.println(" str3 == str4 is " + (str3 == str4)); 
  16.  
  17.     String str5 = "Hel"+ "lo"; 
  18.     String str6 = "He" + "llo";
  19.  
  20.     System.out.println("str5 and str6 : expression.");   
  21.     System.out.println("    str5 == str6 is " + (str5 == str6)); 
  22.  
  23.   }
  24. }  

                                                                      
      
Output:


  1. str1 and str2 : literal 
  2. str1 == str2 is true. 
  3. str3 and str4 : new operator str3 == str4 is false. 
  4. str5 and str6 : expression 
  5. str5 == str6 is true.

       
                                                                                                                                        

String is immutable. What exactly is the meaning??

  • String is immutable means that you cannot change the object itself, but you can change the reference to the object. 
  •  String a="a";
           a = "str";
  • When you called a = "str", you are actually changing the reference of a to a new object created by the String literal "str". 
  • Changing an object means to use its methods to change one of its fields (or the fields are public and not final, so that they can be updated from outside without accessing them via methods)
  • String str="smiley";
    str=str+"bird";
    here new String object will be created.

Why Strings are immutable in java?

  • Security: Parameters are typically represented as String in network connections, database connection urls, usernames/passwords etc. If it were mutable, these parameters could be easily changed.
  • Synchronization and concurrency: making String immutable automatically makes them thread safe thereby solving the synchronization issues.
  • Caching: when compiler optimizes your String objects, it sees that if two objects have same value (a="test", and b="test") and thus you need only one string object (for both a and b, these two will point to the same object).
  • Class loading: String is used as arguments for class loading. If mutable, it could result in wrong class being loaded (because mutable objects change their state).

How to prove Strings are immutable?


  1. package com.instanceofjava;
  2.  
  3. public class StringImmutableDemo {
  4. public static void main(String[] args) {
  5.  
  6. String s1="Java";
  7. String s2 = "Rocks!";
  8.  
  9. System.out.println("The hascode of s1 = " + s1.hashCode());
  10. System.out.println("The hascode of s2 = " + s2.hashCode());
  11.  
  12. s1=s1 + s2;
  13.  
  14. System.out.println("The hascode [AFTER] s1 is changed = " + s1.hashCode());
  15.  
  16. }

 Output:


  1. The hascode of s1 = 2301506
  2. The hascode of s2 = -1841810349
  3. The hascode [AFTER] s1 is changed = 1248336149

String class constructors:

  • String class has 8 important constructors.

1.String():

  • Creates empty string object.

2.String(String value):

  •  Creates String objects with the string value

3.String(StringBuffer sb):

  • Creates String object with the given StringBuffer object.

4. String(StringBuilder sb):

  • Creates String object with the given StringBuilder object.

5.String(char[] ch):

  •  Creates String object  with the given array values.

6.String(char ch, int offset, int count):

  • Creates String object with the given array values start with offset by including with the  given count of characters.

7.String(byte[] b):

  • Creates String object with the given byte array values.

8.String(byte[] b, int offset, int count):

  • Creates String object with the given byte array values starts with offset by including with the given count of bytes

String methods:

1.isEmpty():

  • This method used to check whether String is empty or not

 2.length():

  • To find the length of given string.
  1. package com.instanceofjavaforus;
  2. public Class StringMethodsDemo{
  3. public static void main (String args[]) {
  4. String str="";
  5. System.out.println(str.isEmpty()) ;
  6. System.out.println(str.length());
  7. }
  8. }
  9. Output: 
  10. true
  11. 0

3.equals();


  • To compare two strings

4.compareTo():

  • To Compare two string objects lexicographically, means after comparison method should return difference between string content

5.compareToIgnoreCase():

  • To Compare two string objects lexicographically, means after comparison method should return difference between string content ignores case.
  1. package com.instanceofjavaforus;
  2. public Class StringMethodsDemo{
  3. public static void main (String args[]) {
  4. String str1="abc";
  5. String str2= new String("abc")
  6. System.out.println(str1.equals(str2)) ;
  7. String str3="a";
  8. String str4="A";
  9. System.out.println(str3.compareTo(str4)) ;
  10. String str5="a";
  11. String str6="A";
  12. System.ot.println(str3.compareToIgnoreCase(str4)) ;

  13. }
  14. }
  15. Output: 
  16. true
  17. 32
  18. 0

6.7. startsWith(), endsWith():

  • To check whether the string starts with specified string or ends with specified string
  1. package com.instanceofjavaforus;
  2. public Class StringMethodsDemo{

  3. public static void main (String args[]) {

  4. String str1="Java programming language";
  5. System.out.println(str1.startsWith("Java"));
  6. System.out.println(str1.endsWith("java"));

  7. }
  8. }
  9. Output: 
  10. true
  11. false

8.charAt(int index);

  • To find character at given index
  1. package com.instanceofjavaforus;
  2. public Class StringMethodsDemo{

  3. public static void main (String args[]) {

  4. String str1="Java";
  5. System.out.println(str1.charAt(1));
  6. System.out.println(str1.charAt(3));

  7. }
  8. }
  9. Output: 
  10. a
  11. a

9.indexOf(char ch):

  • Returns first occurrence of  given character
  1. package com.instanceofjavaforus;
  2. public Class StringMethodsDemo{

  3. public static void main (String args[]) {

  4. String str1="Java";
  5. System.out.println(str1.indexOf("J"));
  6. System.out.println(str1.indexOf("B"));

  7. }
  8. }
  9. Output: 
  10. 0
  11. -1



Select Menu