Tech Me More

To quench our thirst of sharing knowledge about our day to day experience & solution to techincal problems we face in our projects.

Advertise with us !
Send us an email at diehardtechy@gmail.com

Monday, December 22, 2014

How to separate words from String in java. Break the String in meaningful sentence.

Problem : Given an input string , separate the input string into a space-separated sequence of dictionary words if possible. For example, if the input string is "helloworld" then we would return the string "hello world" as output.

Assume you are given a Dictionary against which you can check the validity of words. Print "String can not be separated" if it contains numbers , any special character or any invalid combination of character/word.

Solution in java


/**
 * Created by IN00474 on 22-12-2014.
 */

import java.util.*;
public class StringToSentence {

    static List<String> l = new ArrayList<String>();
    static String wordToCheck = "";

    public static void main(String[] args) {
  if (args.length==0)
  {
   System.out.println("Pass the input String");
   System.exit(1);
  }
        String inputString = args[0];
        if (inputString.matches("[a-zA-Z]+")) {
            for (int i = 0; i < inputString.length(); i++) {
                wordToCheck = wordToCheck + inputString.charAt(i);
                if (checkInDictionary(wordToCheck)) {
                    l.add(wordToCheck);
                    wordToCheck = "";
                }
                else
                {
                    if(i==inputString.length()-1)
                    {
                        System.out.println("String can not be sorted");
                        return;
                    }

                }
            }
            displaySentence(l);
        } else {
            System.out.println("String can not be sorted");
        }
    }

    public static boolean checkInDictionary(String wordToCheck) {
        ArrayList al = new ArrayList();
        al.add("hello");
        al.add("world");
        if (al.contains(wordToCheck)) {
            return true;
        } else {
            return false;
        }
    }

    public static void displaySentence(List l) {
        Iterator i = l.iterator();
        while (i.hasNext()) {
            System.out.print((String) i.next() + " ");
        }
    }

}



Please note this code was tested against multiple use cases and return correct results, let us know if any of the use case if fails to pass.


Run time result



Java Program to find missing and repeated number from an unsorted array.

Problem : Given an unsorted array of size n. Array elements are in range from 1 to n.One number from set {1, 2, …n} is missing and one number occurs twice in array. Find these two numbers.



Approach to solve (Algorithm)

1. Sort the input unsorted Array in ascending order.
2. Run a loop from index 0 to length-1;
2. Find the difference between element at i & i+1 index.
if difference==-1 continue the loop;
   else
if(difference==0) //So the Number at i index is repeated 
   else

if(difference==-2)//So the Number at index[i]+1 is missing. 


Thursday, November 27, 2014

TreeSet in java : A detailed overview

TreeSet in java under Collection Framework have below property.

1. Underlying data structure is balanced  tree.
2. Doesn't allow duplicate.
3. Elements are inserted as per natural sorting order by default.
4. All elements which are inserted as per default natural sorting order must be comparable in nature.
5. An object is said to be comparable only if corresponding class implements java.lang.Comparable interface.
6. If we use default natural sorting order than objects are compared using compareTo(Object obj) method of java.lang.Comparable interface.
7. Null insertion is not allowed.


Constructor in TreeSet

TreeSet ts=new TreeSet(); //creates an empty TreeSet with default natural sorting order
TreeSet ts=new TreeSet(Comparator c); //creates an empty TreeSet with passed Customoized sorting order

TreeSet ts=new TreeSet(SortedSet s); //Creates a TreeSet view of a Passed SortedSet argument object.


//TreeSetDemo.java


import java.util.*;
class TreeSetDemo 
{
 public static void main(String[] args) 
 {
  TreeSet ts=new TreeSet();
  ts.add("10");
  ts.add("20");
  ts.add("30");
  System.out.println(ts);
 }
}



TreeSet by default stores objects which are homogeneous and comparable, an object is said to be comparable if and only if it implements Comparable interface.

TreeSet stores elements based upon the default natural sorting order.Elements in the TreeSet are comparaed using compareTo(Object obj) method of java.lang.Comparable interface.

But if we want to store objects based upon our own customized sorting order then we need to have a class which implements java.util.Comparator interface.


Comparator


  • It is meant for customized sorting order.
  • Present in java.util package.
  • Contains below 2 method.

1. public int compare(Object obj1,Object obj2)
2. equals()


any class which implements java.util.Comparator Interface should compulsory implement compare() method. Whereas implementing equal() method is optional.

This is because every java class is a child class of Java.lang.Object class. Object class provide implementation for equals() method, so equals () is by default present in every java class.


