Java XML parsing using DOM parser

Employees.xml:

Java XML parsing tutorial example code


Employee.java


  1. package javaXMLParsing;
  2. public class Employee {
  3.     
  4.     String id;
  5.       String firstName;
  6.       String lastName;
  7.       String location;
  8.      
  9.       @Override
  10.       public String toString() {
  11.         return firstName+" "+lastName+"("+id+")"+location;
  12.       }
  13.  
  14. }

Java Example program to parse XML using DOM parser:

DOMParserDemo.java


  1. package javaXMLParsing;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4.  
  5. import javax.xml.parsers.DocumentBuilder;
  6. import javax.xml.parsers.DocumentBuilderFactory;
  7.  
  8. import org.w3c.dom.Document;
  9. import org.w3c.dom.Element;
  10. import org.w3c.dom.Node;
  11. import org.w3c.dom.NodeList;
  12.  
  13. public class DOMParserDemo {
  14.  
  15.  public static void main(String[] args) throws Exception {
  16.         //Create object of DOM Builder Factory  class By using
  17.        //DocumentBuilderFactory.newInstance() method

  18.         DocumentBuilderFactory factoryobj =
  19.             DocumentBuilderFactory.newInstance();
  20.      
  21.         //Create DOM Builder Object from DocumentBuilderFactory object
  22.         DocumentBuilder builder = factoryobj.newDocumentBuilder();
  23.      
  24.         //Load the XML document and parse it
  25.        
  26.         Document documentobj =
  27.           builder.parse(
  28.             ClassLoader.getSystemResourceAsStream("javaXMLParsing/Employee.xml"));
  29.      
  30.      
  31.         List<Employee> empList = new ArrayList<>();
  32.      
  33.         //Iterating through the nodes and extracting the data.
  34.         NodeList nodeList = documentobj.getDocumentElement().getChildNodes();
  35.      
  36.         for (int i = 0; i < nodeList.getLength(); i++) {
  37.      
  38.           //We have encountered an <employee> tag.
  39.  
  40.           Node node = nodeList.item(i);
  41.           if (node instanceof Element) {
  42.             Employee emp = new Employee();
  43.             emp.id = node.getAttributes().
  44.                 getNamedItem("id").getNodeValue();
  45.      
  46.    NodeList childNodes = node.getChildNodes();
  47.    for (int j = 0; j < childNodes.getLength(); j++) {
  48.        Node cNode = childNodes.item(j);
  49.      
  50.       //Identifying the child tag of employee every employee .
  51.       if (cNode instanceof Element) {
  52.        String content = cNode.getLastChild().
  53.                     getTextContent().trim();
  54.                 switch (cNode.getNodeName()) {
  55.                   case "firstName":
  56.                     emp.firstName = content;
  57.                     break;
  58.                   case "lastName":
  59.                     emp.lastName = content;
  60.                     break;
  61.                   case "location":
  62.                     emp.location = content;
  63.                     break;
  64.   }
  65.   }
  66.  }
  67.             empList.add(emp);
  68. }

  69. }
  70.      
  71.        //Printing the Employee list by using for each loop.
  72.  for (Employee emp : empList) {
  73.           System.out.println(emp);
  74.  }
  75.      
  76.  }
  77.  
  78. }



Output:


  1. saidesh kilaru(001)Bangalore 
  2. ajay chanukya(002)Chicago 
  3. Vinod Gandrakoti(003)Hyderabad

Difference between Collections and Collection in java with example program

In Java, "Collection" refers to the interface that defines the basic properties and behaviors of a collection, while "Collections" is a utility class that provides static methods for working with collections.

The Collection interface is part of the Java Collections Framework and it is a root interface for all the collections. It defines the basic properties and behaviors that all collections should have, such as adding and removing elements, checking the size of the collection, and so on.
It includes List, Set and Queue interfaces.

On the other hand, the Collections class is a utility class that provides various static methods for working with collections, such as sorting, reversing, and searching. It also provides methods for creating unmodifiable collections, which are collections that cannot be modified after they are created.

