java

How to in java






A: 
Why we need this ?

Some time we want static array (e.g. months in year). Defining arraylist in such scenarios is not effective. Also with fix arrays it is very easy to maintain indexes.
Can be used only if you are sure that size will not changed in future (In that case u have to manually changed data).

//Define Array in Java
String[] myString = new String[12];
//Initialize array probably in constructor
Arrays.fill(myString,"0");
//Fill array with some other string
myString[3]="I am replaced");
//get Comma Seperated String
Sting commaSeperated = Arrays.toString(myString).repplace("[","").replace("]","");

^ TOP

A: 

JDOM is nice and easy to play with xml in java.

First you should have jdom.jar in your classpath and build for all the api to work. Go to http://www.jdom.org/ to download jar file.

Creating XML trough JDOM

//First create xml file
String fileName = "myXml.xml";
//boolean to check if this is first record
boolean firstRecord=false;
if(new File(fileName).exists()){
//Then may be update existing xml
}else{
//Create new file.
}

//Create SAXBuilder object. JDOM uses both SAX for DOM to manipulate XML.
SAXBuilder builder = new SAXBuilder();
//Create JDOM Object
 private JDOMParser parser = new JDOMParser();
//Create Document Object
Document doc = null;
//You can check if file contain any record
//If file is empty then it is first record and start with creating root element or add //node to existing xml file.

if(new File(fileName).length==0)
firstRecord = true; 

if(firstRecord)
doc = builder.build(fileName);

//Function to add new record
//If this is first record in file, then create root element else just append to root element

void addNewRecord(String myRecord){

//Create root element
Element root = null;
//if this is brand new record. Create root element
if(doc==null)
root = new Element("root");
else
root = doc.getRootElement();

// Now add element below root
Element firstChild = new Element("firstChild");
//append this child to root
root.addContent(firstChild);
//This will cereate xml of form <root><firstChild></firstChild></root>
//create element to add your data
Element myData = new Element("myData");
//Assign text value of data
myData.addText(myRecord);
//add data to fist child
firstChild.addContent(myData); 
//output would be <root><firstChild><myData>Hey</myData></firstChild></root>
//Now Define output formate
            XMLOutputter output = new XMLOutputter();
            Format newFormat = output.getFormat();
            newFormat.setIndent("\t");
            newFormat.setLineSeparator("\n");
            output.setFormat(newFormat);
//Write data to file and also check if this is append or adding new data
try {
                FileWriter fw = new FileWriter(fileName,false);
                if(this.doc==null)                    
                output.output(new Document(root), fw);
                else
                output.output(this.doc.getRootElement(), fw);
                fw.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

}
}//End of Method addnewRecord

//Method to check if record is already present in xml

boolean isRecordAlreadyPresent(String uniqueKey){
    
    
        if(!isFirstRecord){
        List chart = this.doc.getRootElement().getChildren();
        //List chart = root.getChildren("root");
        Iterator i = chart.iterator();
        while(i.hasNext()){
            Element chartData = (Element)i.next();
            if(chartData.getChildText("uniqueKey").equals(uniqueKey)){                
                this.isRecordPresent=true;
                break;    
            
        }
        }
        }
        return this.isRecordPresent;        
    }//End of method 
isRecordAlreadyPresent

//Method to update existing record. Only if record is already present

 void updateExistingRecord(ChartObject chartObject,String uniqueKey){

        Element root = this.doc.getRootElement();
        List chart = this.doc.getRootElement().getChildren();
        Iterator i = chart.iterator();
        while(i.hasNext()){
            Element chartData = (Element)i.next();
            
            
            if(chartData.getChild("uniqueKey").getText().equals(uniqueKey)){
                   chartData.getChild("myData").setText(your text);
                                break;
            }
        }
        
    }//End of method updateExistingRecord

Q: How to define collection to hold unique and sorted value?

SortedSet<String> allYear = new TreeSet<String>();
allYear.add("Your Data");

//You can Override comparable method to change sorting criteria.

Hashset give unique value but values are not sorted.

Q:How enum work in java

//Enum ............
//This code will restrict AllowedSize to be only SMALL,MEDIUM,HUGE.
//Actually by doing this no way user can pass other option than these


class Coffee{
       enum AllowdSize {SMALL,MEDIUM,HUGE}; // Note that this semicolon is optional {Strange}
       //But not always true .... will come to know shortly ....
       //Very important, enum can not be declared in a METHOD ... not even main
       //Internally java do something this to enum
       /*class AllowdSize{
        * public static final AllowdSize SMALL = new AllowdSize("SMALL",0);
        *  public static final AllowdSize MEDIUM = new AllowdSize("MEDIUM",1);
        *  public static final AllowdSize HUGE = new AllowdSize("HUGE",2);
        *  }
        */
       private AllowdSize Size;
       Coffee(AllowdSize size){
       this.Size=size;
       }
       AllowdSize getsize(){
               return Size;
       }

}

//By looking at above code one might think why to use enum instead of public static final
//Well we could do more on enum like suppose we want to associate ounce with each size
//note that enum is like a class in java so ...


enum AllowedSizeWithOunce {
       SMALL(8),MEDIUM(10),HUGE(15);
       private int Ounce;
         AllowedSizeWithOunce(int Ounce) { //This method can not be declared public Reason ????? (We should not create instance of this class)
               this.Ounce=Ounce;
       }