Write a java program to insert Integer elements in TreeSet with desecending sorting order.



import java.util.*;
class ReverseTreeSet 
{
 public static void main(String[] args) 
 {
  TreeSet ts=new TreeSet(new Com());
  ts.add(10);
  ts.add(20);
  ts.add(30);
  ts.add(40);
  ts.add(50);
  System.out.println(ts);
 }
}

//Java code for customized sorting order


import java.util.*;
class Com implements Comparator
{
 public int compare(Object obj1, Object obj2)
 {
  Integer i1=(Integer)obj1;
  Integer i2=(Integer)obj2;
  return i2.compareTo(i1);
 }
}

Saturday, November 22, 2014

India Insurance Guide : A complete resource for your insurance need



Insurance is the big thing in the dynamically growing world, insurance for different purpose comes in different flavors and different rules based upon the kind of insurance policy you have taken.

India insurance guide is the complete reference for insurance policies, how to claim them and what rules are involved. 

Buy it here


As per the description from the FlipKart 

India Insurance Guide-Handbook of Insurance Policies, Claims and Law is a fully updated and revised 2nd Edition. It is a Reference book on Insurance and Insurance sector in India and covers both Life and Non-Life Insurance with important statistics. Review of India Insurance Guide has been published by Times of India & Asia Insurance Review (Professional magazine published from Singapore).

Foreword of book has been written by honorable Justice (Retd.) N. K. Jain Former Judge of M. P. High Court, Ex-President, M. P. State Consumer Disputes Redressal Commission Bhopal. This updated Reference Book on Insurance explains theoretical & practical aspects of Insurance Policies, Claims & Law related to life & non-life insurance in India & would be found very useful for insurance consumers, students of insurance, Lawyers, insurance professionals, financial consultants, Insurance claims consultants and must for every library in India. This book would prove to be a very important supplementary training/study material for Training Programs conducted for Insurance and bank employees, Insurance agents, Insurance brokers, Insurance surveyors, Third Party Administrators, Courses conducted by Insurance Institute of India, College of Insurance, PG Diploma in Life/General Insurance, MBA in Insurance/Finance, etc.




Apart from india insurance guide , Mr. L. P. gupta has written couple of other handbooks for insurance named as "General insurance guide" and "Insurance claims solutions"

Mr. L. P. Gupta can be reached here : lpgupta1950@gmail.com

L. P. Gupta personal blog can be read here : Blog

Sunday, November 9, 2014

Mail System User : JAVA PROJECT for freshers and final year students

Mail System

Mail system is a JSP-Servlet based advance java project for all the freshers willing to build their career in java software /application develpoment workspace.

This project can be used to showcase in your resume as well as to grow your knowledge on the subjects like JSP and Servlets. 

Its a mini web application which can can be used for best practices.

Technology used

              JSP
·         SERVLET
·         CORE JAVA
·         HTML
·         CSS
·         SQL

To use the email services project below are the prerequisite.
1.       Java
2.       MySql
3.       Apache Tomcat 7.0 or +

To customize the project below are the prerequisite.

1.       Eclipse

Database configuration

·     Create a MySql database and name it as mailsystem.

·         Run the below sql query to create table.
o   CREATE TABLE MAILSYSTEMUSER(EMAIL VARCHAR(100),PASSWORD VARCHAR(50),NAME VARCHAR(100),GENDER VARCHAR(25),MNUM VARCHAR(100), COUNTRY VARCHAR(100))

o   CREATE TABLE INBOX(ID INT(20),RECIEVER VARCHAR(100),SENDER VARCHAR(100),MESSAGE VARCHAR(1000),DATE_OF_RECEIVING VARCHAR(100))

How to use Project

·         Unzip the project to your current workspace of eclipse.
·         Configure the Tomcat 7.0 or higher.
·         Run the project.


Home page of application

Home page of project

Add caption

Compose mail page

Registration page
Download here:

Download here:

Please let us know in comment section if this project helped you that way we will be encouraged to develop more and more projects for free .

If you run into any problem related to this project , feel free to ping us at diehardtechy@gmail.com or you can comment in the comment section below.

Like us on facebook for more !!

Wednesday, November 5, 2014

How to read the value of a attribute of a XML tag in Java

How to read the value of a attribute of a XML tag using Java core library. Attributes reside inside the tag and can be read using the org.w3c.dom and javax.xml.Xpath package. There are several others ways also to achieve the same behavior.

For example you have a below XML file .


