Single Post

Header

Saturday, September 7, 2024

Java Collections - Sep 2024

What is the difference between hashset and hashmap ? 

  1. Hashset implements Set interface, where as HashMap implements Map interface

  2. Hashset stores individual objects, HashMap stores key based values

  3. Hashset does not allow duplicate elements, HashMap does not allow keys, but it contains duplicate values

  4. Hashset allows only one null value, HashMap allows one null key and multiple null values


HashMap and Hashtable : 

// Java HashMap class implements the Map interface which allows us to store key and value pair, where keys should be unique.

// You cannot store duplicate keys in HashMap. However, if you try to store duplicate key with another value, it will replace the value.

// HashMap is non synchronized. It is not-thread safe and can't be shared between many threads without proper synchronization code.

// Hashtable is synchronized. It is thread-safe and can be shared with many threads.

// Hashtable allows one null key and multiple null values.

// Hashtable doesn't allow any null key or value.


import java.util.*;

import java.util.HashMap;

import java.util.Map;

class HashMapExample {

    

    public static void main(String[] args) {

      HashMap<Integer, String> hashMap = new HashMap<Integer, String>();

      hashMap.put(456, "abcd");

      hashMap.put(234, "bcde");

      hashMap.put(4574, "cdef");

      hashMap.put(456, "xyz");

      hashMap.put(null, "jkl");

       hashMap.put(563, null);

        hashMap.put(897, null);

      

      System.out.println("Iterating Hashmap...");  

       System.out.println(hashMap.entrySet());   

   for(Map.Entry m : hashMap.entrySet()){    

    System.out.println(m.getKey()+" "+m.getValue());    

   }  

   

    System.out.println(hashMap.keySet());   

   for(Integer i : hashMap.keySet()) {    

     System.out.println(hashMap.get(i));    

   } 

   

    Hashtable<Integer, String> hashTable = new Hashtable<Integer, String>();

      hashTable.put(456, "abcd");

      hashTable.put(234, "bcde");

      hashTable.put(4574, "cdef");

      hashTable.put(456, "xyz");

    //   hashTable.put(null, "jkl");

    //   hashTable.put(563, null);

    //     hashTable.put(897, null);

      

      System.out.println("Iterating Hashmap...");  

       System.out.println(hashTable.entrySet());   

   for(Map.Entry m : hashTable.entrySet()){    

    System.out.println(m.getKey()+" "+m.getValue());    

   }  

   

    System.out.println(hashTable.keySet());   

   for(Integer i : hashTable.keySet()) {    

     System.out.println(hashTable.get(i));    

   } 

    }

}


Output : 

Iterating Hashmap...

[null=jkl, 897=null, 563=null, 456=xyz, 234=bcde, 4574=cdef]

null jkl

897 null

563 null

456 xyz

234 bcde

4574 cdef

[null, 897, 563, 456, 234, 4574]

jkl

null

null

xyz

bcde

cdef

Iterating Hashmap...

[4574=cdef, 456=xyz, 234=bcde]

4574 cdef

456 xyz

234 bcde

[4574, 456, 234]

cdef

xyz

bcde



List Program : 

 import java.util.*;  

public class Main {  

 public static void main(String args[]){  

  List<String> list1=new ArrayList<String>();//Creating arraylist  

  list1.add("abcd");//Adding object in arraylist    

  list1.add("defg"); 

  // list1.add(1);  // syntax error

  list1.add("bcde");

  list1.add("bcde");

  list1.add("bcde");

  //Traversing list through for-each loop  

  System.out.println("old list ");   

  for(String s:list1)    

    System.out.println(s);    

  

  // Remove list value

  list1.remove("bcde");

  list1.remove(2);

  System.out.println("\n after remove list"); 

  for(String s:list1)    

    System.out.println(s); 

    

    // Sort the list

    Collections.sort(list1);

    System.out.println("\n after sort list"); 

    for(String s:list1)    

    System.out.println(s); 

    

    // Change list value

    list1.set(1, "xyz");

    System.out.println("\n after change list"); 

     for(String s:list1)    

    System.out.println(s); 

    

    // Get the list values

    System.out.println("\n get the list"); 

    for(int i=0;i<list1.size();i++) {

        System.out.println(list1.get(i)); 

    }

 }  

}   

output : 

old list abcd defg bcde bcde bcde after remove list abcd defg bcde after sort list abcd bcde defg after change list abcd xyz defg get the list abcd xyz defg    

Wednesday, September 4, 2024

Java Programs - Sep, 2024


Basic Java Programs : 

This keyword :

// This keyword is used to refer current class instance variables

// This keyword is used to call current methods and constrcutors


class ThisKeyword {

    int id ;  // These are called instance variables

    String name ; 

    String company ;

