顯示具有 java 標籤的文章。 顯示所有文章
顯示具有 java 標籤的文章。 顯示所有文章

2022年5月20日 星期五

正則表達式 (regex) 各程式語言使用方法 (part 5)

0

#Java

public class RegexTestStrings {
  public static final String EXAMPLE_TEST = "This is my small example "
      + "string which I'm going to " + "use for pattern matching.";

  public static void main(String[] args) {
    System.out.println(EXAMPLE_TEST.matches("\\w.*"));
    String[] splitString = (EXAMPLE_TEST.split("\\s+"));
    System.out.println(splitString.length);// should be 14
    for (String string : splitString) {
      System.out.println(string);
    }
    // replace all whitespace with tabs
    System.out.println(EXAMPLE_TEST.replaceAll("\\s+", "\t"));
  }
} 


#PHP

$str = 'a1234';
if (preg_match("/^[a-zA-Z0-9]{4,16}$/", $str)) {
    echo "驗證成功";
} else {
    echo "驗證失敗";
}

#perl 
print $str = "a1234" =~ m:^[a-zA-Z0-9]{4,16}$: ? "COMFIRM" : "FAILED";




Java call SQL

0


Class.forName(GlobalConstants.DB_DRIVER);
Connection conn = DriverManager.getConnection(GlobalConstants.DB_URL,GlobalConstants.DB_USER,GlobalConstants.DB_PWD);
 
String sql = "SELECT DISTINCT location FROM servicedoffices ORDER BY location";
PreparedStatement stmt = conn.prepareStatement(sql);
ResultSet rs = stmt.executeQuery();

  Vector locationList = new Vector();
  while(rs.next()){
    locationList.add(rs.getString("location"));
    locationList.add(rs.setTimestamp("Time"));

  }
rs.close();
stmt.close();
conn.close();



Java Date API

0

Java Date API
Java date to string(日期轉字串)
#import java.text.SimpleDateFormat;
#import java.util.Date;
#java.util.Calendar;



//目前時間

Date date = new Date();

//設定日期格式

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

//進行轉換

String dateString = sdf.format(date);

System.out.println(dateString);

           
Java string to date(字串轉日期)
#

//欲轉換的日期字串

String dateString = "2010-03-02 20:25:58";

//設定日期格式

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

//進行轉換

Date date = sdf.parse(dateString);

System.out.println(date);

Add Date
#


String dt = "2008-01-01";  // Start date
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

Calendar c = Calendar.getInstance();
c.setTime(sdf.parse(dt));
c.add(Calendar.DATE, 1);  // number of days to add
dt = sdf.format(c.getTime());  // dt is now the new date

Difference in days between two dates in Java?
#

    Calendar calendar1 = Calendar.getInstance();
    Calendar calendar2 = Calendar.getInstance();


    calendar1.set();
    calendar2.set();
    long milliseconds1 = calendar1.getTimeInMillis();
    long milliseconds2 = calendar2.getTimeInMillis();
    long diff = milliseconds2 - milliseconds1;
    long diffSeconds = diff / 1000;
    long diffMinutes = diff / (60 * 1000);
    long diffHours = diff / (60 * 60 * 1000);
    long diffDays = diff / (24 * 60 * 60 * 1000);

    System.out.println("\nThe Date Different Example");
    System.out.println("Time in milliseconds: " + diff + " milliseconds.");
    System.out.println("Time in seconds: " + diffSeconds + " seconds.");
    System.out.println("Time in minutes: " + diffMinutes + " minutes.");
    System.out.println("Time in hours: " + diffHours + " hours.");
    System.out.println("Time in days: " + diffDays + " days.");




check if date() is monday?
#



Calendar cal = Calendar.getInstance();
cal.setTime(theDate);
boolean monday = cal.get(Calendar.DAY_OF_WEEK) == Calendar.MONDAY;

Java Get Hours / Minutes
#
Date date = new Date();   // given date
Calendar calendar = GregorianCalendar.getInstance(); // creates a new calendar instance
calendar.setTime(date);   // assigns calendar to given date 
calendar.get(Calendar.HOUR_OF_DAY); // gets hour in 24h format
calendar.get(Calendar.HOUR);        // gets hour in 12h format
calendar.get(Calendar.MONTH);       // gets month number, NOTE this is zero based!