Here are some examples of how we can use the Collections class:

To sort a List:

List<Integer> myList = new ArrayList<>();
myList.add(3);
myList.add(1);
myList.add(2);
Collections.sort(myList);

To reverse an array:

Collections.reverse(myList);

To create an unmodifiable collection:

List<Integer> unmodifiableList = Collections.unmodifiableList(myList);

It's worth noting that, the Collections class only provides static methods, it does not provide any instance methods. So, you can't create an object of the Collections class.

  • Famous java interview question: difference between collections and collection in java
  • Major difference between Collection and Collections is Collection is an interface and Collections is a class. 
  • Both are belongs to java.util package
  • Collection is base interface for list set and queue.
  • Collections is a class and it is called utility class.
  • Collections utility class contains some predefined methods so that we can use while working with Collection type of classes(treeset, arraylist, linkedlist etc.)
  • Collection is base interface for List , Set and Queue.



Collection vs Collections

  1. public interface Collection<E> 
  2. extends Iterable<E>


  1. public class Collections
  2. extends Object


difference between collections and collection in java

  • Collections utility class contains static utility methods so that we can use those methods by using class name without creating object of Collections class object
  • Lest see some methods of Collections class.


  1. addAll: public static <T> boolean addAll(Collection<? super T> c,T... elements)
  2. reverseOrder: public static <T> Comparator<T> reverseOrder()
  3. shuffle: public static void shuffle(List<?> list)
  4. sort:public static <T extends Comparable<? super T>> void sort(List<T> list)
How to Relate Collection and Collections
  • ArrayList is a Collection type of class means it is implementing Collection interface internally
  • Now lets see a java example program to sort ArrayList of elements using Collections.sort() method.

  1. public class ArrayList<E>
  2. extends AbstractList<E>
  3. implements List<E>, RandomAccess, Cloneable, Serializable


1.Basic Java example program to sort arraylist of integers using Collections.sort() method

  1. package com.javasortarraylistofobjects;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.Collections;
  5. import java.util.Iterator;
  6.  
  7. public class SortArrayListExample{
  8.  
  9. public static void main(String[] args) {
  10.   
  11. //create an ArrayList object
  12.  ArrayList<Integer> arrayList = new ArrayList<Integer>();
  13.        
  14.  //Add elements to Arraylist
  15. arrayList.add(10);
  16. arrayList.add(7);
  17. arrayList.add(11);
  18. arrayList.add(4);
  19. arrayList.add(9);
  20. arrayList.add(6);
  21. arrayList.add(2);
  22. arrayList.add(8);
  23. arrayList.add(5);
  24. arrayList.add(1);
  25.         
  26.         
  27.  System.out.println("Before sorting ArrayList ...");
  28.  Iterator itr=arrayList.iterator();
  29.         
  30. while (itr.hasNext()) {
  31.  
  32. System.out.println(itr.next());
  33.      
  34. }
  35.  
  36.        
  37.  /*
  38.  To sort an ArrayList object, use Collection.sort method. This is a
  39.   static method. It sorts an ArrayList object's elements into ascending order.
  40. */
  41.   Collections.sort(arrayList);
  42.      
  43.   System.out.println("After sorting ArrayList ...");
  44.        
  45.     
  46.         
  47. Iterator itr1=arrayList.iterator();
  48.         
  49. while (itr1.hasNext()) {

  50. System.out.println(itr1.next());
  51.             
  52. }
  53.     
  54.   
  55. }
  56. }
     


Output:

  1. Before sorting ArrayList ...
  2. 10
  3. 7
  4. 11
  5. 4
  6. 9
  7. 6
  8. 2
  9. 8
  10. 5
  11. 1
  12. After sorting ArrayList ...
  13. 1
  14. 2
  15. 4
  16. 5
  17. 6
  18. 7
  19. 8
  20. 9
  21. 10
  22. 11