       public int GetOunce(){
               return Ounce;
       }
}

class CofeeWithOunce{
       AllowedSizeWithOunce allowedsizewithounce;
       public CofeeWithOunce(AllowedSizeWithOunce allowedsizewithounce) {
               this.allowedsizewithounce = allowedsizewithounce;
       }
       public int GetOunce(){
               return allowedsizewithounce.GetOunce();
       }

}

//Not enuf ??????? well we could do some more thing on enum
//since enum is like a class so we can override the method in the enum itself to behave differently
//for example suppose we have some bar code associated with each size and we don't want same code to be returned
//by each size. then we can define something look like anonymous class (What is this ????? if someone explain this that would be great)

enum AllowedSizeWithBarcode{
       SMALL(8),MEDIUM(10),HUGE(15){
               public String GetBarCode(){ //Override the method defined in the AllowedSizeWithBarcode
                       return "A";
               }
       }; // Note that this semicolon is required when we have body
       private int Ounce;
       AllowedSizeWithBarcode(int Ounce) { //Second time remember ... this can not be public
               this.Ounce = Ounce;
       }
       public int GetOunce(){
               return Ounce;
       }
       public String GetBarCode(){
               return "B";
       }

}

class CofeeWithBarcode{
       private AllowedSizeWithBarcode allowedsizewithbarcode;
       public CofeeWithBarcode(AllowedSizeWithBarcode allowedsizewithbarcode) {
               this.allowedsizewithbarcode = allowedsizewithbarcode;
       }
       public int GetOunce(){
       return allowedsizewithbarcode.GetOunce();
       }
       public String getBarCode(){
               return allowedsizewithbarcode.GetBarCode();
       }

}
public class Enum_test {

       /**
        * @yogi args
        */
       public static void main(String[] args) {
               // TODO Auto-generated method stub

               Coffee drink = new Coffee(Coffee.AllowdSize.HUGE);
               drink.getsize();
               CofeeWithOunce drinkwithounce = new CofeeWithOunce(AllowedSizeWithOunce.HUGE);
               //drinkwithounce.allowedsizewithounce = AllowedSizeWithOunce.HUGE;
               int Size = drinkwithounce.GetOunce();
               System.out.println("Size is  "+Size);
               CofeeWithBarcode drinkwithbarcode1 = new CofeeWithBarcode(AllowedSizeWithBarcode.SMALL);
               CofeeWithBarcode drinkwithbarcode2 = new CofeeWithBarcode(AllowedSizeWithBarcode.HUGE);
               System.out.println("For Bar Code Small size has Size = "+drinkwithbarcode1.GetOunce()+"  Barcode =  "+drinkwithbarcode1.getBarCode());
               System.out.println("For Bar Code Huge size has Size = "+drinkwithbarcode2.GetOunce()+"  Barcode =  "+drinkwithbarcode2.getBarCode());


       }

}

//Important point about enum
//We can not declare enum inside a method
//We can not have public costructor for the enum (enum constructor will be invoked automatically based on the argument)
//for example SMALL(8) will invoke enum costructor. Moreover by defining something like this we are forcing ourself
//to define constructor otherwise it will give compile time error (Type safe ?????)
//You can any time overload enum constructor e.g we can define something like SMALL(8,"A")

^ TOP
Q: How to send mail in java ?
//Before this import mail.jar and activation.jar

import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class MailSender {

/**
* @param args
*/
public static void main(String[] args) throws MessagingException {
// TODO Auto-generated method stub

Properties props= new Properties();
props.put("mail.smtp.host","your host name");
Session session = Session.getDefaultInstance(props);
session.setDebug(true);
MimeMessage message = new MimeMessage(session);
message.setSubject("Order Confirmation");
message.setText("Thanks");
InternetAddress addressFrom = new
InternetAddress ("your email address");
message.setFrom(addressFrom);
InternetAddress adressTo = new
InternetAddress("your email address");
message.setRecipient(Message.RecipientType.TO,adressTo);
Transport.send(message);
}

}

^ TOP
Q: can we override static method in java?

Simple answer is NO. See Example.

class A{
       static void Method1(){
               System.out.println("Hi I am in A");
       }
}

class B extends A{
//This is not overriding it is just redefinition.
       static void Method1(){
               System.out.println("Hi I am in B");
       }
       
       
        /* Rule 1: Can Not Overrride Static method Compile time error
         *
       void Method1(){
               System.out.println("Overriding it");
       }
       */
       
       static int b=5;
       int a=6;
       static void Method2(){
               System.out.println("Static member b is "+b);
               //Rule 2:Can Not have non static variable or method in a static method
               //System.out.println("Non Static Member a is  "+a);
       }
       
}


public class Static_Test {

       /**
        * @yogi args
        */
       public static void main(String[] args) {
               // TODO Auto-generated method stub
 A a = new A();
 a.Method1(); // Can call static method using object ... but useless here "a" will be replace by "A" by compiler.
 A.Method1();
 //Method1();
 B b = new B();
 B.Method1(); //will call static method of B. once again Note that this is redefinition not overriding.
 b.Method1();
 A a1=new A();
 a1 = b;
 a1.Method1(); //Strange ??? here object type is b but instance of a is called .... 

Static methods are inherited but not Polymorphic. When a static method is called, it isn't called with a specific object instance. So you know exactly which method will be called at compile time and polymorphism is not possible.

^ TOP



Subpages (1): java2
Comments