Rabu, 06 Juli 2016

Java interview programming questions on this keyword part 2



Java Quiz on this keyword part #2
  • Java interview program on this keyword: can we call method using this keyword?
  
Program  #5:

java programming on this keyword





Program #6: Can we call non static method from constructor using this?

Java programming examples on this keyword





Program #7: Can we assign something to this ?



  1. package thiskeywordinterviewprograms.java;
  2. public class ThisDemo {
  3.  
  4.     int a;
  5.     int b;
  6.     
  7.  ThisDemo(int x, int y){
  8.  
  9.        this= new ThisDemo();
  10.         System.out.println("Two argument constructor called.");
  11.         this.x=x;
  12.         this.y=y;
  13.         
  14. }
  15.  
  16. public static void main(String[] args) {
  17.         
  18.     ThisDemo obj = new ThisDemo(10, 20);
  19.         
  20.      System.out.println(obj.a);
  21.      System.out.println(obj.b);

  22. }
  23.  
  24. }





Program #8 : Can we use this as return statement in a method?


  1. public class B{

  2.    int a;
  3.     
  4.  public int getA() {
  5.         return a;
  6.  }
  7.  
  8. public void setA(int a) {
  9.         this.a = a;
  10. }
  11.  
  12. B show(){
  13.     return this;
  14. }
  15.  
  16. public static void main(String[] args) {
  17.        
  18.  B obj = new B();
  19.  
  20.   obj.setA(10);
  21.  
  22.  System.out.println(obj.getA());
  23.  B obj2= obj.show();
  24.  System.out.println(obj2.getA());
  25.  
  26. }

  27. }





Baca selengkapnya

Java Interview programming questions on this keyword

  • Lets discuss some interesting programs on this keyword.
  • Now its time to practice some programs on this keyword. 
  • Try to guess the output of the following java programming questions on this keyword.
  • If you want explanations for all the programs please go through this keyword interview questions on java
Java Quiz on this keyword part #1



Program #1: Java interview programming question on this keyword.


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

  20. }
  21.  
  22. }





Program #2: Java interview programming question on this keyword.

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

  20. }
  21.  
  22. }




Program #3: Java Interview programming example on this keyword.

  • What will be the output of the below program

  1. package thiskeywordinterviewprograms.java;
  2. public class ThisDemo {
  3.  
  4.     int a;
  5.     int b;
  6.     
  7. ThisDemo(int a, int b){
  8.  
  9.     this.a=a;
  10.     this.b=b;
  11.         
  12. }
  13.  
  14. public static void main(String[] args) {
  15.         
  16.     ThisDemo obj = new ThisDemo();
  17.         
  18.      System.out.println(obj.a);
  19.      System.out.println(obj.b);

  20. }
  21.  
  22. }





Program #4: Java interview programming question on this keyword.


java programming examples on this keyword




  1. Zero argument constructor called.
  2. Two argument constructor called.
  3. x=1
  4. y=2

Interview Programming questions on this keyword part 2
Baca selengkapnya

Selasa, 05 Juli 2016

Java Program to find shortest palindrome in string

  • We have a Letter or a word then we need add some letters to it and need to find out shortest palindrome 
  • For example we take "S":  S will be the shortest palindrome string.
  • If we take "xyz"zyxyz will be the shortest palindrome string
  • So we need to add some characters to the given string or character and find out what will be the shortest palindrome string by using simple java program.


Java example Program to find out shortest palindrome of given string


  1. package shortestpalindromeexample.java;
  2. import java.util.Scanner;
  3.  
  4. public class ShortestPalindromeDemo {
  5.  
  6. public static String shortestPalindrome(String str) {
  7.      
  8. int x=0;  
  9. int y=str.length()-1;
  10.      
  11.   while(y>=0){
  12.      if(str.charAt(x)==str.charAt(y)){
  13.           x++;
  14.          }
  15.             y--;
  16.   }
  17.  
  18. if(x==str.length())
  19. return str;
  20.  
  21. String suffix = str.substring(x);
  22. String prefix = new StringBuilder(suffix).reverse().toString();
  23. String mid = shortestPalindrome(str.substring(0, x));
  24.  
  25. return prefix+mid+suffix;
  26. }
  27.  
  28. public static void main(String[] args) {
  29.  
  30. Scanner in = new Scanner(System.in);
  31.  
  32. System.out.println("Enter a String to find out shortest palindrome");
  33.  
  34. String str=in.nextLine();
  35.  
  36. System.out.println("Shortest palindrome of "+str+" is "+shortestPalindrome(str));
  37.  
  38. }
  39.  
  40. }
Output:

  1. Enter a String to find out shortest palindrome
  2. java
  3. Shortest palindrome of java is avajava

find shortest palindrome in java program

Baca selengkapnya

Minggu, 19 Juni 2016

Validate email address using javascript

  • One of the famous interview question in JavaScript : how to validate email address in JavaScript.
  • In order to validate a text field of HTML we need a JavaScript function.
  • On submit form we need to call a java script function to validate all fields in the form also known as client side validation.
  • Now on form submit we need to check email text field and validate it whether entered email is in correct format or not for ex: instanceofjava@gmail.com. 



JavaScript program for email validation:

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <script>
  5. function validateEmailForm() {
  6.     var x = document.forms["Form_Name"]["txt_email"].value;
  7.     var atpos = x.indexOf("@");
  8.     var dotpos = x.lastIndexOf(".");
  9.     if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length) {
  10.         alert("Not a valid e-mail address");
  11.         return false;
  12.     }
  13. }
  14. </script>
  15. </head>
  16.  
  17. <body>
  18. <form name="Form_Name" action="User_email_validation.jsp" onsubmit="return
  19. validateEmailForm();" method="post">
  20. Email: <input type="text" name="txt_email">
  21. <input type="submit" value="Submit">
  22. </form>
  23. </body>
  24.  
  25. </html>

Validate email in java-script using regular expression: on submit form validation

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <script>
  5. function validateEmailForm() {
  6.     var email = document.forms["Form_Name"]["txt_email"].value;
  7.   
  8.  var re = /\S+@\S+\.\S+/;
  9.     return re.test(email);
  10.   
  11.     }
  12. }
  13. </script>
  14. </head>
  15.  
  16. <body>
  17. <form name="Form_Name" action="User_email_validation.jsp" onsubmit="return
  18. validateEmailForm();" method="post">
  19. Email: <input type="text" name="txt_email">
  20. <input type="submit" value="Submit">
  21. </form>
  22. </body>
  23.  
  24. </html>


javascript program for email validation


HTML 5 Email validation:



  1. <form>
  2. <input type="email" placeholder="Enter your email">
  3. <input type="submit" value="Submit">
  4. </form>
email address validation code in java script

Baca selengkapnya

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
Baca selengkapnya

Sabtu, 18 Juni 2016

Difference between Collections and Collection in java with example program

  • 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

    Baca selengkapnya

    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.
    Baca selengkapnya