Java Program to find missing numbers in an array

  • To find missing numbers in an array first we need to make sure that array is sorted.
  • After sorting we need to check that array each element with next element then we can find the difference.
  • if Array is not sorted :To sort array use Arrays.sort(array);
  • If difference is 1 then no need to do any thing because numbers are in order.
  • If difference is not equal to 1 then we need to print all those numbers or pick those numbers and place it in one array.
  • this would be the logic to find missing numbers in an array
  • Here there may be a chance of array not starts with 1 then we need to check first itself whether array starts with 1 or not if not we need to print 1 to starting element of array.
  • for example int a[]={4,5,6,8}; then we need to print 1 2 3  7.



 Lets see a java example program to find missing numbers in an array.

  1. package arraysInterviewQuestions;
  2. public class PrintMissingNumbers {
  3.  
  4. private static void findMissingNumber(int[] number){
  5.  
  6.         // take max length as last number in array
  7.     int k[] = new int[number[number.length-1]];
  8.         
  9.   int m=0;
  10.  
  11.   if(number[0]!=1){
  12.    for (int x = 1; x < number[0]; x++) {
  13.        k[m] =  x;
  14.        m++;
  15.        }
  16.   }
  17.         
  18.  for (int i = 0; i < number.length -1; i++) {
  19.     
  20.     int j = i+1;
  21.     int difference = number[j] - number[i] ;
  22.             
  23.             
  24.    if(difference != 1 ){
  25.         
  26.   for (int x = 1; x < difference; x++) {
  27.  
  28.           k[m] = number[i] + x;
  29.            m++;
  30.     
  31. }
  32.             
  33.  }
  34.  }
  35.         
  36. System.out.println("missing numbers in array ::");
  37.         
  38. for (int l = 0; l < m ; l++) {
  39.     System.out.println( k[l]+" ");
  40. }
  41. }
  42.  public static void main(String[] args) {
  43.         
  44.    int a[]= {2,4,6,9,10,20};
  45.  
  46.    //if Array is not sorted :To sort array use Arrays.sort(a); 
  47.  
  48.   findMissingNumber(a);
  49.  
  50.    
  51. }
  52. }
 
program to find missing number in an array in java


  • Change the array in main method and practice try to find missing elements in an array that contains 1 to 100 numbers.

Dynamic polymorphism in java with example program

  • Polymorphism means defining multiple methods with same name.

  • Two types of polymorphism
    1.Static polymorphism
    2.Dynamic polymorphism.

Static polymorphism:

  • Defining multiple methods with same name and with different type of arguments is known as static polymorphism.
  • We can achieve this static polymorphism using method overloading.

Static polymorphism in java with example program


  1. package com.instanceofjava;
  2. class A{
  3.  
  4. public void show(int a){
  5. System.out.println("saidesh");
  6. }
  7.  
  8. public void show(int a,int b){
  9. System.out.println("ajay");
  10. }
  11.  
  12. public void show(float a){
  13. System.out.println("vinod");
  14. }
  15. public static void main(String args[]){
  16.  
  17. A a=new A();
  18.  
  19. a.show(10);
  20. a.show(1,2);
  21. a.show(1.2);
  22.  
  23. }
  24. }
Output:

  1. saidesh
  2. ajay
  3. vinod


Dynamic polymorphism:

  • Defining multiple methods with same name and with same signature in super class and sub class.
  • We can achieve dynamic polymorphism by using method overriding concept in java.
  • Define a method in super class and override same method with same signature in sub class
  • Whenever we call the method on t the object based on the object corresponding class method will be executed dynamically.
Java example program on dynamic polymorphism: (Real time example)

  1. package MethodOverridingExamplePrograms;
  2. public class Vehicle{
  3.  
  4. void Start(){ 
  5. System.out.println("Vehicle started")
  6. }

  7. }


  1. package MethodOverridingExamplePrograms;
  2. public class Car extends Vehicle{
  3.  
  4. void Start(){ 
  5. System.out.println("Car started")
  6. }

  7. }


  1. package MethodOverridingExamplePrograms;
  2. public class Bus extends Vehicle{
  3.  
  4. void Start(){ 
  5. System.out.println("Bus started")
  6. }

  7. }


  1. package MethodOverridingExamplePrograms;
  2. public class Bike extends Vehicle{
  3.  
  4. void Start(){ 
  5. System.out.println("Bike started")
  6. }

  7. }


  1. package MethodOverridingExamplePrograms;
  2. public class Test{
  3.  
  4. public static void startVehicle(Vehicle vh){ 
  5.    
  6. vh.start();


  7.  
  8. }

  9. }