2013年2月28日 星期四

用Java替中文網址轉碼:URLEncoder

0


用Java替中文網址轉碼:URLEncoder


在程式或者網頁的應用中我們常常需要把中文轉換為其他編碼

下面介紹這些也不僅僅限於轉換網址而已


在我目前的應用中只用過了JAVA
使用的函數是 URLEncoder.encode(String 字串, String 編碼)
(編碼為:UTF-8, UTF-16等等)
以下是節錄自用javascript轉UTF-8編碼的編碼解碼介紹

#Java#
會處理#字元為%23,空白字元轉換為+,中文字拆開每BYTE處理為ASCII

第二個String 為Locale

java.net.URLEncoder.encode(String args,String args)

java.net.URLDecoder.decode(String args,String args)




URLEncoder.encode("random word £500 bank $", "ISO-8859-1");
String s = "許功蓋";
URLEncoder.encode(s, "UTF-8")

Java API URLEncoder
http://docs.oracle.com/javase/1.4.2/docs/api/java/net/URLEncoder.html






URL Encoding Reference

ASCII CharacterURL-encoding
space%20
!%21
"%22
#%23
$%24
%%25
&%26
'%27
(%28
)%29
*%2A
+%2B
,%2C
-%2D
.%2E
/%2F
0%30
1%31
2%32
3%33
4%34
5%35
6%36
7%37
8%38
9%39
:%3A
;%3B
<%3C
=%3D
>%3E
?%3F
@%40
A%41
B%42
C%43
D%44
E%45
F%46
G%47
H%48
I%49
J%4A
K%4B
L%4C
M%4D
N%4E
O%4F
P%50
Q%51
R%52
S%53
T%54
U%55
V%56
W%57
X%58
Y%59
Z%5A
[%5B
\%5C
]%5D
^%5E
_%5F
`%60
a%61
b%62
c%63
d%64
e%65
f%66
g%67
h%68
i%69
j%6A
k%6B
l%6C
m%6D
n%6E
o%6F
p%70
q%71
r%72
s%73
t%74
u%75
v%76
w%77
x%78
y%79
z%7A
{%7B
|%7C
}%7D
~%7E
 %7F
`%80
%81
%82
ƒ%83
%84
%85
%86
%87
ˆ%88
%89
Š%8A
%8B
Œ%8C
%8D
Ž%8E
%8F
%90
%91
%92
%93
%94
%95
%96
%97
˜%98
%99
š%9A
%9B
œ%9C
%9D
ž%9E
Ÿ%9F
 %A0
¡%A1
¢%A2
£%A3
¤%A4
¥%A5
¦%A6
§%A7
¨%A8
©%A9
ª%AA
«%AB
¬%AC
%AD
®%AE
¯%AF
°%B0
±%B1
²%B2
³%B3
´%B4
µ%B5
%B6
·%B7
¸%B8
¹%B9
º%BA
»%BB
¼%BC
½%BD
¾%BE
¿%BF
À%C0
Á%C1
Â%C2
Ã%C3
Ä%C4
Å%C5
Æ%C6
Ç%C7
È%C8
É%C9
Ê%CA
Ë%CB
Ì%CC
Í%CD
Î%CE
Ï%CF
Ð%D0
Ñ%D1
Ò%D2
Ó%D3
Ô%D4
Õ%D5
Ö%D6
×%D7
Ø%D8
Ù%D9
Ú%DA
Û%DB
Ü%DC
Ý%DD
Þ%DE
ß%DF
à%E0
á%E1
â%E2
ã%E3
ä%E4
å%E5
æ%E6
ç%E7
è%E8
é%E9
ê%EA
ë%EB
ì%EC
í%ED
î%EE
ï%EF
ð%F0
ñ%F1
ò%F2
ó%F3
ô%F4
õ%F5
ö%F6
÷%F7
ø%F8
ù%F9
ú%FA
û%FB
ü%FC
ý%FD
þ%FE
ÿ%FF

2013年1月24日 星期四

Java Synchronized 筆記

0

