Multiply two matrices

  1. package com.instanceofjava;
  2.  
  3. import java.util.Scanner;
  4.  
  5. class Multiply2Matrices{
  6.  
  7.    public static void main(String args[])
  8.    {
  9.  
  10.       int m, n, p, q, sum = 0, c, d, k;
  11.  
  12.       Scanner in = new Scanner(System.in);
  13.  
  14.       System.out.println("Enter the number of rows and columns of first matrix");
  15.  
  16.       m = in.nextInt();
  17.       n = in.nextInt();
  18.  
  19.       int first[][] = new int[m][n];
  20.  
  21.      System.out.println("Enter the elements of first matrix");
  22.  
  23.       for ( c = 0 ; c < m ; c++ )
  24.          for ( d = 0 ; d < n ; d++ )
  25.             first[c][d] = in.nextInt();
  26.  
  27.       System.out.println("Enter the number of rows and columns of second matrix");
  28.  
  29.       p = in.nextInt();
  30.       q = in.nextInt();
  31.  
  32.      if ( n != p )
  33.          System.out.println("Matrices with entered orders can't be multiplied with each other.");
  34.       else
  35.       {
  36.          int second[][] = new int[p][q];
  37.          int multiply[][] = new int[m][q];
  38.          System.out.println("Enter the elements of second matrix");
  39.  
  40.          for ( c = 0 ; c < p ; c++ )
  41.             for ( d = 0 ; d < q ; d++ )
  42.                second[c][d] = in.nextInt();
  43.  
  44.          for ( c = 0 ; c < m ; c++ )
  45.          {
  46.             for ( d = 0 ; d < q ; d++ )
  47.             {   
  48.                for ( k = 0 ; k < p ; k++ )
  49.                {
  50.                   sum = sum + first[c][k]*second[k][d];
  51.                }
  52.                multiply[c][d] = sum;
  53.                sum = 0;
  54.             }
  55.          }
  56.  
  57.          System.out.println("Multiplication of entered matrices:-");
  58.  
  59.          for ( c = 0 ; c < m ; c++ )
  60.          {
  61.             for ( d = 0 ; d < q ; d++ )
  62.                System.out.print(multiply[c][d]+"\t");
  63.             System.out.print("\n");
  64.          }
  65.  
  66.       }
  67.  
  68.    }
  69. }  

OutPut:


  1. Enter the number of rows and columns of first matrix
  2.  
  3. 2 2
  4.  
  5. Enter the elements of first matrix
  6.  
  7. 2 2
  8. 2 3
  9.  
  10. Enter the number of rows and columns of second matrix
  11.  
  12. 2 2
  13.  
  14. Enter the elements of second matrix
  15.  
  16. 1 1
  17. 1 1
  18.  
  19. Multiplication of entered matrices:-
  20.  
  21. 4    4    
  22. 5    5  


add two matrices

  1. package com.instanceofjava;
  2.  
  3. import java.util.Scanner;
  4.  
  5. class Add2Matrix
  6. {
  7.  
  8.    public static void main(String args[])
  9.    {
  10.  
  11.       int rows, cols, c, d;
  12.  
  13.       Scanner in = new Scanner(System.in);
  14.  
  15.       System.out.println("Please Enter number of rows and columns");
  16.  
  17.       rows = in.nextInt();
  18.       cols  = in.nextInt();
  19.  
  20.       int first[][] = new int[rows][cols];
  21.       int second[][] = new int[rows][cols];
  22.       int sum[][] = new int[rows][cols];
  23.  
  24.       System.out.println("Please Enter elements of first matrix");
  25.  
  26.       for (  c = 0 ; c < rows ; c++ )
  27.          for ( d = 0 ; d < cols ; d++ )
  28.             first[c][d] = in.nextInt();
  29.  
  30.       System.out.println("Please Enter elements of second matrix");
  31.  
  32.       for ( c = 0 ; c < rows ; c++ )
  33.          for ( d = 0 ; d < cols ; d++ )
  34.             second[c][d] = in.nextInt();
  35.  
  36.       for ( c = 0 ; c < rows ; c++ )
  37.          for ( d = 0 ; d < cols ; d++ )
  38.              sum[c][d] = first[c][d] + second[c][d];  //replace '+' with '-' to subtract matrices
  39.  
  40.       System.out.println("Sum of entered matrices:-");
  41.  
  42.       for ( c = 0 ; c < rows ; c++ )
  43.       {
  44.          for ( d = 0 ; d < cols ; d++ )
  45.             System.out.print(sum[c][d]+"\t");
  46.          System.out.println();
  47.       }
  48.    }

  49.  }
  50.    
     

 