Dynamic polymorphism in java with example program



  •  In the above example based on the object creation at run time corresponding class method will be executed.

toString() method in java with example program

  • toString() method belongs to object class.
  • By default it will be called once  whenever we try to print object.
  • toString() method by default will print classname@hex representation of hashcode.
  • We can override this toString() method from object class.


  1. public String toString(){
  2.  
  3.    return null;
  4.        
  5. }

Advantage of toString() method in java.

  • When ever we try to print object by default toString() method will be called and print classname@HEX_hashcode.
  • We can represent object in String format using toString() method.
  • if we want to represent string representation of object then we need to override toString() method in our class and return values of the object as a String.




 Java example program to print object without using toString() method.
  • Lets see an example program on printing object of a class.

  1. package tostringexamples;
  2. public class ToStringDemo {
  3.  
  4.     int a,b;
  5.  
  6. ToStringDemo(int x, int y){
  7.         a=x;
  8.         b=y;
  9.  }
  10.  
  11. public static void main(String[] args) {
  12.  
  13.  ToStringDemo obj= new ToStringDemo(1,2);
  14.         
  15.  ToStringDemo obj2= new ToStringDemo(3,4);
  16.         
  17.     System.out.println(obj);
  18.     System.out.println(obj2);
  19.  
  20.  }
  21.  
  22. }


Output:


  1. tostringexamples.ToStringDemo@2a139a55
  2. tostringexamples.ToStringDemo@15db9742

  •  In the above program when we print object of ToStringDemo class it prints ToStringDemo@2a139a55.
  • It means when ever we print object of the class toString() method will be called and by default toString() method print classname@HEX_hashcode.
  • To test this now we will override the toString() method and prints object of the class and if it calls our method then we can understand that when ever we print object by default toString() method will be called.

 Java example program to print object by overriding toString() method.

override tostring method in java example

  • In above example when we print object it executed overridden toString() method.
  • By overriding toString() method we can represent object in string form.

 

toString() method used to convert data to String type. 

  •   By using toString method we can convert any wrapper object to string object
     
Java example program to convert integer to string using toString() method.

  1. package tostringexamples;
  2. public class ToStringDemo {
  3.  
  4. public static void main(String[] args) {
  5.  
  6.   Integer a=12;
  7.   Integer b=37;
  8.  
  9.   String str1=a.toString();
  10.   String str2 =b.toString();
  11.         
  12.   System.out.println(str1);
  13.   System.out.println(str2);
  14.  
  15.     }
  16. }

Output:

  1. 12
  2. 37

Java example program to convert Float to String using toString() method.

  1. package tostringexamples;
  2. public class ToStringDemo {
  3.  
  4. public static void main(String[] args) {
  5.  
  6. Float  a=12.0f;
  7. Float b=33.4f;
  8.  
  9.   String str1=a.toString();
  10.   String str2 =b.toString();
  11.         
  12.   System.out.println(str1);
  13.   System.out.println(str2);
  14.  
  15.     }
  16. }

Output:

  1. 12.0
  2. 33.4

Google Wins Java Copyright Case Against Oracle


  • Google has won a six-year court case brought by software firm Oracle, which claimed Google had infringed its copyright by using 11,500 lines of Java code in its Android operating system.
  • A jury has ruled that Google did not unfairly use parts of Java programming language.?Oracle? sought billions in damages from Google.
  • A judge on Thursday ruled Google's use of Java code in the Android operating system does not infringe on Oracle's copyrights and is protected by fair use. Oracle said it would appeal the decision.