Java Synchronized 筆記 最近寫程式遇到各個 Thread 之間共用資料保護的問題,做了點功課,寫下一些小筆記。
簡單介紹
Synchronized使用時,需指定一個物件,系統會Lock此物件,當程式進入Synchrnoized區塊或Method時,該物件會被Lock,直到離開Synchronized時才會被釋放。在Lock期間,鎖定同一物件的其他Synchronized區塊,會因為無法取得物件的Lock而等待。待物件Release Lock後,其他的Synchronized區塊會有一個取得該物件的Lock而可以執行。
各種用法
1. Synchronized Method
synchronized public void syncMethod() {
…
}

此種synchronized用法鎖定的物件為Method所屬的物件,只要物件被new出超過一個以上的Instance,就有可能保護不到Method內程式。但如果此物件只會被new出一個Instance,譬如new出來後就放到ServletContext,要用的時候從ServletContext中拿出來執行,就可以避免此情況。
2. Synchronized Static Method
synchronized static public void syncMethod() {
…
} 

此種synchronized用法鎖定的物件為Method所屬的物件的Class,不管被new出幾個的Instance,都能夠保證同一個時間只會有一個Thread在執行此Method。
3. Synchronized(this)
public void syncMethod() {
  synchronized(this) {
    …
  }
} 

此種synchronized用法與synchronized method用法一樣,都是鎖定Method所屬的物件本身。
4. Synchronized(SomeObject)
public void syncMethod() {
  synchronized(SomeObject) {
    …
  }
} 

此種synchronized用法鎖定的是SomeObject,如果SomeObject是同一個Class的兩個不同Instance,那synchronized區塊內就有可能被同時執行。如果每一個Synchronized的SomeObject都是同一個Instance(或者SomeObject本身就是Static),就可以保證區塊內同時間只會有一個Thread執行。

當使用Synchornized(SomeObject)時,SomeObject本身處於被Lock狀態,但此時其他的Thread是可以去更改SomeObject裡面的值,Lock只是同步化的狀態,不表示不能更改資料。
使用時機
Synchronized的使用時機很難定義,比較常見的情況是,當程式中會取出某一個共用的物件且會判斷物件內容值,再更新物件內容,此情況大部分都需要synchronized保護。

2013年1月15日 星期二

Java Class Libraries - Time (Alvin API)

0

#

import java.util.*;
public class Timer
{
  public static void main(String args[])
  {
// create start and end calendar objects
    Calendar sTime=Calendar.getInstance();
    Calendar eTime=Calendar.getInstance();
// now set times -- add routines to get from sio or file
// be sure to verify times are in range !!
// adjust times for early start and late finish
    sTime.set(Calendar.HOUR_OF_DAY,8);sTime.set(Calendar.MINUTE,0);
    eTime.set(Calendar.HOUR_OF_DAY,16);eTime.set(Calendar.MINUTE,0);
    long span=timeSpan(sTime,eTime);
// adjust time for lunch hour here
    long secs=span/1000;long mins=secs/60;long hours=mins/60;
    System.out.println(hours);
    System.out.println(mins);
  }
// timeSpan (calendarObject,calendarObject) returns long milliseconds
  public static long timeSpan(Calendar calStart,Calendar calEnd)
  {
    Date sTime1,eTime1;long interval,sTime2,eTime2;
    sTime1=calStart.getTime();eTime1=calEnd.getTime(); // to Date objects
    sTime2=sTime1.getTime();eTime2=eTime1.getTime(); // to long objects
    interval=eTime2-sTime2;return interval;
  }
}

Java Class Libraries - DateFormat (Alvin API)

0

Java Class Libraries - DateFormat
#

import java.text.*; import java.util.*;
public class DateFormat
{
  
    
    public static String getCurrencyFormat(double currency , String format){        
            String pattern = format;            
            DecimalFormat df = new DecimalFormat(pattern);  
            String s ="$ " +  df.format(currency);           
            return s;
        } 
    public static String getCurrentTime(String format){
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        Date d = new Date(System.currentTimeMillis());
        String timeStamp = sdf.format(d);
        return timeStamp;
    }
    
    public static String getToday(String format){
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat dateFormat = new SimpleDateFormat(format);
        String today =null;
        try {
            today = dateFormat.format(calendar.getTime());
                                      
        } catch (Exception e) {
            e.printStackTrace();
        }
        return today;
    }
    
