Friday, October 11, 2013

Digit available number of times in given range

package com.rrvtechdiamond;

import java.util.Scanner;

class NumberOfDigits
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner scanner=new Scanner(System.in);
                System.out.println("Enter up to which range you want: "); 
int numberRange=scanner.nextInt();
System.out.println("Enter which digit you want");
int digit=scanner.nextInt();
int count=0;/*count for counting number of digit available within                     given range*/
//for loop start with 0 up to given range
for(int i=0;i<numberRange;i++){
int innerCount=0;/*this count for given digit is available or                                           not if given digit is find more than one time we                                                will print that i value*/
int j=i;
while(j>0)
{
int temp=j%10;
if(temp==digit)
{
innerCount++;
count++;
}
j=j/10;
}
if(innerCount>0){
System.out.println(i);
}
}
System.out.println("You enter digit comes in "+count+" times");
}
}

OUTPUT:

Enter up to which range you want:
100
Enter which digit you want
8
8
18
28
38
48
58
68
78
80
81
82
83
84
85
86
87
88
89
98
You enter digit comes in 20 times

Monday, September 23, 2013

About JSON

What is XML?
                 XML(Extensible markup language) is a data-interchange format.In this format values is surrounded  with start and end tags.Xml is derived from SGML(Standard Generalized Markup Language). This format is used for to sending data from one computer to remote computer in a network.It is easy to read and write for humans. For parsing xml data, we use xml parsers. This parsers verify that particular xml file well-formed and valid based on respective DTD(Document Type Definition) file.
Disadvantages with XML:

1.It doesn't support data types.

2.Its XML parser takes more time to process the XML file.

3.File size is limited.

4. For storing xml data to object and vice-versa is high cost process.

5.This format is not good for sending data from client to server or vice-versa.

    To over come above problems JSon is used.

What is JSON ?
             JSON(JavaScript Object Notation) is a lightweight data-interchange format.It is easy for humans to read and write and easy for machine to parse and generate.This JSon is developed from JavaScript programming language,standard ECMA-262 Edition December 1999.JSON is a text format that is completely language independent.

How many ways we can write JSON ?

We can built JSon in two ways.

1.Collection of name/value pairs.In various languages,this is realized as an object, record, struct, dictionary, hash-table, key-list, or associative array.
2. An ordered list of values.In most  languages this is relialized as an array,vector,list or sequence.

This are universal data structures.Virtually all modern programming languages support them in one form of another. It makes sense that a data format that is interchangeable with programming languages also be based on this structure.

Advantages of JSon:

1.This format is supported by every browser and parser is parsing data very fastly.

2.To send data from client to server or vice-verse  JSON is better than XML.

3.It store data in form of name /value pairs.

4.JSon is used for consumption of data in web applications from webservices for its size and ease of use.

5.JSon is Data-oriented,so so JSon is easily mapped with object-oriented systems.

6. A browser JSon is faster for serializing and de-serializing.

Example :

I have xml file file like below
<order>
<itemno>10</itemno>
<itemName>LUX</itemName>
<qty>2</qty>
</order>

Now i am converting XML to JSon

Syntax of JSON file:

{

-----
-----
-----
}

Example 1:

json1.json:
{//start
{
    "order": {
        "itemno": "10",
        "itemName": "LUX",
        "qty": "10" (Donot give  coma (,)for last field)
}
}//end

The above format is Object format and below format is Array format
Example 2:

json2.json:

{
"order": [
        {
            "itemno": "10",
            "itemName": "LUX",
            "qty": "10" (Donot give  coma (,)for last field)
        }   ]
]
}
Example 2:
{
    "array": [  1, 2, 3 ],
    "boolean": true,
    "null": null,
    "number": 123,
    "object": {
        "a": "b",
        "c": "d",
        "e": "f"
    },
    "string": "Hello World"

}

If you want validate your JSON, copy  and paste your json in this site
www.jsoneditoronline.org
http://jsonlint.com/
















Sunday, September 1, 2013

How to delete elements from Array in java

Array is collection of homogenous fixed size number of elements.If we want to create array object in our program, we should know the size of the array.It is a big problem to the programmers and clients.And once we create an array, cannot change its size and cannot delete elements from array.If you want to delete any element from array,you should create one more array and copy that array elements to this array except which elements you want to delete by using for loop. In java array is object but we donot have method like add,delete thats why collections are introduced in 1.2 version. To reducing burden of developers Apache giving one jar(Download) file. By using this array we can add or delete elements from array.See below snippet

package com.rrv;
import org.apache.commons.lang.ArrayUtils;
 public class ArrayElementDelete
{
   public static void main(String[] args){
      //create array object
     int[] naturalNumber = {1,2,3,6,4,7,6,8,9};

     System.out.println (" Array elements:  "+Arrays.toString(naturalNumber));
     
     //now you can delete element from array
    naturalNumbe = ArrayUitls.remove(naturalNumbers,5); //deleting index 5
   
     // After deleting element from array print the array elements

     System.out.println (" Array elements:  "+Arrays.toString(naturalNumber));
  }
}

Output:

Array elements: 1 2 3 6 4 7 6 8 9

Array elements: 1 2 3 6 4 6 8 9


  

Monday, August 19, 2013

Octal to Decimal in Java

This program is written for to convert octal  number to decimal number programmatically. It is a important interview question and this program as logic to convert octal to decimal.

                                First we find the given number is octal or not. Then we will write logic for decimal number from octal. Observe below logic how to write logic to convert octal to decimal.

