Thursday, 14 July 2016

How to Add and Fetch Class Data from List in Java

  • One of the most concept which is used in interview question as well as in program level . because if we add object into list and print the reference it will print whole data not referece
  • But if we add Class level data it will print reference so we need to perform type casting so easily we can fetch the record and print it 
programme:-



/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package highleveljava;

import java.util.*;

/**
 *
 * @author Admin
 */
public class GenericType {
    /*
     Global Variable
     */

    public static String customername;
    public static String customerid;
    public static String customerlocation;

    /*
     Setter and getter
     */
    public static String getCustomername() {
        return customername;
    }

    public static void setCustomername(String customername) {
        GenericType.customername = customername;
    }

    public static String getCustomerid() {
        return customerid;
    }

    public static void setCustomerid(String customerid) {
        GenericType.customerid = customerid;
    }

    public static String getCustomerlocation() {
        return customerlocation;
    }

    public static void setCustomerlocation(String customerlocation) {
        GenericType.customerlocation = customerlocation;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here

        /*
         set the variable value
         */
        GenericType classobject = new GenericType();
        classobject.setCustomername("Anand");
        classobject.setCustomerid("101");
        classobject.setCustomerlocation("Bangalore");
        /*
         Add Class reference into list
         */
        List<GenericType> list = new ArrayList<GenericType>();
        list.add(classobject);
    
        /*
         Fetch class level data
         */
        customername = ((GenericType) list.get(0)).getCustomername();
        customerid = ((GenericType) list.get(0)).getCustomerid();
        customerlocation = ((GenericType) list.get(0)).getCustomerlocation();

        /*
         Lets Print the data
         */
        System.out.println("\t" + customername + "\t" + customerid + "\t" + customerlocation);
    }

}



Thanks  for More Details Comment here !  

Monday, 11 July 2016

Nested while loop in java

Placing one while loop with in the body of another while is called Nested while loop in java programm.


CODE

public class NestedWhileExample
{
    public static void main(String arg[])
    {
        int outer = 1;
        while(outer < 3)
        {
            int inner = 5; 
            while(inner < 8)
            {
                System.out.println(outer + "  " + inner);
                inner++;
            }
            outer++;
        }
    
    }
}


Output :
1 5
1 6
1 7
2 5
2 6
2 7



DESCRIPTION
Here outer loop is executed for values going from 1 till less than 3 i.e. 1 and 2. Similarly inner loop is executed from 5 till less than 8 i.e. 5, 6 and 7. So when outer is 1, inner will become 5, 6, and 7 and when outer is 2, then also inner will become 5, 6, and 7.

Saturday, 9 July 2016

How to wait on file creation in Java

Here are some steps that we can remember while move in to coding part
  1. Iterate the (!file.exist()) blog till this block becomes as a false . so for that we can use Thread class and do Thread.sleep(10). that will wait for 10ns  and once time has been expire again it start same loop . means every 10 ns it will check on directory whether file is exist or not . if not then iterate.
  2.  once it got the file on directory then while loop iteration will stop and terminate the execution of while block  
Programme to wait on file creation in Java



/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

import java.io.*;

/**
 *
 * @author Anand
 */
public class FileOperation {