Output:

  1. Please Enter number of rows and columns
  2.  
  3. 3
  4. 3
  5.  
  6. Please Enter elements of first matrix
  7.  
  8. 1 1 1
  9. 1 1 1
  10. 1 1 1
  11.  
  12. Please Enter elements of second matrix
  13.  
  14. 2 2 2
  15. 2 2 2
  16. 2 2 2
  17.  
  18. Sum of entered matrices:-
  19.  
  20. 3    3    3    
  21. 3    3    3    
  22. 3    3    3  

You might like:



Sort ArrayList in descending order

Descending order:

  1. package com.instanceofjavaforus;
  2. import java.util.ArrayList;
  3.  import java.util.Collections;
  4. import java.util.Comparator;
  5.  
  6. public class SortArrayListDesc {
  7.  
  8.      public static void main(String[] args) {
  9.  
  10.             //create an ArrayList object
  11.             ArrayList arrayList = new ArrayList();
  12.  
  13.             //Add elements to Arraylist
  14.             arrayList.add(1);
  15.             arrayList.add(2);
  16.             arrayList.add(3);
  17.            arrayList.add(4);
  18.             arrayList.add(5);
  19.             arrayList.add(6);
  20.  
  21.             /*
  22.            Use static Comparator reverseOrder() method of Collections 
  23.         utility class to get comparator object
  24.            */
  25.  
  26.          Comparator comparator = Collections.reverseOrder();
  27.  
  28.           System.out.println("Before sorting  : "  + arrayList);
  29.         
  30.  
  31.            /*
  32.               use
  33.               static void sort(List list, Comparator com) method of Collections class.
  34.             */
  35.  
  36.             Collections.sort(arrayList,comparator);
  37.             System.out.println("After sorting  : + arrayList);
  38.  
  39.        }
  40.     }
     

  1. OutPut:
  2. Before sorting  : [1, 2, 3, 4, 5, 6]
  3. After sorting  : [6, 5, 4, 3, 2, 1]
     

Ascending order:


  1. package com.instanceofjavaforus;
  2. import java.util.ArrayList;
  3.  import java.util.Collections;
  4. import java.util.Comparator;
  5.  
  6. public class SortArrayListAsc{
  7.  
  8.      public static void main(String[] args) {
  9.  
  10.             //create an ArrayList object
  11.             ArrayList arrayList = new ArrayList();
  12.  
  13.             //Add elements to Arraylist
  14.             arrayList.add(10);
  15.             arrayList.add(4);
  16.             arrayList.add(7);
  17.            arrayList.add(2);
  18.             arrayList.add(5);
  19.             arrayList.add(3);
  20.  
  21.           
  22.  
  23.           System.out.println("Before sorting  : "  + arrayList);
  24.         
  25.  
  26.            /*
  27.               use
  28.               static void sort(List list) method of Collections class.
  29.             */
  30.  
  31.             Collections.sort(arrayList);
  32.             System.out.println("After sorting  : + arrayList);
  33.  
  34.        }
  35.     }
     



  1. OutPut:
  2. Before sorting  : [10, 4, 7, 2, 5, 3]
  3. After sorting  : [2, 3, 4, 5, 7, 10]

Arraylist add element at specific index

  1. package com.instanceofjavaforus;
  2. import java.util.ArrayList;
  3.  
  4. public class AddElementAtSpecifiedIndex {
  5.  
  6.     public static void main(String[] args) {
  7.  
  8.        //create an ArrayList object
  9.         ArrayList arrayList = new ArrayList();
  10.  
  11.         //Add elements to Arraylist
  12.         arrayList.add("a");
  13.         arrayList.add("b");
  14.         arrayList.add("c");
  15.         arrayList.add("d");
  16.         arrayList.add("f");
  17.         arrayList.add("g");
  18.  
  19.         arrayList.add(1,"Y");
  20.  
  21.         System.out.println("ArrayList values...");
  22.  
  23.         //display elements of ArrayList
  24.         for(int index=0; index < arrayList.size(); index++)
  25.           System.out.println(arrayList.get(index));
  26.        arrayList.add(2,"Z");
  27.  
  28.     System.out.println("ArrayList values...");
  29.  
  30.         //display elements of ArrayList
  31.        for(int index=0; index < arrayList.size(); index++)
  32.           System.out.println(arrayList.get(index));
  33.       }
  34.  
  35. }
  36. }
     

  1. OutPut:
  2. ArrayList values...
  3. a
  4. Y
  5. b
  6. c
  7. d
  8. f
  9. g
  10. ArrayList values...
  11. a
  12. Y
  13. Z
  14. b
  15. c
  16. d
  17. f
  18. g
     

Print 1 to 10 without using loop in java?

  •  Basically to display numbers from 1 to 10 or a series we will use for , while or do while loop
  • So here is the programs to do same thing without using loop.
  • This is possible in two ways
  • First one is to display by printing all those things using system.out.println.
  • second one is by using recursive method call lets see these two programs

Solution #1:


  1. package com.instanceofjavaTutorial;
  2.  
  3. class Demo{  
  4.  
  5. public static void main(String args[]) { 

  6.    System.out.println(1);
  7.    System.out.println(2);
  8.    System.out.println(3);
  9.    System.out.println(4);
  10.    System.out.println(5);
  11.    System.out.println(6);
  12.    System.out.println(7);
  13.    System.out.println(8);
  14.    System.out.println(9);
  15.    System.out.println(10);
  16.  
  17. }

  18. }

Output:

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10



Solution #2


  1. package com.instanceofjavaTutorial; 
  2. public class Main {
  3.     public static void main(String[] args) {
  4.         printNumbers(1, 10);
  5.     }

  6.     public static void printNumbers(int start, int end) {
  7.         if (start > end) {
  8.             return;
  9.         }
  10.         System.out.println(start);
  11.         printNumbers(start + 1, end);
  12.     }
  13. }
  • This uses recursion to achieve the same result. In this example, the method printNumbers is called with the start and end numbers as arguments. Inside the method, it checks if the start number is greater than the end number and if so, it returns (ends the recursion). 
  • If not, it prints the current start number and then calls the printNumbers method again with the start number incremented by 1. 
  • This continues until the start number is greater than the end number and the recursion ends.
  1. package com.instanceofjavaTutorial; 
  2. class PrintDemo{
  3.  
  4. public static void recursivefun(int n) 
  5.  
  6.   if(n <= 10) {
  7.  
  8.        System.out.println(n); 
  9.          recursivefun(n+1);   }
  10. }
  11.  
  12. public static void main(String args[]) 
  13. {
  14.  
  15. recursivefun(1); 
  16.  
  17.  }
  18.  
  19. }