Google Wins Java Copyright Case Against Oracle
  • Google wins $9bn Java copyright case with Oracle short by Swarnim Bagre / 05:49 pm on 27 May 2016,Friday
  • A federal jury in San Francisco ruled in favor of Google in the Java copyright case against Oracle on Thursday. Oracle had filed a suit in 2010 against Google claiming that it used code from the Oracle-owned Java programming language in Android without permission, seeking nearly $9 billion in damages. Oracle said that it will appeal against the decision
  • Copyright law expert Professor Pam Samuelson said the litigation was a "very unusual" fair use case, but that the jury ultimately agreed with the fair use defense, including the fact that "Google was the one who made an innovative and highly successful product from Java."
  • The sun has finally set on the Google and Oracle copyright battle. Google has won the long running Java lawsuit against Oracle as the jury found that Android OS does not violate copyrights owned by the latter.
  • Earlier in March Oracle demanded $9.3 billion in damages from Google over the use of Java API in Android which powers about 80% of the world’s mobile devices.. The company stated that Google needed a license to use its Java programming language to develop Android however, the jury rejected that argument and concluded Google made fair use of the code under copyright law. Oracle owns the programming language Java as it was acquired Sun Microsystems in 2010.
  •  "Today's verdict that Android makes fair use of Java APIs represents a win for the Android ecosystem, for the Java programming community, and for software developers who rely on open and free programming languages to build innovative consumer products," Google said in an emailed statement. 
  • The verdict is the latest development in the six-year legal skirmish over software copyrights with billions of dollars in damages at stake. 
  •  Oracle pledged it would appeal the verdict. "We strongly believe that Google developed Android by illegally copying core Java technology to rush into the mobile device market. Oracle brought this lawsuit to put a stop to Google’s illegal behavior. We believe there are numerous grounds for appeal," Oracle's general counsel Dorian Daley said in an emailed statement.
     

linux unix commands with examples

Unix/Linux Commands
Ls: List of all files
    Syntax
                             Function
Ls-l
Complete properties of files or folders
Ls-lt
List of files or folders order by time
Ls-ltr
List of files or folders reverse order by time
Ls-d
Displays only directories

Cd: Change directory
    Syntax
                             Function
cd-
Change directory to previous working directory
cd..
Change working directory to parent directory
Cd~
Same as above
cd../..
Change two levels up in the directory structure
Command
          Syntax
                     Function
Cp(copy)
Cp source..destination
Copy the files and directories
sort
Sort[option][filename]
Sort the contents of text line by line
uniq
Uniq[option] filename
Eliminates duplicate lines from file
cat
Cat[options][files]
Display the contents of the file
join
Join[option]file1 file2
Join he two files based on key field present
sed
Sed..[script][input file]
Basic text transformations on input
head
head[option][files]
Prints first N lines from file
tail
Tail[option][file]
Print last N lines from file
alias
Alias[name=[’command]’]
Alternative name used for long strings
date
Date[option]…[format]
Print the date or change the system date and time
zip
Zip[option]zipfile file_list
Compress the file and reduce file size
grep
Grep[option]pattern[list of files]
Search the words in a file
find
Find[pathnames][condition]
Search for directories, files and links
cut
Cut[option]…[file]
Select sections of text from each line in a file
chmod
Chmod[option]mode… filename
Change or assign the permissions of files or directories
rmdir
Rmdir[options]directories
Remove directories
rm
Rm[options]directories/files
Remove both files and directories
mkdir
Mkdir[option]directories
Creates single or multiple directories
mv(move)
Mv[option]source.. destin
Move or rename the files and directories
hostname
Hostname[option][file]
Name of the system or server you are logged into.
paste
Paste[options]file-list
Merges the lines from multiple files
split
Split..filename
Split the one file in to many pieces
mail
Mail[options]to address [sending mail options]
Send email to users, also read delete mails
kill
Kill[-s signal] pid
Terminate or kill the process, also running the process
top
Top[options]
Provides system information
expr
Expr[expression]
For doing arithmetic operations
WC
Wc[options]filename
Finding number of lines, characters, words in a file
tr (Translate)
Tr[options]set1 [set2]
Translate, delete, squeezed characters
Select Menu