    public void ProcessFile() {
        File statText = new File("statsTest1.txt");// Check for this file
        while (!statText.exists()) {
            try {
                Thread.sleep(10);//wait for 10 ns
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        System.out.println("Finally got the =>"+statText.getName());

    }

    public static void main(String[] args) {
        FileOperation write = new FileOperation();
        write.ProcessFile();
    }
}

For any query Ask Here . happy Coding

Anand

Null Pointer Exception Class Implementation in Java

Here is the implementation of NullPointerException class in Java : -

  1   /*
    2    * Copyright (c) 1994, 2011, Oracle and/or its affiliates. All rights reserved.
    3    * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
    4    *
    5    * This code is free software; you can redistribute it and/or modify it
    6    * under the terms of the GNU General Public License version 2 only, as
    7    * published by the Free Software Foundation.  Oracle designates this
    8    * particular file as subject to the "Classpath" exception as provided
    9    * by Oracle in the LICENSE file that accompanied this code.
   10    *
   11    * This code is distributed in the hope that it will be useful, but WITHOUT
   12    * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
   13    * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
   14    * version 2 for more details (a copy is included in the LICENSE file that
   15    * accompanied this code).
   16    *
   17    * You should have received a copy of the GNU General Public License version
   18    * 2 along with this work; if not, write to the Free Software Foundation,
   19    * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
   20    *
   21    * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
   22    * or visit www.oracle.com if you need additional information or have any
   23    * questions.
   24    */
   25  
   26   package java.lang;
   27  
   28   /**
   29    * Thrown when an application attempts to use {@code null} in a
   30    * case where an object is required. These include:
   31    * <ul>
   32    * <li>Calling the instance method of a {@code null} object.
   33    * <li>Accessing or modifying the field of a {@code null} object.
   34    * <li>Taking the length of {@code null} as if it were an array.
   35    * <li>Accessing or modifying the slots of {@code null} as if it
   36    *     were an array.
   37    * <li>Throwing {@code null} as if it were a {@code Throwable}
   38    *     value.
   39    * </ul>
   40    * <p>
   41    * Applications should throw instances of this class to indicate
   42    * other illegal uses of the {@code null} object.
   43    *
   44    * {@code NullPointerException} objects may be constructed by the
   45    * virtual machine as if {@linkplain Throwable#Throwable(String,
   46    * Throwable, boolean, boolean) suppression were disabled and/or the
   47    * stack trace was not writable}.
   48    *
   49    * @author  unascribed
   50    * @since   JDK1.0
   51    */
   52   public
   53   class NullPointerException extends RuntimeException {
   54       private static final long serialVersionUID = 5162710183389028792L;
   55  
   56       /**
   57        * Constructs a {@code NullPointerException} with no detail message.
   58        */
   59       public NullPointerException() {
   60           super();
   61       }
   62  
   63       /**
   64        * Constructs a {@code NullPointerException} with the specified
   65        * detail message.
   66        *
   67        * @param   s   the detail message.
   68        */
   69       public NullPointerException(String s) {
   70           super(s);
   71       }
   72   }



  • you could fine Same thing when you click on NullPointerException from any IDE like Eclipse or netbeans 


Thanks 

Monday, 27 June 2016

how to create File and write into file in Java

How to create File and write into that using java

  • IO package is used to perform Input/Output operation or file operation .  
    package Name:--> import java.io
  • FileWriter is used to check file is there or not if not it will throw "File not found Exception ". but we can overcome this problem using
       FileWriter fw = new FileWriter(file.getAbsoluteFile());
       if(!file.exists()){
       file.createNewFile();//Force to create File with Empty content
       }
  • File operation will force to progammer to put File operation code inside try catch else throw IO Exception because JVM don't know run time wheather file is avilable on directroy or not .or any other reason that is handle by IO Exception 
Example :-


import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class FileOperation {
public static void main(String[] args) {
String filepath=null;
// TODO Auto-generated method stub

try {
filepath=System.getProperty("user.home")+System.getProperty("file.separator")+"Hello.txt";
System.out.println(filepath);
File file = new File(filepath);

if (!file.exists()) {//File is already there 
FileWriter fw = new FileWriter(file.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
bw.write("Hi Anand");
bw.newLine();
bw.write("welcome in Java World");
bw.close();
}else{
file.createNewFile();//Force to create File with Empty content
System.out.println("File created With Empty Content");
}

System.out.println("File created and write sucessfully");

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

Sunday, 26 June 2016

Genric Data Type in Java


Java Generic Type will  enable programmers to specify, specific Data type in Java .we can use Generic for class,Method,Collection.

*  Suppose if we take example of Hashset normally when we create Object of set it will allow all data type in reference . so while retrieving value we need to perform type casting because we don't know which type of Data it is .

* So to overcome typecasting problem and enable to add only one type on data in reference   of set we use generic in Java

 --> How to create Generic type in Java
   Set<String> hashset=new HashSet<String>();//it will allow to add only String type
and while retrieving  no need to perform typecasting .

*   if we try to add other then String type then it will compile time error like "The method add(String) in the type Set<String> is not applicable for the arguments (int)"

==============Code of Generic in Collection ================


import java.util.*;


public class GenericType {
/*
 ** author:Anand
 */
  public static void main(String[] args){
   String value=null;
   //Let's create Hashset Object with Genric Data type
  Set<String> hashset=new HashSet<String>();//it will allow only String type to add on Reference
  hashset.add("Bangalore");
  hashset.add("Chennai");
  hashset.add("Hyderabad");
  Iterator<String> itr=hashset.iterator();//Iterate only String object
  while(itr.hasNext()){
   value=itr.next();
   System.out.println(value);
  }

 }
}

Saturday, 14 May 2016

How to Find Duplicate String in Java

Since we all known HashSet is a part of Collection that will store unique value always 
>  if we are trying to add any duplicate value add method return  false.
> add Method check existing Object Hashcode and compare with  newly added Object
if hashCode match then add method Return False else Return True .
>here we created HashSet<String> Object with generic type data type
>since we Added <String> After HashSet then it only allows to add String value
>generic type is only use to overcome data type casting problem 
..
Please Check below programmer 




/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package javainterview;
import java.util.*;

/**
 *
 * @author shiboo
 */
public class Duplicate {
    
    public static void main(String[] args) {
        
        String [] arr= {"Anand","Ajeet","Antrish","Anand"};
        HashSet<String>hset= new HashSet<String>();
        for(String value:arr){
        if(!hset.add(value)){
            System.out.println("Duplicate Value=>"+value);
        }
        }
        
    }
    
}


Map class field to map

 import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; public class AutogeneratedClassMapper {     public static M...