<?xml version="1.0" encoding="UTF-8"?>
<details name="person-detail" >
    <property name="personal">
        <value text="Mr.XYZ"/>
        <value text="Teacher" />
        <value text="Single" />
    </property>   
</details>


and you want to read the value of text attribute of a value tag of above XML using java and print it on console.

Expected Output:
Mr.XYZ
Teacher
Single


Given below is the code to achieve expected behavior using java.
import java.io.File;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.DocumentBuilder;
import org.w3c.dom.*;
import javax.xml.xpath.*;

public class XMLRead
{

    public static void main(String args[]) 
    {
        try 
        {
   DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
   Document dDoc = builder.parse("C:\\MyXMLFile.xml");
   XPath xPath = XPathFactory.newInstance().newXPath();
   NodeList nodes1 = (NodeList) xPath.evaluate("/details/property[@name='personal']/value/@text", dDoc, XPathConstants.NODESET);
   for (int j = 0; j < nodes1.getLength(); j++) {
   Node node1 = nodes1.item(j);
   System.out.println(node1.getTextContent()); 
   }

        } 
  catch (Exception e) 
        {
            e.printStackTrace();
        }

    }
}

Above code produces the below output.


In Ruby how to use the function of a module defined in a different directory



To use the function of a module defined in a different directory below steps need to be followed.

1. Define a module in some directory other then which have your ruby class.

Example

Say some module Week is defined in trig.rb file inside io/test package.


module Week
  FIRST_DAY = "Sunday"
  def Week.weeks_in_month
    puts "You have four weeks in a month"
  end
  def Week.weeks_in_year
    puts "You have 52 weeks in a year"
  end
end


2. To use this module related function in your class 'test.rb' use the below syntax.


#!/usr/bin/ruby

require_relative 'io/test/trig'

class Decade

end
d1=Decade.new
puts Week::FIRST_DAY
Week.weeks_in_month
Week.weeks_in_year

To make it more clear check the below the hierarchy diagram of directory structure.

Hierarchy diagram of above explanation


To download the above example code:

Tuesday, October 14, 2014

HashSet in collection framework


HashSet

HashSet is the direct subclass of Set interface , HashSet doesn’t allow duplicates element insertion and insertion order is not preserved.

  1.  Underlined data structure is HashTable.
  2. HashSet doesn't allow duplicates.
  3.  Insertion order is not preserved.
  4.  Null insertion is allowed.
  5.  Heterogeneous objects are allowed. 
  6. Implements Serializable and clonable interfaces.

Constructor in HashSet

HashSet hs=new HashSet();  // creates an empty HashSet


HashSet hs=new HashSet(int initialCapacity); 

//Creates and empty HashSet with passed initialCapacity and default load factor 0.75.

HashSet hs=new HashSet(Collection c); 

//Creates a HashSet representation of Passed collection object.

HashSet hs=new HashSet(int initialCapacity, float loadFactor); 

//creates an empty HashSet with given initialCapacity and given loadFactor.

Example:

import java.util.*;
class HashSetDemo 
{
 public static void main(String[] args) 
 {
  HashSet hs=new HashSet();
  hs.add(10);
  hs.add(20);
  hs.add(30);
  hs.add(10);
  hs.add("Hello");
  hs.add(null);
  hs.add(new HashSetDemo());
  System.out.println(hs);
  System.out.println(hs.remove(30)); /*removes the passes argument object from 
           the HashSet and returns true, false otherwise.*/
  System.out.println("Total number of elements in the HashSet "+hs.size());
  hs.clear(); //clear the entire HashSet 
  System.out.println(hs);
  
 }
}

Output:



Neosoft Technologies Ltd hiring 1-4 years experience as java developers


Company Name : Neosoft Technologies Ltd

Location :Hyderabad

Position : Java/J2ee Developer

Experience: 1 to 4 Year

Apply here : Click to apply 

Skills Required



  • Application/UI development in Java, JSP, Servlets, JDBC.
  • J2EE, JSP, Tiles, UML Methodology.
  • Extensive coding experience on IDEs like Netbeans / JBuilder / Eclipse, experience with HTML, JavaScript, XML/XSL/XSLT.
  • Must have sound knowledge of Frameworks: Spring, Struts, Hibernate, Swing, JSF, EJB.
  • Database –(MYSQL, Oracle, PostgreSQL)

Friday, October 10, 2014

Flipkart big billion day. What went wrong and what we should learn from it.