Output:

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10

Convert values of a Map to a List

Java How To Convert Map Values To List In Java Some Different Ways Below are some common methods for doing so:

1. How to use values() with ArrayList

You can convert the values of a Map to a List in Java using various approaches. 

below are a few common methods:

1. Using ArrayList andvalues()

import java.util.*;

public class MapToListExample {
    public static void main(String[] args) {
        Map<Integer, String> map = new HashMap<>();
        map.put(1, "Apple");
        map.put(2, "Banana");
        map.put(3, "Cherry");

        // Convert values to List
        List<String> list = new ArrayList<>(map.values());

        System.out.println(list);  // Output: [Apple, Banana, Cherry]
    }
}

2. Using Java 8 Stream API

import java.util.*;
import java.util.stream.Collectors;

public class MapToListExample {
    public static void main(String[] args) {
        Map<Integer, String> map = Map.of(1, "Apple", 2, "Banana", 3, "Cherry");

        // Convert values to List using Stream
        List<String> list = map.values().stream().collect(Collectors.toList());

        System.out.println(list);  // Output: [Apple, Banana, Cherry]
    }
}

3. Using forEach Loop

import java.util.*;

public class MapToListExample {
    public static void main(String[] args) {
        Map<Integer, String> map = new HashMap<>();
        map.put(1, "Apple");
        map.put(2, "Banana");
        map.put(3, "Cherry");

        List<String> list = new ArrayList<>();
        map.values().forEach(list::add);

        System.out.println(list);  // Output: [Apple, Banana, Cherry]
    }
}