    public static String getdate(Timestamp d , String format){
        SimpleDateFormat dateFormat = new SimpleDateFormat(format);
        String day =null;
        try {
            day = dateFormat.format(d.getTime());
                                      
        } catch (Exception e) {
            e.printStackTrace();
        }
        return day;
    }

    public static String stringChecking( String s){
        String text = "" ;
       
            for (int i = 0; i < s.length(); i++){
                if ( s.substring(i,i+1).equals("'") )
                    text +="\\"+ s.substring(i,i+1);
                else 
                    text += s.substring(i,i+1);
                }
        return text;
    }



}

Java Class Libraries - Company (Alvin API)

0

Java Class Libraries - Company
#

public class Person
{
private int age;
private String firstName;
private String lastName;
private String nameString;
private String ageString;

public Person(String firstName, String lastName, int age)
{
this.age = age;
this.firstName = firstName;
this.lastName = lastName;
}

public void printName() 
{
System.out.println(nameString);
}

public void printAge()
{
System.out.println(ageString);
}

public void printAgeGroup()
{
System.out.println(nameString);
System.out.println(ageString);
}


}



}
} 


#
public class Employee
{
private double currentSalary;
private double newSalary;
private java.lang.String name;
public Employee()
{
name = "Last, First";
currentSalary = 0;
}

public Employee (String n)
{
name = n;
}

public String getName()
{
return name;
}

public double getSalary()
{
return currentSalary;
}

public Employee (String n, double cs)
{
name = n;
currentSalary = cs;

} 

public void raiseSalary (double byPercent)
{
double newSalary = currentSalary * (1 + (byPercent/100));
}

public String toString()
{
String str = "";
str = "Name: " + name + "\n The salary of the employee is " + currentSalary +
"\n The empoyee's salary after the raise is " + ;
return str;
}

}

#
   
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;

public class Company {
  public static void main(String args[]) {
    Employee emps[] = { new Employee("Finance", "Degree, Debbie"),
        new Employee("Finance", "Grade, Geri"),
        new Employee("Finance", "Extent, Ester"),
        new Employee("Engineering", "Measure, Mary"),
        new Employee("Engineering", "Amount, Anastasia"),
        new Employee("Engineering", "Ratio, Ringo"),
        new Employee("Sales", "Stint, Sarah"),
        new Employee("Sales", "Pitch, Paula"),
        new Employee("Support", "Rate, Rhoda"), };
    Set set = new TreeSet(Arrays.asList(emps));
    System.out.println(set);
    Set set2 = new TreeSet(Collections.reverseOrder());
    set2.addAll(Arrays.asList(emps));
    System.out.println(set2);

    Set set3 = new TreeSet(new EmpComparator());
    for (int i = 0, n = emps.length; i < n; i++) {
      set3.add(emps[i]);
    }
    System.out.println(set3);
  }
}

class EmpComparator implements Comparator {

  public int compare(Object obj1, Object obj2) {
    Employee emp1 = (Employee) obj1;
    Employee emp2 = (Employee) obj2;

    int nameComp = emp1.getName().compareTo(emp2.getName());

    return ((nameComp == 0) ? emp1.getDepartment().compareTo(
        emp2.getDepartment()) : nameComp);
  }
}

class Employee implements Comparable {
  String department, name;

  public Employee(String department, String name) {
    this.department = department;
    this.name = name;
  }

  public String getDepartment() {
    return department;
  }

  public String getName() {
    return name;
  }

  public String toString() {
    return "[dept=" + department + ",name=" + name + "]";
  }

  public int compareTo(Object obj) {
    Employee emp = (Employee) obj;
    int deptComp = department.compareTo(emp.getDepartment());

    return ((deptComp == 0) ? name.compareTo(emp.getName()) : deptComp);
  }

  public boolean equals(Object obj) {
    if (!(obj instanceof Employee)) {
      return false;
    }
    Employee emp = (Employee) obj;
    return department.equals(emp.getDepartment())
        && name.equals(emp.getName());
  }

  public int hashCode() {
    return 31 * department.hashCode() + name.hashCode();
  }
}

           

2013年1月4日 星期五

Java 字串 String API 用法大全

0

