Tuesday, October 17, 2017

How to make Map Unmodifiable in java collection

Collections class provide a method unmodifiableMap to make our Map unchangeable.
After applying unmodifiableMap() to map if try to put a new value it will throw UnsupportedOperationException.



public class UnmodifiableMapTest {

    public static void main(String[] args) {
      

        Map map=new HashMap();
        map.put(1, "value1");
        map.put(2, "value2");
        Map m=Collections.unmodifiableMap(map);
       
        m.put(3, "value3");
        System.out.println(map);
   
    }

}


Output : -

Exception in thread "main" java.lang.UnsupportedOperationException
    at java.util.Collections$UnmodifiableMap.put(Collections.java:1457)
    at Basic.Animals.main(Animals.java:31)

Object class In Java -all Methods With Complete Signature

Object class In Java -all  Methods With Complete Signature

public native int hashCode();

public boolean equals(Object obj) {
        return (this == obj);
    }

protected native Object clone() throws CloneNotSupportedException;

public String toString() {
        return getClass().getName() + "@" + Integer.toHexString(hashCode());
    }


public final native void notify();

public final native void notifyAll();

public final native void wait(long timeout) throws InterruptedException;

public final void wait(long timeout, int nanos) throws InterruptedException {
        if (timeout < 0) {
            throw new IllegalArgumentException("timeout value is negative");
        }

        if (nanos < 0 || nanos > 999999) {
            throw new IllegalArgumentException(
                                "nanosecond timeout value out of range");
        }

        if (nanos > 0) {
            timeout++;
        }

        wait(timeout);
    }




public final void wait() throws InterruptedException {
        wait(0);
    }


protected void finalize() throws Throwable { }


Monday, October 16, 2017

Sum of given Number till one digit

To find sum of a given number till one digit we need a while loop and the count the sum till we get one digit number.

Ex - Like this num i have - 345678923 , sum of all these number(3+4+5+6+7+8+9+2+3 =47) is 47 so this is not one digit number then again while loop will run and we will get a new sum that(4+7=11) is 11, so again its not one digit so again sum(1+1 =2) now finally we got 2 that is one digit.

345678923 =  3+4+5+6+7+8+9+2+3 = 47 => 4+7 =11 => 1+1=2.
Thats it our program runs fine :)






public class SumNum {

    public static int getSum(long n){
        long remainder;
        int sum=0;
       
        while (n!=0){
            remainder = n%10;
            n=n/10;
            sum+=remainder;
        }
      
        return sum;
    }
    public static void main(String[] args) {

        Scanner scn=new Scanner(System.in);
        long num = scn.nextLong();
        int sum =getSum(num);
        while(sum>9){
            System.out.println(sum);
            sum = getSum(sum);
        }
        System.out.println(sum);
       
    }

}

Friday, August 25, 2017

Basic HIbernate With MYSQL DB

Hi Friends Today i am sharing a basic of Hibernate, How to Store a Student Object In MySql DB Using Hibernate.

I am not explaining so much, follow the steps or copy paste code :P .

Let's Start  : -


hibernate.cfg.xml :

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>

<!-- Related to the connection START -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/test_db?autoReconnect=true&amp;useSSL=false</property>
<property name="connection.user">root</property>
<property name="connection.password">root</property>
<!-- Related to the connection END -->

<!-- Related to hibernate properties START -->
<property name="show_sql">true </property>
<property name="dialet">org.hibernate.dialect.MySQLDialect</property>
<property name="hbm2ddl.auto">update</property>
<!-- Related to hibernate properties END -->

<!-- Related to mapping START -->
<!-- <mapping resource="student.hbm.xml" /> -->
<!-- I am not using here student.hbm.xml file so i commented this, if you want to use you can . I am using annotation class so i declared as below. If you want to use hbm file uncomment the above line -->
 <mapping class="classes.StudentPojo"/>
<!-- Related to the mapping END -->

</session-factory>
</hibernate-configuration>



student.hbm.xml :

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-mapping>
<class name="StudentPojo" table="STUDENTS">

<id name="id" column="SId"  >
<generator class="assigned" />
</id>

<property name="name" column='SName'/>
<property name="mobile"/>

</class>
</hibernate-mapping>



Now create a pojo class :

package classes;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "Student")
public class StudentPojo {

    @Column(name = "SName")
    private String name;
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "Sid")
    private int id;
    private int mobile;
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public int getMobile() {
        return mobile;
    }
    public void setMobile(int mobile) {
        this.mobile = mobile;
    }
}


At last create one class using main method to save Pojo object to MySql DB :

package classes;


import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class SaveStudent {

    public static void main(String[] args)
    {

        Configuration cfg = new Configuration();
        cfg.configure("hibernate.cfg.xml");

        SessionFactory factory = cfg.buildSessionFactory();
        Session session = factory.openSession();
        StudentPojo p=new StudentPojo();

        //p.setId(1);
        p.setName("ABC");
        p.setMobile(1444456724);
       
        StudentPojo p1=new StudentPojo();
       
        //p1.setId(103);
        p1.setName("ABCD");
        p1.setMobile(1444346724);
       
        StudentPojo p2=new StudentPojo();
       
        //p2.setId(104);
        p2.setName("ABCDD");
        p2.setMobile(1454456724);
       
        StudentPojo p3=new StudentPojo();
       
        //p3.setId(105);
        p3.setName("ABCDS");
        p3.setMobile(1448456724);

        Transaction tx = session.beginTransaction();
        session.save(p);
        session.save(p1);
        session.save(p2);
        session.save(p3);
        System.out.println("Object saved successfully.....!!");
        tx.commit();
        session.close();
        factory.close();
    }
}