💡 Choose the method based on your Java version:

  • Use ArrayList<>(map.values()) for simple cases.
  • Use Stream API (map.values().stream().collect(Collectors.toList())) in Java 8+ for a functional approach.
  • Use a forEach loop if modifying the list during iteration.


  1. package com.instanceofjavaforus;

  2. import java.util.ArrayList;
  3. import java.util.HashMap;
  4. import java.util.List;
  5. import java.util.Map;
  6.  
  7. public class MapValueToList {
  8.  
  9.  Map<Integer, String> map;
  10.  
  11.  public MapKeyToList(Map<Integer, String> map) {
  12.       this.map = map;
  13.  }
  14.  public List<String> convertValuesToList() {
  15.     return new ArrayList(map.values());
  16.  }
  17.  
  18.  public static void main(String[] args) {           
  19.  Map<Integer, String> map = new HashMap<>();
  20.  
  21.     map.put(1, "one");
  22.     map.put(2, "two");
  23.     map.put(3, "three");
  24.     map.put(4, "Four");
  25.     map.put(5, "Five");
  26.     map.put(6, "Six");
  27.     map.put(7, "Seven");
  28.     map.put(8, "Eight");
  29.     map.put(9, "Nine");
  30.     map.put(10, "Ten");
  31.  
  32.      MapValueToList  conv = new MapValueToList (map);
  33.      List<String> keysList = conv.convertValuesToList();
  34.      System.out.println("Values:");
  35.     for (String val : keysList) {
  36.        System.out.println(val);
  37. }
  38.  
  39.  }
  40. }
  41. OutPut:
  42. Values:
  43. one
  44. two
  45. three
  46. Four
  47. Five
  48. Six
  49. Seven
  50. Eight
  51. Nine
  52. Ten

     


Remove duplicates from an array java

Removing duplicate elements form an array using collections:

  1. package com.instanceofjavaTutorial;
  2.  
  3. import java.util.Arrays;
  4. import java.util.HashSet;
  5. import java.util.List;
  6. import java.util.Set;
  7.  
  8. public class RemoveDupArray {
  9.  
  10.   public static void main(String[] args) {
  11.  
  12.   // A string array with duplicate values
  13.    String[] data = { "E", "C", "B", "E", "A", "B", "E", "D", "B", "A" };
  14.  
  15. System.out.println("Original array         : " + Arrays.toString(data));
  16.  
  17.  List<String> list = Arrays.asList(data);
  18.  Set<String> set = new HashSet<String>(list);
  19.  
  20.   System.out.print("After removing duplicates: ");
  21.   String[] resarray= new String[set.size()];
  22.    set.toArray(resarray);
  23.  
  24.  for (String ele: resarray) {
  25.  
  26.  System.out.print(ele + ", ");
  27.  
  28.  }
  29.  
  30. }
  31.  
  32. }



  1. OutPut:
  2. Original array         : [E, C, B, E, A, B, E, D, B, A]
  3. After removing duplicates: D, E, A, B, C




You Might Like:

1. Java Interview Programs On Core Java

2. Java Interview Programs On Collections 

3. What is The Output Of Following Programs Java Interview:

4. Java Concept and Example Program

Collections Map

Map:
  • Map is key-value pair.
  • Map Interface represents a mapping between key and value.
  • Map having:
  1. HashMap
  2. LinkedHashMap
  3. HashaTable
  4. TreeMap