Java 字串 String API 用法大全

 String是一個比較特別的資料型態,它是一個物件類別( Object ),基本型態所對應的物件類別,可直接給於相同類型的值,而不需使用new來產生物件,而String資料型態跟基本型態一樣可以直接給於值,不過String沒有相對應的基本型態。 String在使用上十分普遍,大部份的資料型能都可以變成String存放。String本身是字串是使用utf8格式存放的,所以在計算字元時,一個中文字跟一個英文字都是算1,這點是跟其它程式語言不太一樣的。

 String的宣告及初始化 “ ”雙引號內資料則為String資料型能

#

 //直接給值
            String a = "123";
            System.out.println("a:"+a);
 
            //new 一個String物件
            String b = new String("456");
            System.out.println("b:"+b);
 
            //先宣告再給值
            String c ;
            c = "789";
            System.out.println("c:"+c);
 
            //先宣告再new一個物件
            String d;
            d = new String("321");
            System.out.println("d:"+d);


字串的連結合併 字串的連結合併是利用 + 來使二個字串變成一個字串
#
         String z = a + b;//二字串變數相加,連結
            System.out.println("二字串變數相加:"+z);
 
            String y = "789"+"123";//二字串相加,連結
            System.out.println("二字串相加:"+y);
 
            String x = 456+"123" ;//數字加字串,連結
            System.out.println("數字加字串:"+x);
String.valueOf 基本型態轉換成字串 利用靜態函數String.valueOf(型態)可以把型能轉變成字串
#

 int num = 123;
        String Snum = String.valueOf(num);
        System.out.println("數字變字串:"+Snum);
        //數字變字串:123
 
        double numf = 123.1;    
        String Snumf = String.valueOf(numf);
        System.out.println("浮點變字串:"+Snumf);
        //浮點變字串:123.1

基本型態物件.parse基本型態 字串轉換成基本型態 利用基本型態物件的函數parse,可以把字轉換成基本型態,如果無法轉換時會有Exception產生
#

 String Sint = "123";
        int myint = Integer.parseInt(Sint);
        System.out.println("字串轉換成數字:"+myint);
        //字串轉換成數字:123
 
        String SFloat = "123.1";
        float myfloat= Float.parseFloat(SFloat);
        System.out.println("字串轉換成浮點數:"+myfloat);
        //字串轉換成浮點數:123.1
 
        String SDouble = "123.2";
        double mydouble= Double.parseDouble(SDouble);
        System.out.println("字串轉換成雙浮點數:"+mydouble);
        //字串轉換成雙浮點數:123.2
 
        //其它型態以此類推...

IndexOf 查詢字元位存在於字串內位置,以0為起始 IndexOf(字串),有找到字串時會回傳第一個字元的位置,IndexOf如查詢不到,則會回傳-1 字串內的內容存放可視為一連續空間,而每一個字元均存放在順序的位置上,如下表所示:
#

 String smart = "Smart";
        int idx = smart.indexOf("m");
        System.out.println("m所在位置:"+idx);
        //m所在位置:1
 
        idx = smart.indexOf("rt");
        System.out.println("rt所在位置:"+idx);
        //rt所在位置:3
 
        idx = smart.indexOf("z");
        System.out.println("z所在位置:"+idx);
        //z所在位置:-1
 
        //中文部份
        String chinese = "中華民國";
        int cidx = chinese.indexOf("民");
        System.out.println("民所在位置:"+cidx);
        //民所在位置:2
 
        cidx = chinese.indexOf("中華");
        System.out.println("中華所在位置:"+cidx);
        //中華所在位置:0
 
        cidx = chinese.indexOf("台灣");
        System.out.println("台灣所在位置:"+cidx);
        //台灣所在位置:-1

replaceAll、replaceFirst字串取代 replaceAll (要被取代的字串,要取代的字串) 取代全部找到的”要被取代字串” replaceFirst (要被取代的字串,要取代的字串) 取代第一個找到的”要被取代字串” 其中replaceAll函數可以使用正規表示式來做整批有規則性的取代
#

 String replaceString = "blog.yslifes.com,blog.yslifes.com";
        String replaced = replaceString.replaceAll("blog", "www");
        System.out.println("All取代後的字串:"+replaced);
        //All取代後的字串:www.yslifes.com,www.yslifes.com
 
        replaced = replaceString.replaceFirst("blog", "www");
        System.out.println("First取代後的字串:"+replaced);
        //First取代後的字串:www.yslifes.com,blog.yslifes.com