package com.rrv;
import java.math.*;
import java.util.Scanner;
//class for converting Octal to Decimal
class OctalToDecimal
{
 //main method
  public static void main(String[] args)
    {  
      //declare boolean type variable for to check given number is octal or not 
       boolean is_Octal=false;
       //create scanner object for taking values from user
       Scanner scanner=new Scanner(System.in);
       System.out.println("Enter Octal Number ");
       int octalNum=scanner.nextInt();
      //call isOctal() method for finding given number is octal or not
       is_Octal= isOctal(octalNum);
      //check given number is octal or not,if true call octalToDecimal() method else print message to console
       if (is_Octal==true){
         octalToDecimal(octalNum);
       }
      else
       {
         System.out.println("Entered Number is not octal number. Please enter Octal number");
       }
    }
// method for finding given number is octal or not
  public static boolean isOctal(int octalNum)
    { 
      //declare remainder variable for to store remainder value
        int remain=0;
     //if octal number is > zero then enter into while loop
        while(octalNum>0)
          {
              remain=octalNum%10;
               if(remain<8)
                {
                   octalNum=octalNum/10;
                 }
              else{
                  return false;
                }
          }
        return true;
     }
//method for convert into decimal
public static void octalToDecimal(int octalNum)
{
   int inputNumber=octalNum;
   int remain=0;
   int count=0;
   int decimal=0;
   while(inputNumber>0)
    {
       remain=inputNumber%10;
       //first find power value of 8 with count and multiply with remainder then add to decimal variable
       decimal=(int) (decimal+remain*Math.pow(8,count));
       count++;
      inputNumber=inputNumber/10;
    }
    System.out.println("The Decimal number for "+octalNum+"  octal is: "+decimal);
  }
}

OutPut:

Enter Octal Number 
173

The Decimal number for 173  octal is: 123

Enter Octal Number 
189

Entered Number is not octal number. Please enter Octal number

 
     
     
   

   

   
     


Saturday, August 10, 2013

Array index start with zero Why?

Array is collection of fixed size homogeneous type of elements.In this post i will explain "Why Array index start with zero on-wards".Generally we cannot think about this question because no one ask this type of questions in interview or anywhere.But in present interview panels asking this question frequently.So we should knowing this one is important for improving knowledge on language(C,C++,JAVA,etc).Before knowing about our topic first we know " How does array store in memory?".Array store in memory based address value.And we are printing element then it use offset value of physical address for getting values.

                   When we are creating the array variable we declare and initialize size of the array. Then we take values from console or directly we can assign.
         Ex:
              int studentNos[]={10,20,60,30,40,80,90,100,50};
                 
                   The array variable is store in memory.The value of array variable is address of zero th index of array.See below diagram

From above diagram we can know how array is storing in memory.After creating array, array variable store only address of zeroth index.Based on this value it calculate addresses of remaining indexes of array.For example, we calculate zeroth index of array based on offset value.Now we discuss "Why array index start with zero?".

 address of zeroth index of array=array variable address + datatype in bytes *  index of array;
                                                 =1000+2*0
                                                 =1000+0
                                                 =1000
Now we got address of zero index then we get value of zeroth index by using &.
 value of zero index of array =&(1000)

                                           =10

Then remaining also calculated like above.


Friday, August 9, 2013

Serialization Vs Extranalization

Serializable is a Marker Interface,is empty interface means it doesn't contain any fields and methods.Marker interface give special ability to Java object at run time  by using Serialization,we can save or transfer state of on object by converting it into a byte Stream.If java class implements Serializable interface then JVM treats this class object as Serializable object.

Externalizable  is a Interface and it is a sub interface of Serializable interface.Externalizable gives capability to programmers to create rules and own mechanisms.It has two methods,are writeExternal() and readExternal().

Serialization Vs Externalization:

1. Serialization is used for default serialization.While Externalization is used for customized serialization process.

2. We can use readObject() and writeObject() of serialization for store object  into persistence or re-getting object from persistence.But in Externalization,we can use readExternal() and writeExternal() methods for store object  into persistence or re-getting object from persistence. 

3. In Serialization, control is under JVM,while in Externalization control in programmer hands.

4. In deserialization process no constructor called in Serialization interface and default constructor is called in externalization at time of deserialization.


Delete given character from text using javascript

a. Design a HTML page as below
b. You can take any sentence like the above diagram. Take only character from the user and remove the character from the given sentence and after clicking on “Click” button, display the sentence again after removing the character as below.
c. Validate for only characters.
d. Design a good looking HTML page.



<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<script>
function clickCha(){
var inn=document.getElementById('1').innerHTML;

while(inn.search(document.getElementById('cha').value)!=-1){
inn=inn.replace(document.getElementById('cha').value,"");

}
var content=document.getElementById('tab').innerHTML;
content=content+inn;
document.getElementById('tab').innerHTML=content;
return true;

}
</script>
<body><center>
<form><fieldset style='border:solid;' id='tab'>
<p id='1'>We at Nacre have created an idea work environment wherenin every Nacrean adheres to set of rules and regulations practiced in the corporate world.This exposes team to corporate culture,leading to inculcation of professionalisam,integrity,time manangement,efficient delegation of work and optimal working strategies both individually and within teams.Nacreans adhere to the following rules and regulations.</p>

Enter a Character:
<input type='text' name='tex' id='cha' value=''>
<input type='button' id='cli' value='click'
onclick='return clickCha()'><br>
</fieldset>
</form></center>
</body>
</html>