They named it as big billion day but many visitors named it as big fool day because of the unwanted performance issue and technical problems in the back end of flipkart application . 

Here is our point on what went wrong and what should we learn from it.

They deployed best of app servers , extend their system capabilities and work force to an extreme but an unfortunate show of technically unfeasible web application, no matter how decent front end of your web application looks but if the application back end is not strong outcome can be worse than big billion day as flipkat.Computers and computer science technology are the great resources and can bring you never imagined admiration. But if you don't respect technology they can make you stand in a situation where you never want to go.

But as the saying goes every breakdown bring some message/lesson associated with it, this crash of flipkart application is a best trigger for all fellow IT people, future technocrats and architects to learn, nurture and craft a system which will be sustainable even in the circumstances of extreme traffic or load.

I support flipkart for the dedication and confidence they have created; I can only imagine how many sleepless nights flipkart and their team have spent to bring it on a forefront. It takes unlimited patience, confidence and dedication to turn something big into reality. The bitter results are the best critics which teach us to learn and learn and push ourselves to the beyond.

P.S. this post is not a criticism of an e-commerce giant but a learning prospect for performance engineers, quality assurance engineers and classy developers, it is also a big business opportunity for independent software testing organizations.

Tuesday, October 7, 2014

9 Key Interfaces of Collection framework and Collection framework Hierarchy

Collection framework in Java


When we want to represent a group of individual object as a single entity we should choose Collection. 



Difference between Collection and Collections

Collection is an interface, whereas Collections is a class in java. Collection is treated as base interface in Collection framework, whereas Collections class consists exclusively of static methods that operate on or return collections. Collections class is defined in java.util package.


9 Key Interfaces of Collection framework

  • Collection
  • List
  • Set
  • SortedSet
  • NavigableSet
  • Queue
  • Map
  • SortedMap
  • NavigableMap

s       Collection framework Hierarchy

        






How to start with servlets, a guide for beginners.

How to start with Servlets, Write a servlet program to print the name coming from a HTML form.

Before we start with servlets , make sure you have following software installed.
  1. Apache Tomcat 7.0
  2. Java 1.7 or higher

Create a folder structure as shown below under C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps directory.




  1. Create a file say HelloWorld.java and placed it in the classes folder.
  2. import javax.servlet.http.*;
    import javax.servlet.*;
    import java.io.*;
    public class HelloWorld extends HttpServlet 
    {
     public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException
     {
      String name=request.getParameter("t1");
      response.setContentType("text/html");
      PrintWriter ps=response.getWriter();
      ps.print("Hello "+name);
     }
    }
  3. compile the HelloWorld.java file.
  4. edit the web.xml file as given below.

  5. <?xml version="1.0" encoding="ISO-8859-1"?>
    <!--
     Licensed to the Apache Software Foundation (ASF) under one or more
      contributor license agreements.  See the NOTICE file distributed with
      this work for additional information regarding copyright ownership.
      The ASF licenses this file to You under the Apache License, Version 2.0
      (the "License"); you may not use this file except in compliance with
      the License.  You may obtain a copy of the License at
    
          http://www.apache.org/licenses/LICENSE-2.0
    
      Unless required by applicable law or agreed to in writing, software
      distributed under the License is distributed on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      See the License for the specific language governing permissions and
      limitations under the License.
    -->
    
    <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://java.sun.com/xml/ns/javaee  http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
      version="3.0"  metadata-complete="true">
    
      <display-name>Welcome to Tomcat</display-name>
      <description>Welcome to Tomcat</description>
    
      <servlet>
        <servlet-name>FirstSer</servlet-name>
        <servlet-class>HelloWorld</servlet-class>
      </servlet> 
    
      <servlet-mapping>
        <servlet-name>FirstSer</servlet-name>
        <url-pattern>/DisplayName.do</url-pattern>
      </servlet-mapping>
    
    </web-app>
    
  6. Create a Hello.html file and place it in HelloWorld i.e. root folder.

  7. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
     <head>
      <title> First App</title>
     </head>
     <body>
     <form action="DisplayName.do">
     <center>
     <h1>Please enter your name </h1>
      <input type="text" name="t1"><input type="submit" value="Submit">
      </center>
      </form>
     </body>
    </html>
    
  8. Run the Tomcat Server.
  9. Navigate to the following URL.
    http://localhost:8080/HelloWorld/Hello.html

    You should see the Hello.html web page on your browser.
    Hello.html


  10. Enter your Name in the text field and click submit.
  11. You should see the result something like below.



If you run into any error, please feel free to reach us.