String.format字串格式化 String.format是一個靜態函數,可以直接使用,將字串依設定的位置或格式回傳出來。 如需顯示三位數的字串數字,前方補零,則可利用以下方法:
#

String formatStr = "%03d";
        String formatAns = String.format(formatStr, 12);
        System.out.println("數字補零:"+formatAns);
        //數字補零:012

CharAt取得指定字元 CharAt(位置)可取出指定位置的字元,中文算法與英文相同
#

String charStr = "This is my Web site! blog.yslifes.com";
        char c = charStr.charAt(3);
        System.out.println("英文第4位的字元是:"+c);
        //英文第4位的字元是:s
 
        charStr = "這是我的網站! blog.yslifes.com";
        c = charStr.charAt(5);
        System.out.println("中文第5位的字元是:"+c);
        //中文第5位的字元是:站

equals 二字串是否相等 equals可以比較二個字串或物件是否相同,以為Object原型就有的方法,字串要全數相同回傳值才會為true
#

  String aStr = "String A";
 
        String bStr = "String B";
        boolean Equal = aStr.equals(bStr);
        System.out.println("a與b是否相同:"+Equal);
        //a與b是否相同:false
 
        String cStr = "String A";
        Equal = aStr.equals(cStr);
        System.out.println("a與c是否相同:"+Equal);
        //a與c是否相同:true
 
        String dStr = "String A ";
        Equal = aStr.equals(dStr);
        System.out.println("a與d是否相同:"+Equal);
        //a與d是否相同:false