Thats all. save all these file and run :)

Thursday, July 27, 2017

Sum Numbers From A String


This simple but tricky programs is to filter numbers from a given string and find the sum of all those numbers.





public class StringFilter {

    public static void main(String[] args)
         {  
                 String s = "aB1cD2";
                 int sum=0;       
                 String s1=s.toLowerCase();
                 for(int i=0;i<s1.length();i++)
                 {
                          int m=Character.getNumericValue(s1.charAt(i));
                          if(m >=0  && m<=9)
                          {
                                sum += m;
                          }       
               
                  }
       
        System.out.println(s1+" :- "+sum);
    }

}



Output :  ab1cd2 :- 3

Friday, March 24, 2017

Sum Of Subset of an Array

Program to find sum of subset of a given array and match it with the given sum, if its match with the sum it will print "Yes", if not match with the given sum print "No" if sum of subset is negative number print "error".

Exp :
1
4 8
1
3
5
3

1 is the number of test case, 4 is size of array , 8 is the given sum , 
output : Yes


Sum Of Subset of an Array

Thursday, March 23, 2017

Print biggest numbers from the Array

This is the basic program to print biggest number from the array, but if in the right side of the array is big number from our current number skip it from printing ,else in the right no number is bigger then current number so print it.

Ex : 3,5203,3,6,7,8,1,2,23,54,232,554,879,0

in this array we need to start comparing numbers from 3 and we will go till 0, if we found any bigger number then 3 in right side we will skip it and move to next element.

Output : 5203,879,0

it printing 0 also because there is no number in the right side of 0 so its the biggest.

Print biggest numbers from the Array

Friday, December 16, 2016

Compare the Triplet

Alice and Bob each created one problem for HackerRank. A reviewer rates the two challenges, awarding points on a scale from to for three categories: problem clarity, originality, and difficulty.
We define the rating for Alice's challenge to be the triplet , and the rating for Bob's challenge to be the triplet .
Your task is to find their comparison scores by comparing with , with , and with .
  • If , then Alice is awarded point.
  • If , then Bob is awarded point.
  • If , then neither person receives a point.
Given and , can you compare the two challenges and print their respective comparison points?


Solution : 

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int alice=0;
        int bob=0;
        int a0 = in.nextInt();
        int a1 = in.nextInt();
        int a2 = in.nextInt();
        int b0 = in.nextInt();
        int b1 = in.nextInt();
        int b2 = in.nextInt();
       
        if (a0<b0){
            bob+=1;
           
        }
        if (a1<b1){
            bob+=1;
           
        }
        if (a2<b2){
            bob+=1;
          
        }
        if(a0>b0 ){
            alice+=1;
          
           
        }
        if(a1>b1 ){
            alice+=1;
           
           
        }
        if(a2>b2){
            alice+=1;
           
           
        }
        if(a0==b0){
            alice+=0;
           bob+=0;         
          
        }
        if(a1==b1){
            alice+=0;
           bob+=0;         
          
        }
        if(a2==b2){
            alice+=0;
           bob+=0;         
          
        }
        System.out.println(alice+" "+bob);
    }
}

Diagonal Difference

Given a square matrix of size , calculate the absolute difference between the sums of its diagonals.
Input Format
The first line contains a single integer, . The next lines denote the matrix's rows, with each line containing space-separated integers describing the columns.
Output Format
Print the absolute difference between the two sums of the matrix's diagonals as a single integer.


Solution :


import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
       
       
        int a[][] = new int[n][n];
        for(int a_i=0; a_i < n; a_i++){
            for(int a_j=0; a_j < n; a_j++){
                a[a_i][a_j] = in.nextInt();
            }
        }
        System.out.println(diffrence(a,n));      
       
    }
     static int diffrence(int a[][], int n){
        int sumi=0;
        int sumj=0;
       
        for(int i=0;i<a.length;i++){
            for(int j=0;j<a.length;j++){
                if(i==j){
                    sumi+=a[i][j];
                }
                if(j==(n-i-1))
                sumj+=a[i][j];
            }
        }     
         return Math.abs(sumi-sumj);
    }
   
}

Kangaroo

There are two kangaroos on an x-axis ready to jump in the positive direction (i.e, toward positive infinity). The first kangaroo starts at location and moves at a rate of meters per jump. The second kangaroo starts at location and moves at a rate of meters per jump. Given the starting locations and movement rates for each kangaroo, can you determine if they'll ever land at the same location at the same time?


Solution :

import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int x1 = in.nextInt();
        int v1 = in.nextInt();
        int x2 = in.nextInt();
        int v2 = in.nextInt();
        int x1sum=x1;
        int x2sum=x2;
        boolean test=false;
      
       while (x1sum<x2sum || x1sum>=0 && x1sum<=10000  || x2sum>=0 && x2sum<=10000)  {
            x1sum=x1sum+v1;
            x2sum=x2sum+v2;
           
            if(x1sum==x2sum){
                test=true;
                System.out.println("YES");break;
            }
        }
        if(test==false){
            System.out.println("NO");
        }
       
    }
}