HashMap:
  • HashMap is not synchronized.
  • Hashmap allows one key null and multiple null values.
  • HashMap default capacity is :
static final int DEFAULT_INITIAL_CAPACITY =16 static final float DEFAULT_LOAD_FACTOR = 0.75f;
Program for HashMap:

package com.instanceofjava;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

public class Hashmap2 {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
HashMap map=new HashMap();
map.put(1, "indhu");
map.put("d", "sindhu");
map.put("3", "swathi");
map.put(null, "indhira");
map.put(null, "indhira");
map.put(4, "sindhu");
if(!map.isEmpty()){
Iterator it=map.entrySet().iterator();
while(it.hasNext()){
Map.Entry obj=(Entry) it.next();
System.out.println(obj.getValue());
}
}
}


Output:
indhira
swathi
indhu
sindhu
sindhu

HashTable:
  • HashTable is synchronized.
  • HashTable doesn't allow any null key or any null values.
  • HasTable Default capacity:
static final int DEFAULT_INITIAL_CAPACITY = 11;static final float DEFAULT_LOAD_FACTOR = 0.75f;
Program for HashTable:

package com.instanceofjava;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

public class Hashtable3{

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Hashtable hashTable=new Hashtable();
hashTable.put(1, "indhu");
hashTable.put("d", "sindhu");
hashTable.put("3", "swathi");
hashTable.put("d", "sindhu");
if(!hashTable.isEmpty()){
Iterator it=hashTable.entrySet().iterator();
while(it.hasNext()){
Map.Entry obj=(Entry) it.next();
System.out.println(obj.getValue());
}


}
}

}


Output:
swathi
sindhu
indhu

TreeMap:

  • TreeMap is sorted order.
  • TreeMap doesn't allow null key or null values.



Program for TreeMap:

package com.instanceofjava;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

public class Employee{

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
TreeMap treeMap=new TreeMap();
treeMap.put("g", "indhu");
treeMap.put("d", "sindhu");
treeMap.put("3", "swathi");
treeMap.put("d", "sindhu");
if(!treeMap.isEmpty()){
Iterator it=treeMap.entrySet().iterator();
while(it.hasNext()){
Map.Entry obj=(Entry) it.next();
System.out.println(obj.getValue());
}


}
}

}

Output:

swathi
sindhu
indhu



Producer consumer problem


Common   class
package com.instanceofjavaforus;

public class Common {

    int x;
   
    boolean flag=true;
    //if flag is true producer thread has to produce
    // if flag is false consumer thread has to produce

    synchronized public void produce(int i){
       
        if(flag){
           
            x=i;
            System.out.println("producer thread has produced "+i);
            flag=false;
            notify();
            try {
                wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }      
        }
     }
   

    synchronized public int consume(){
        if(flag){
            try {
                wait();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
           
        }
        flag=true;
        notify();
        return x;
    }
   
}

package com.instanceofjavaforus;

public class ProducerThread extends Thread {
    Common c;
   
    ProducerThread(Common c){
        this.c=c;
    }
   
    public void run(){
        int i=0;
        while(true){
           
            i++;
            c.produce(i);
           
           
            try {
                Thread.sleep(600);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } 
        } 
    } 
}

ConsumerThread:

package com.instanceofjavaforus;

public class ConsumerThread extends Thread {
   
    Common c;
   
    ConsumerThread(Common c){
        this.c=c;
    }
   
    public void run(){
       
        while(true){
           
            int x=c.consume();
            System.out.println("Consumer consumes"+x);
            try {
                Thread.sleep(600);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } 
        } 
    }
}

ProducerConsumerTest:

package com.instanceofjavaforus;

public class ProducerConsumerTest {
   
    public static void main(String args[]){
        Common c= new Common();
        ProducerThread pt=new ProducerThread(c);
        ConsumerThread ct= new ConsumerThread(c);
        pt.start();
        ct.start();
    }
}

Output:

producer thread has produced 1
Consumer consumed 1
producer thread has produced 2
Consumer consumed 2
producer thread has produced 3
Consumer consumed 3
producer thread has produced 4
Consumer consumed 4
producer thread has produced 5
Consumer consumed 5
producer thread has produced 6
Consumer consumed 6








Check armstrong number or not