split字串切割 split(指定符號) ,可依指定符號把字串分開成陣列
#
String splitStr = "blog,yslifes,com";
        String[] array = splitStr.split(",");
        for(int i = 0 ; i < array.length ; i ++)
            System.out.println("第"+i+"個:"+array[i]);
        /*
        第0個:blog
        第1個:yslifes
        第2個:com
substring取得指定字串範圍 substring(起始值 , 終始值),可以取出起始位置,到終止位置的字串,其中包含起始值,不包含終始值
#
String subStr = "blog.yslifes.com";
        String sub1 = subStr.substring(1, 4);
        System.out.println("第1到4的字串內容為:"+sub1);
        //第1到4的字串內容為:log

trim去空白 trim()可以去除左邊及右邊二則空白,不過在字串間空白並不會處理
#

String HasEmptyStr = " ABC";
        System.out.println("1空白去除:"+HasEmptyStr.trim());
        //1空白去除:ABC
 
        HasEmptyStr = "ABC ";
        System.out.println("2空白去除:"+HasEmptyStr.trim());
        //2空白去除:ABC
        HasEmptyStr = " ABC ";
        System.out.println("3空白去除:"+HasEmptyStr.trim());
        //3空白去除:ABC
 
        HasEmptyStr = "ABC DEF";
        System.out.println("4空白去除:"+HasEmptyStr.trim());
        //4空白去除:ABC DEF

字串長度 length()可以取回字串的長度
#
String strLength = "長度是多少呢?";
        System.out.println("字串長度:"+strLength.length());
        //字串長度:7
http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/String.html#format(java.lang.String, java.lang.Object...) http://blog.yslifes.com/archives/638

2012年12月14日 星期五

JSP Page 指令

0


JSP Page 指令

內容、字碼設定
<%@ page contentType="text/html;charset=big5" %>
引入套件
<%@ page import="java.util.*" %>
指定錯誤處理頁面
<%@ page errorPage="error.jsp" %>
定義這個網頁是錯誤處理頁面
<%@ page isErrorPage="true" %>
網頁編碼的指定
<%@ page pageEncoding="big5" %>




2012年12月12日 星期三

Vector Example in java

0

In this example we are going to show the use of java.util.Vector class. We will be creating an object of Vector class and performs various operation like adding, removing etc. Vector class extends AbstractList and implements List, RandomAccess, Cloneable, Serializable. The size of a vector increase and decrease according to the program. Vector is synchronized. In this example we are using seven methods of a Vector class. add(Object o): It adds the element in the end of the Vector size(): It gives the number of element in the vector. elementAt(int index): It returns the element at the specified index. firstElement(): It returns the first element of the vector. lastElement(): It returns last element. removeElementAt(int index): It deletes the element from the given index. elements(): It returns an enumeration of the element In this example we have also used Enumeration interface to retrieve the value of a vector. Enumeration interface has two methods. hasMoreElements(): It checks if this enumeration contains more elements or not. nextElement(): It checks the next element of the enumeration. Code of this program is given below: //java.util.Vector and java.util.Enumeration; import java.util.*; public class VectorDemo{ public static void main(String[] args){ Vector vector = new Vector(); int primitiveType = 10; Integer wrapperType = new Integer(20); String str = "tapan joshi"; vector.add(primitiveType); vector.add(wrapperType); vector.add(str); vector.add(2, new Integer(30)); System.out.println("the elements of vector: " + vector); System.out.println("The size of vector are: " + vector.size()); System.out.println("The elements at position 2 is: " + vector.elementAt(2)); System.out.println("The first element of vector is: " + vector.firstElement()); System.out.println("The last element of vector is: " + vector.lastElement()); vector.removeElementAt(2); Enumeration e=vector.elements(); System.out.println("The elements of vector: " + vector); while(e.hasMoreElements()){ System.out.println("The elements are: " + e.nextElement()); } } } Output of this example is given below: C:\Java Tutorial>javac VectorDemo.java C:\Java Tutorial>java VectorDemo the elements of vector: [10, 20, 30, tapan joshi] The size of vector are: 4 The elements at position 2 is: 30 The first element of vector is: 10 The last element of vector is: tapan joshi The elements of vector: [10, 20, tapan joshi] The elements are: 10 The elements are: 20 The elements are: tapan joshi

2012年8月27日 星期一

Java Convert string , double , int, long, Calendear

0


Java Convert string , double , int

Convert String to double
double doubleToString= Double.parseDouble(aString);

Convert String to int
int intToString= Integer.parseInt(aString);

Convert int to String
String aString = Integer.toString( intToString ); // or
aString = "" + intToString;


Convert milliseconds/ long to date format in Calendear    
Calendar calendar = Calendar.getInstance();
long milliSeconds = 86400000;
calendar.setTimeInMillis(milliSeconds);



2012年8月22日 星期三

Primitive Data Types {Java}

0


byte: The byte data type is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive). The byte data type can be useful for saving memory in large arrays, where the memory savings actually matters. They can also be used in place of int where their limits help to clarify your code; the fact that a variable's range is limited can serve as a form of documentation.

short: The short data type is a 16-bit signed two's complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive). As with byte, the same guidelines apply: you can use a short to save memory in large arrays, in situations where the memory savings actually matters.

int: The int data type is a 32-bit signed two's complement integer. It has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive). For integral values, this data type is generally the default choice unless there is a reason (like the above) to choose something else. This data type will most likely be large enough for the numbers your program will use, but if you need a wider range of values, use long instead.

long: The long data type is a 64-bit signed two's complement integer. It has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive). Use this data type when you need a range of values wider than those provided by int.

float: The float data type is a single-precision 32-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in the Floating-Point Types, Formats, and Values section of the Java Language Specification. As with the recommendations for byte and short, use a float (instead of double) if you need to save memory in large arrays of floating point numbers. This data type should never be used for precise values, such as currency. For that, you will need to use the java.math.BigDecimal class instead. Numbers and Strings covers BigDecimal and other useful classes provided by the Java platform.

double: The double data type is a double-precision 64-bit IEEE 754 floating point. Its range of values is beyond the scope of this discussion, but is specified in the Floating-Point Types, Formats, and Values section of the Java Language Specification. For decimal values, this data type is generally the default choice. As mentioned above, this data type should never be used for precise values, such as currency.

boolean: The boolean data type has only two possible values: true and false. Use this data type for simple flags that track true/false conditions. This data type represents one bit of information, but its "size" isn't something that's precisely defined.

char: The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).


Default Values

It's not always necessary to assign a value when a field is declared. Fields that are declared but not initialized will be set to a reasonable default by the compiler. Generally speaking, this default will be zero or null, depending on the data type. Relying on such default values, however, is generally considered bad programming style.
The following chart summarizes the default values for the above data types.
Data TypeDefault Value (for fields)
byte0
short0
int0
long0L
float0.0f
double0.0d
char'\u0000'
String (or any object)  null
booleanfalse



Reference : http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html