    ThisKeyword() {

         System.out.println("this is default constrcutor");

    }

   

   ThisKeyword(int id, String name, String company) {

       this();  // This should be first line inside another constructor

       id =id;

       name = name;

       company = company;

    System.out.println("inside the method id is "+id+ "name is "+name+" company is "+company);

    this.displayinfo();

    }

    void displayinfo() {

        System.out.println("id is "+id+ "name is "+name+" company is "+company);

    }

     void withThisKeyword(int id, String name, String company) {

        

        this.id =id;

        this.name = name;

        this.company = company;

        System.out.println("id is "+id+ "name is "+name+" company is "+company);

        

    }

    

    

    

    public static void main(String[] args) {

     ThisKeyword thisObj = new ThisKeyword(23, "venkat", "abcd");

     thisObj.displayinfo();

     //thisObj.withoutThisKeyword(23, "venkat", "abcd");

     thisObj.withThisKeyword(23, "venkat", "abcd");

     thisObj.displayinfo();

     

    }

}

output : 

this is default constrcutor

inside the method id is 23name is venkat company is abcd

id is 0name is null company is null

id is 0name is null company is null

id is 23name is venkat company is abcd

id is 23name is venkat company is abcd


Static Keyword and Static Method : 

// Static keyword belongs to the class rather than instance of the class

// Static variable belongs to all the objects of the class

// It is used to save memory

// Static method belong to the class rather than pbject of the class

// Static method can be called using class name


class StaticVariableMethodClass {

    int id ;

    String name ; 

    static String company = "abcd"; // will create memory only once

    static int  n1=0;

    int  n2=0;

    

    

   void display(int i, String s) {

       System.out.println("id is "+i+" name is "+s+" company is " +company) ;

   }

   

   void staticvar() {

       n1++;   // If any object changes the value of the static variable, it will retain its value. 

       n2++;

    System.out.println("static n1 is "+n1) ;

    System.out.println("non static n2 is "+n2) ;

   }

   

   

   static void changeStaticvar()

   {

       company = "xyz";

        System.out.println("static method static var " +company) ;

   }

   

     void changeStaticvar1()

   {

       company = "fgh";

        System.out.println("non static method can change the value of static var " +company) ;

   }

    public static void main(String[] args) {

      StaticVariableMethodClass s1 = new StaticVariableMethodClass();

      StaticVariableMethodClass s2 = new StaticVariableMethodClass();

      s1.display(5, "jai");

      s1.staticvar();

      s2.staticvar();

      StaticVariableMethodClass.changeStaticvar();

      StaticVariableMethodClass s3 = new StaticVariableMethodClass();

      s3.changeStaticvar1();

    }

}

Output:

id is 5 name is jai company is abcd

static n1 is 1

non static n2 is 1

static n1 is 2

non static n2 is 1

static method static var xyz

non static method can change the value of static var fgh

Constructor : 

// Constructor is a block codes similar to the method.

// It is called when an instance of the class is created.

// Constructors can be overloaded like methods

// Constructor does not have any return type

class ConstructorTest {

    int id ;

    String name ; 

    String college;

    

    ConstructorTest() {

        System.out.println("This is default constrcutor which has no params");

    }

    ConstructorTest(int i, String s) {

        id = i;

        name = s;

        System.out.println("id is : "+i+" name is: "+name);

    }

     ConstructorTest(int i, String s, String c) {

        id = i;

        name = s;

        college = c;

        System.out.println("id is : "+i+" name is: "+name+ " college is: "+college);

    }

    

    public static void main(String[] args) {

       ConstructorTest obj1 = new ConstructorTest(); // default constructor

       ConstructorTest obj2 = new ConstructorTest(12, "venkat"); // parameterrized constructor

        ConstructorTest obj3 = new ConstructorTest(12, "venkat", "abcd");

      

    }

}



Class and Object : 

 // Object is an entity which has state and behaviour

 // Class is collection of objects , it is a template or logical entity

class ClassAndObject {

    int id ;

    String name ; 


    void display(int i, String s) {

        id = i;

        name = s;

        System.out.println("id is : "+i+" name is: "+name);

    }

    

    public static void main(String[] args) {

       

       ClassAndObject obj = new ClassAndObject();

       obj.display(8, "jaivardhan");

       obj.display(9, "havish") ; 

    }

}

output : 

This is default constrcutor which has no params

id is : 12 name is: venkat

id is : 12 name is: venkat college is: abcd


Basic Java Programs

class JavaPrograms {

    

    void palindrome(int n) {

        int original = n;

        int p= 0;

        while(n!=0) {

        int r = n%10;  // 123 -  3. 12- 2

        p = p*10 + r ;  // 30

        n = n/10;

        }

        

        if(p==original) {

            System.out.println("the given number "+original+ " is palindrome");

        }

        else {

            System.out.println("the given number "+original+"  is not a palindrome");

        }

    }

    