  1. package com.instanceofjavaTutorial; 
  2. import java.util.Scanner;

  3. public class ArmstrongNumber{
  4.  
  5. public static void main(String args[])
  6.  {
  7.  
  8.           int n, sum = 0, temp, r;
  9.  
  10.           Scanner in = new Scanner(System.in);
  11.  
  12.           System.out.println("Enter a number to check if it is an Armstrong number or not");     
  13.           n = in.nextInt();
  14.  
  15.           temp = n;
  16.           while( temp != 0 )
  17.           {
  18.  
  19.              r = temp%10;
  20.              sum = sum + r*r*r;
  21.              temp = temp/10; 
  22.  
  23.           }
  24.  
  25.           if ( n == sum )
  26.              System.out.println(n+"is an Armstrong number.");
  27.           else
  28.              System.out.println(n+"  is not an Armstrong number.");  
  29.        
  30.        }
  31. }


Output:

  1. Enter a number to check if it is an Armstrong number or not
  2. 153
  3. 153is an Armstrong number.



Print numbers in pyramid shape


  1. package com.instanceofjava;
  2.  
  3. public class Pyramidshape {
  4.  
  5.  public static void main(String[] args) {
  6.  
  7.   int num=10;
  8.  
  9.   for (int i = 1; i < num; i++) {
  10.  
  11.    for (int j = 1; j<=num-i;j++) {
  12.  
  13.     System.out.print(" ");
  14.    } 

  15.   for (int k = 1; k <= i; k++) {
  16.    System.out.print(""+k+" ");
  17.   } 

  18.   for (int l =i-1; l >0; l--) {
  19.    System.out.print(""+l+" ");
  20.   } 

  21.    System.out.println();
  22.   }
  23.  
  24. }



 Output:

  1.  1
  2.  1 2 1 
  3.  1 2 3 2 1
  4.  1 2 3 4 3 2 1

Sort object using comparator

  1. package com.instanceofjava;
  2.  
  3. public class Employee 
  4. {
  5.  
  6.  int id;
  7.  String name;
  8.  
  9.  public Employee(int id, String name) {
  10.  
  11.   this.id=id;
  12.   this.name=name;
  13.  
  14.  }
  15.  
  16. public int getId() {
  17.  
  18. return id;
  19.  
  20. }
  21.  
  22.  public void setId(int id) {
  23.   this.id = id;
  24.  }
  25.  
  26.  public String getName() {
  27.   return name;
  28.  }
  29.  
  30. public void setName(String name) {
  31.  
  32.   this.name = name;
  33.  
  34. }
  35.  
  36. }


  1. class MyEmpComp implements Comparator<Employee >
  2.  
  3.  @Override
  4.  public int compare(Employee e1, Employee e2) {
  5.  
  6.         if(e1.getName() < e2.getName()){
  7.             return 1;
  8.         } else {
  9.             return -1;
  10.         }
  11.  
  12. }
  13.  
  14. }