    void palindromeString(String s) {

        String rev = "";

        for(int i=s.length()-1;i>=0;i--) {

            rev = rev + s.charAt(i);

        }

       System.out.println("after reverse selenium is : " +rev); 

       

        if(rev.equals(s)) {

            System.out.println("the given string "+s+ " is palindrome");

        }

        else {

            System.out.println("the given string "+s+"  is not a palindrome");

        }

        

    }

    

    void findMaximumNumber(int a[]) {

        int max = a[0];

        for(int i=1; i<a.length; i++) {

            if(max<a[i])

            max=a[i];

        }

         System.out.println("maximum number is : " +max);

    }

    

    void findSmallestNumber(int a[]) {

        int min = a[0];

        for(int i=1; i<a.length; i++) {

            if(min>a[i])

            min=a[i];

        }

         System.out.println("smallest number is : " +min);

    }

    

    void swap(int a, int b) {

        a = a+b ; // 20+30 = 50

        b = a-b;  // 50-30 = 20

        a = a-b;  // 50-20 = 30

        System.out.println("after swap a = "+a+" and b = "+b);

    }

    

     int factorial(int n) {

        int fact =1 ;

        for(int i=2; i<=n; i++) {

            fact = fact * i;

        }

        return fact;

    }

    

    public static void main(String[] args) {

        

    JavaPrograms jp = new JavaPrograms();

    System.out.println("factorial value of 5 is : " + jp.factorial(5));

    jp.swap(20,30);

    int a[] = {34, 45, 12, 67, 54};

    jp.findSmallestNumber(a);

    jp.findMaximumNumber(a);

    jp.palindromeString("selenium");

    jp.palindromeString("malayalam");

    jp.palindrome(1221);

    jp.palindrome(1234);

    

    }

}


factorial value of 5 is : 120

after swap a = 30 and b = 20

smallest number is : 12

maximum number is : 67

after reverse selenium is : muineles

the given string selenium  is not a palindrome

after reverse selenium is : malayalam

the given string malayalam is palindrome

the given number 1221 is palindrome

the given number 1234  is not a palindrome



Java - String, StringBuffer and StringBuilder


 class HelloWorld {

    public static void main(String[] args) {

        String s1 = "hello"; // Strings are immuitable

        String s2 = "hello";  // s1 and s2 points to the same reference

        s1.concat("world");   // s1 does not change because string mutable

        System.out.println("string s1 "+ s1);

        s1.concat("world");

        System.out.println("string s1 after contact: "+ s1);

        

        if(s1==s2) {

          System.out.println("both string objects point to the same reference");

          System.out.println("== references to the reference");

        }

        

        String s3 = new String("hello");

        String s4 = new String("hello");

         if(s3==s4) {

          System.out.println("This will not print, because are not pointing to the same reference");  

        }

        

        if(s1.equals(s2)) {

            System.out.println("\n equals operator checks for the content matches or not");

        }

        

        // StringBuffer and StringBuilder are mutable

        // StringBuffer is  thread safe

        // It is  synchronized

        // If we run the tests in paraller runs

        StringBuffer sb = new StringBuffer("hello string buffer"); // StringBuffer is mutable

    

        System.out.println("sb : " +sb);

        sb.append(" world");

        System.out.println("sb after append: " +sb);

        sb.reverse();

        System.out.println("sb after reverse: " +sb);

        

        StringBuffer sbMethods = new StringBuffer("hello");

        sbMethods.append(" world");

        System.out.println("sb after append: " +sbMethods);

        sbMethods.insert(2, "she");

        System.out.println("sb after insert: " +sbMethods);

        sbMethods.replace(5,7, "aa");

        System.out.println("sb after replace: " +sbMethods);

         sbMethods.deleteCharAt(5);

        System.out.println("sb after delete chat: " +sbMethods);

         sbMethods.reverse();

        System.out.println("sb after reverse: " +sbMethods);

        

        // String Builer is not thread safe

        // It is non synchronized

        // If we run the tests in squence then it is better , not good in paraller runs

        StringBuilder sbuilder = new StringBuilder("hello");

        sbuilder.append(" world");

        System.out.println("sbuilder after append: " +sbuilder);

    }

}


string s1 hello

string s1 after contact: hello

both string objects point to the same reference

== references for the reference


 equals operator checks for the content matches or not

sb : hello string buffer

sb after append: hello string buffer world

sb after reverse: dlrow reffub gnirts olleh

sb after append: hello world

sb after insert: heshello world

sb after replace: hesheaao world

sb after delete chat: hesheao world

sb after reverse: dlrow oaehseh

sbuilder after append: hello world