  1. package com.oops;
  2.  
  3. import java.util.ArrayList;  
  4. import java.util.Collections;
  5. import java.util.Iterator;
  6.  
  7. import java.io.*;  
  8.  
  9. class Main{  
  10.  
  11. public static void main(String args[]){  
  12.  
  13. ArrayList al=new ArrayList();  
  14.  
  15. al.add(new Employee(101,"Indhu"));  
  16. al.add(new Employee(106,"Sindhu"));  
  17. al.add(new Employee(105,"Swathi"));
  18.   
  19. Collections.sort(al,MyEmpComp );  
  20.  
  21. Iterator itr=al.iterator();  
  22.  
  23. while(itr.hasNext()){   
  24.  
  25. Employee st=(Employee)itr.next();  
  26. System.out.println(st.id +" "+st.name );  
  27.  
  28.   }
  29.  
  30.   
  31. }
  32.  
  33.  


Output:
  1. Indhu
  2. Swathi
  3. Sindhu



Sort object using comparable interface

  1. package com.instanceofjava;
  2.  
  3. import java.util.Comparable;
  4.  
  5. public class Employee implements Comparable<Employee> {
  6.  
  7.  int id;
  8.  String name;
  9.  
  10.  public Employee(int id, String name) {
  11. this.id=id; 
  12. this.name=name;
  13.  }
  14.  
  15.  public int getId() {
  16. return id;
  17.  }
  18.  
  19.  public void setId(int id) {
  20.   this.id = id;
  21.  }
  22.  
  23.  public String getName() {
  24. return name;
  25.  }
  26.  
  27.  public void setName(String name) {
  28.   this.name = name;
  29.  }
  30.  
  31.  @Override
  32.  public int compareTo(Employee e) {
  33.  
  34.  Integer i= this.getId();
  35.  Integer j=e.getId();
  36.  
  37.      if (this.getId() == e.getId())
  38.        return 0;
  39.       if (this.getId() < e.getId())
  40.         return 1;
  41.       if (this.getId() > e.getId())
  42.        return -1;
  43.       return 0;
  44. }
  45. }

  1. package com.oops;
  2. import java.util.ArrayList;
  3. import java.util.Collections;
  4. import java.util.Iterator;
  5. import java.io.*;
  6.   class Main{  
  7.  
  8. public static void main(String args[]){
  9.  
  10.  ArrayList al=new ArrayList();  
  11.  
  12.  al.add(new Employee(101,"Indhu"));
  13. al.add(new Employee(106,"Sindhu"));
  14.  al.add(new Employee(105,"Swathi"));  
  15. Collections.sort(al);
  16.  
  17. Iterator itr=al.iterator();   
  18.  
  19. while(itr.hasNext()){
  20.  
  21.    Employee st=(Employee)itr.next();
  22.    System.out.println(st.id +" "+st.name );   
  23.  
  24.   } 
  25. }  
  26.  
  27. }  
Output:
  1. Indhu 
  2. Swathi 
  3. Sindhu

 

Method overriding example program


  1. package com.oops; 
  2.  
  3. class A
  4.  
  5. void msg(){
  6.  
  7.  System.out.println("Hello");
  8.  
  9.  
  10. }

  1. class B extends A
  2. {
  3.  
  4.  void msg(){
  5.  
  6. System.out.println("Welcome");
  7.  
  8. }
  9.  
  10. public static void main(String args[])
  11.  
  12.     A a=new A();
  13.     B b=new B();
  14.      A obj=new B(); 
  15.  
  16.    System.out.println(a.msg());   //   Hello
  17.         System.out.println(obj.msg());  // Welcome
  18.         System.out.println(b.msg());   //Welcome
  19.  
  20. }  





Output:
  1. Hello
  2. Welcome 
  3. Welcome



Object cloning in java example

  1. package com.instanceofjava;
  2.  
  3. public class Employee implements Cloneable {
  4.  
  5.         int a=0; 
  6.         String name="";
  7.         Employee (int a,String name){ 
  8.         this.a=a;
  9.         this.name=name;
  10. }
  11.  
  12. public Employee clone() throws CloneNotSupportedException{
  13.  
  14. return (Employee ) super.clone();
  15.  
  16. }
  17.  
  18. public static void main(String[] args) {
  19.  
  20.           Employee e=new Employee (2,"Indhu");
  21.             System.out.println(e.name);
  22.  
  23. try {
  24.  
  25.  Employee b=e.clone();
  26.  System.out.println(b.name);
  27.  
  28. }
  29.  catch (CloneNotSupportedException e1) {

  30. e1.printStackTrace();
  31. }
  32. }
  33.  
  34. }




Output:
  1. Indhu
  2. Indhu

Sort integer array using Bubble Sort in java

  1. package com.instaceofjava;
  2.  
  3. public class Bubblesort {
  4.  
  5. public static void main(String[] args) {  
  6.  
  7. int a[]={23,5,6,66,1};
  8.  
  9. int n=a.length;
  10.  
  11.         int temp=0;
  12.  
  13. for(int i=0;i<n;i++){
  14.  
  15. for(int j=1;j<(n-i);j++){
  16.  
  17. if(a[j-1]>a[j]){
  18.    temp=a[j];
  19.   a[j]=a[j-1];
  20.   a[j-1]=temp;
  21.  
  22.   }  
  23.  
  24. }
  25.  
  26. }
  27.  
  28. for(int k=0;k<n;k++){
  29. System.out.println(a[k]);


  30. }



Output:
  1. 1,
  2. 5
  3. 6
  4. 23
  5. 66


How to find largest element in an array with index and value using array?


  • Lets see an example program to get largest element in an integer array. and also find second largest element in the same array.


  1. package com.instanceofjava; 
  2. public class Array {
  3.  
  4. public static void main(String[] args) {
  5.  
  6. int arr[]={1,120,56,78,87};
  7. int largest=arr[0];
  8. int smallest=arr[0];
  9. int small=0;
  10. int index=0;
  11.  
  12. for(int i=1;i<arr.length;i++){
  13.  
  14. if(arr[i]>largest){
  15.  
  16. largest=arr[i];
  17. index=i;
  18.  
  19. }
  20. else if(smallest>arr[i]){
  21.  
  22. smallest=arr[i];
  23. small=i;
  24.  
  25. }
  26. }
  27.  
  28. System.out.println(largest);
  29. System.out.println(index);
  30. System.out.println(smallest);
  31. System.out.println(small);
  32.  

  33. }


Output:
  1. 120
  2. 1
  3. 87
  4. 4


How to Add elements to hash map and Display?


  1. package com.instaceofjava; 
  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 Mapiterator {
  9.  
  10. public static void main(String[] args) {
  11.  
  12. HashMap map=new HashMap();
  13.  
  14. map.put(1, "indhu");
  15. map.put("d", "sindhu");
  16. map.put("3", "swathi");
  17.  
  18. if(!map.isEmpty()){
  19.  
  20. Iterator it=map.entrySet().iterator();
  21.  
  22. while(it.hasNext()){
  23.  
  24. Map.Entry obj=(Entry) it.next();
  25. System.out.println(obj.getValue());
  26.  
  27. }
  28.  
  29. }
  30.  
  31. }
  32.  
  33. }


Output:

  1. swathi 
  2. indhu
  3. sindhu

Count the number of occurrences of a character in a String?

  1. package com.instaceofjava; 
  2.  
  3. public class StringCount {
  4.  
  5. public static void main(String[] args)
  6. {
  7.  
  8. String str = "abcdcabcdacbdadbca";
  9.  
  10.     String findStr = "b";
  11.     int lastIndex = 0;
  12.     int count = 0;
  13.  
  14.     while (lastIndex != -1) {
  15.  
  16.     lastIndex = str.indexOf(findStr, lastIndex);
  17.  
  18.     if (lastIndex != -1) {
  19.     count++;
  20.     lastIndex += findStr.length();
  21.  
  22.     }
  23.     }
  24.     System.out.println(count);
  25. }
  26.  
  27. }


Output:
  1. 4

Sorting string without using string Methods?


  1. package com.Instanceofjava; 
  2. public class SortString {
  3.  
  4. public static void main(String[] args) {
  5.  
  6. String original = "edcba";
  7. int j=0;
  8. char temp=0;
  9.  
  10.   char[] chars = original.toCharArray();
  11.  
  12.   for (int i = 0; i <chars.length; i++) {
  13.  
  14.       for ( j = 0; j < chars.length; j++) {
  15.  
  16.        if(chars[j]>chars[i]){
  17.             temp=chars[i];
  18.            chars[i]=chars[j];
  19.            chars[j]=temp;
  20.        }
  21.  
  22.    }  
  23.  
  24. }
  25.  
  26. for(int k=0;k<chars.length;k++){
  27. System.out.println(chars[k]);
  28. }
  29.  
  30. }
  31.  
  32. }





Output:
  1. abcde


Select Menu