tag:blogger.com,1999:blog-78797371904707842602024-02-19T09:13:48.569-08:00Let's Learn Java APIKanishka Dilshanhttp://www.blogger.com/profile/08604043101957122711noreply@blogger.comBlogger10125tag:blogger.com,1999:blog-7879737190470784260.post-35429985234502876102010-10-03T08:49:00.000-07:002010-10-03T08:49:35.118-07:00Determine user details from a Java programWhen we want to get details of the host pc from a java program , we can use the <span style="font-family: "Courier New",Courier,monospace;">getProperty()</span> method of System class in java.lang package. According to the java documentation(SE6) we can get following information using this class.<br />
<table border="1" summary="Shows property keys and associated values"><tbody>
<tr><th style="background-color: #d0e0e3;">Key</th> <th style="background-color: #d0e0e3;">Description of Associated Value</th></tr>
<tr><td style="background-color: #fff2cc;"><code>java.version</code></td> <td>Java Runtime Environment version</td></tr>
<tr><td style="background-color: #fff2cc;"><code>java.vendor</code></td> <td>Java Runtime Environment vendor</td></tr>
<tr><td style="background-color: #fff2cc;"><code>java.vendor.url</code></td> <td>Java vendor URL</td></tr>
<tr><td style="background-color: #fff2cc;"><code>java.home</code></td> <td>Java installation directory</td></tr>
<tr><td style="background-color: #fff2cc;"><code>java.vm.specification.version</code></td> <td>Java Virtual Machine specification version</td></tr>
<tr><td style="background-color: #fff2cc;"><code>java.vm.specification.vendor</code></td> <td>Java Virtual Machine specification vendor</td></tr>
<tr><td style="background-color: #fff2cc;"><code>java.vm.specification.name</code></td> <td>Java Virtual Machine specification name</td></tr>
<tr><td style="background-color: #fff2cc;"><code>java.vm.version</code></td> <td>Java Virtual Machine implementation version</td></tr>
<tr><td style="background-color: #fff2cc;"><code>java.vm.vendor</code></td> <td>Java Virtual Machine implementation vendor</td></tr>
<tr><td style="background-color: #fff2cc;"><code>java.vm.name</code></td> <td>Java Virtual Machine implementation name</td></tr>
<tr><td style="background-color: #fff2cc;"><code>java.specification.version</code></td> <td>Java Runtime Environment specification version</td></tr>
<tr><td style="background-color: #fff2cc;"><code>java.specification.vendor</code></td> <td>Java Runtime Environment specification vendor</td></tr>
<tr><td style="background-color: #fff2cc;"><code>java.specification.name</code></td> <td>Java Runtime Environment specification name</td></tr>
<tr><td style="background-color: #fff2cc;"><code>java.class.version</code></td> <td>Java class format version number</td></tr>
<tr><td style="background-color: #fff2cc;"><code>java.class.path</code></td> <td>Java class path</td></tr>
<tr><td style="background-color: #fff2cc;"><code>java.library.path</code></td> <td>List of paths to search when loading libraries</td></tr>
<tr><td style="background-color: #fff2cc;"><code>java.io.tmpdir</code></td> <td>Default temp file path</td></tr>
<tr><td style="background-color: #fff2cc;"><code>java.compiler</code></td> <td>Name of JIT compiler to use</td></tr>
<tr><td style="background-color: #fff2cc;"><code>java.ext.dirs</code></td> <td>Path of extension directory or directories</td></tr>
<tr><td style="background-color: #fff2cc;"><code>os.name</code></td> <td>Operating system name</td></tr>
<tr><td style="background-color: #fff2cc;"><code>os.arch</code></td> <td>Operating system architecture</td></tr>
<tr><td style="background-color: #fff2cc;"><code>os.version</code></td> <td>Operating system version</td></tr>
<tr><td style="background-color: #fff2cc;"><code>file.separator</code></td> <td>File separator ("/" on UNIX)</td></tr>
<tr><td style="background-color: #fff2cc;"><code>path.separator</code></td> <td>Path separator (":" on UNIX)</td></tr>
<tr><td style="background-color: #fff2cc;"><code>line.separator</code></td> <td>Line separator ("\n" on UNIX)</td></tr>
<tr><td style="background-color: #fff2cc;"><code>user.name</code></td> <td>User's account name</td></tr>
<tr><td style="background-color: #fff2cc;"><code>user.home</code></td> <td>User's home directory</td></tr>
<tr><td style="background-color: #fff2cc;"><code>user.dir</code></td> <td>User's current working directory</td></tr>
</tbody></table><br />
I have written a Java class to encapsulate these data. lets see the class and a sample program.<br />
<br />
class <span style="font-family: "Courier New",Courier,monospace;">UserInfo</span><br />
<pre class="Java" name="code">//© http://imagocomputing.blogspot.com/
class UserInfo {
private String getInfo(String key){
return System.getProperty(key);
}
public String getVersion(){
return getInfo("java.version");
}
public String getJavaHome(){
return getInfo("java.home");
}
public String getTempDir(){
return getInfo("java.home");
}
public String getOS(){
return getInfo("os.name");
}
public String getOSVer(){
return getInfo("os.version");
}
public String getUserName(){
return getInfo("user.name");
}
public String getUserHome(){
return getInfo("user.home");
}
public String getfileSeperator(){
return getInfo("file.separator");
}
}
</pre>class <span style="font-family: "Courier New",Courier,monospace;">UserInfoTest</span><br />
<pre class="Java" name="code">class UserInfoTest {
public static void main(String args[]){
UserInfo useInf=new UserInfo();
System.out.println("JRE Version \t: "+useInf.getVersion());
System.out.println("JRE Directory \t: "+useInf.getJavaHome());
System.out.println("JRE Temp Dir \t: "+useInf.getTempDir());
System.out.println("OS Name \t: "+useInf.getOS());
System.out.println("OS version \t: "+useInf.getOSVer());
System.out.println("User Name \t: "+useInf.getUserName());
System.out.println("User Home \t: "+useInf.getOSVer());
System.out.println("File Seperator \t: "+useInf.getfileSeperator());
}
}
</pre><br />
Output:<br />
<div class="separator" style="clear: both; text-align: center;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi_8QEaSQLDYxZqq8y57omgBMw1wSRu5zQhbDEm1zstjhdxwBj9U8Rrjm-a_Vj5-0ZyQKIlbXjORwpT5f6rOWlendlv_vkyTN8F-cdv4qTfmTk1paD1XkwTO6YcQX5IH03mhzZP9CRhI4Y/s1600/UserInfo1.png" /></div>Kanishka Dilshanhttp://www.blogger.com/profile/08604043101957122711noreply@blogger.com5tag:blogger.com,1999:blog-7879737190470784260.post-42840175905317733362010-05-31T10:42:00.000-07:002010-05-31T10:42:20.235-07:00Reading Text Files In a Java Program II :: Using a FileReader and a BufferedReaderIn this example we use a <span style="font-family: "Courier New",Courier,monospace;">FileReader </span>object wrapped by a <span style="font-family: "Courier New",Courier,monospace;">BufferedReader </span>object to read a plain text file. This method is more efficient than reading raw bytes and converting them into character array.<br />
<br />
<b>Constructors of BufferedReader class</b><br />
<span style="font-family: "Courier New",Courier,monospace;">BufferedReader(Reader in)</span> <br />
<span style="font-family: "Courier New",Courier,monospace;">BufferedReader(Reader in, int inpBuffSize)</span> : When we use this constructor we must specify the size of the input buffer.<br />
<br />
Code:<br />
<pre class="java" name="code">//© http://imagocomputing.blogspot.com/
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
public class ReadTxtFile{
public static void main(String args[]){
try{
String fileContent="";
//create a FileReader object(fin)
FileReader fin=new FileReader("myFile2.txt");
//wrap FileReader object(fin) using a BufferedReader
BufferedReader buffR=new BufferedReader(fin);
String line;
while((line=buffR.readLine())!=null){
fileContent+=line+"\n";
}
System.out.println(fileContent);
buffR.close();
fin.close();
}catch(FileNotFoundException e){
System.err.println("File not found : " + e.getMessage());
}catch(IOException e){
System.err.println("Error in file stream! : " + e.getMessage());
}
}
}
</pre>Output :<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEixXko1B7nORMm3Q4mnAHeOnh79TYsnCiP7VRX2v1rG49RV9Gz1XZMTTlHoMy8AdyMLqJ_e7hIwZa5_ZLhw6VINuRTes1Sv8Bcyoppt3wzEYIvRLtaCrnrUy_XYiU0uRt-RT9SvwwAy_s8/s1600/fileread2.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEixXko1B7nORMm3Q4mnAHeOnh79TYsnCiP7VRX2v1rG49RV9Gz1XZMTTlHoMy8AdyMLqJ_e7hIwZa5_ZLhw6VINuRTes1Sv8Bcyoppt3wzEYIvRLtaCrnrUy_XYiU0uRt-RT9SvwwAy_s8/s320/fileread2.png" /></a></div><br />
Explanation:<br />
Line 12 : We create a <span style="font-family: "Courier New",Courier,monospace;">FileReader </span>object to read out targeted text file<br />
Line 14: Wrap the FileReader object (<span style="font-family: "Courier New",Courier,monospace;">fin</span>) by a <span style="font-family: "Courier New",Courier,monospace;">BufferedReader</span>(<span style="font-family: "Courier New",Courier,monospace;">buffR</span>) this allows us to read file content line by line.<br />
<br />
Class <span style="font-family: "Courier New",Courier,monospace;"><a href="http://java.sun.com/javase/6/docs/api/java/io/FileReader.html" target="_blank">FileReader</a> </span>Since : JDK1.1<br />
Class <span style="font-family: "Courier New",Courier,monospace;"><a href="http://java.sun.com/javase/6/docs/api/java/io/BufferedReader.html" target="_blank">BufferedReader</a> </span>Since : JDK1.1Kanishka Dilshanhttp://www.blogger.com/profile/08604043101957122711noreply@blogger.com0tag:blogger.com,1999:blog-7879737190470784260.post-71991527303296982992010-05-30T06:58:00.000-07:002010-05-30T06:58:04.841-07:00Reading Text Files In a Java Program :: Using a FileReaderFileReader class is located in Java I/O package (java.io.FileReader). using this class we can read character files. In other words we can read character streams using FileRead class. If our purpose is reading bytes (raw bytes) from the files we can use FileInputStream.<br />
<br />
<b>Constructors of FileReader class.</b><br />
<span style="font-family: "Courier New",Courier,monospace;">FileReader(File file) </span> <br />
<span style="font-family: "Courier New",Courier,monospace;">FileReader(String fileName)</span><br />
<span style="font-family: "Courier New",Courier,monospace;">FileReader(FileDescriptor fd)</span> : File reader provides three handles to standard I/O streams such as in,out,err (FileDescriptor.in, FileDescriptor.out, FileDescriptor.err)<br />
<br />
Lets see an example to undestand the FileReader class.<br />
<pre class="java" name="code">//© http://imagocomputing.blogspot.com/
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
public class ReadTxtFile {
public static void main(String args[]) {
try{
FileReader fin=new FileReader("myFile.txt");
String fileContent="";
char buff[]=new char[512];
int len;
while((len=fin.read(buff))!=-1){
fileContent+=(new String(buff,0,len));
}
/*now fileContent variable contains
*the whole text in the targeted file
*/
System.out.println(fileContent);
fin.close();
}catch(FileNotFoundException e){
System.err.println("File not found : " + e.getMessage());
}catch(IOException e){
System.err.println("Error in file stream! : " + e.getMessage());
}
}
}
</pre>Output :<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEilLEUi4-614MlmEakPkpWKO4MIHqlLTMcIN5_VLL08gPc_pgKj0775RKXFfnXENC_e2SDkU6zA1cLwbNAlN5OhUed0pFZJCsdqY_NFbXlUQtIWkOFTzYUFsKFTP6dgMGoLQNLy0K2pNqY/s1600/FileReadDemo.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEilLEUi4-614MlmEakPkpWKO4MIHqlLTMcIN5_VLL08gPc_pgKj0775RKXFfnXENC_e2SDkU6zA1cLwbNAlN5OhUed0pFZJCsdqY_NFbXlUQtIWkOFTzYUFsKFTP6dgMGoLQNLy0K2pNqY/s320/FileReadDemo.png" /></a></div>Explanation :<br />
In line 9 we create <span style="font-family: "Courier New",Courier,monospace;">FileReader</span> object called <span style="font-family: "Courier New",Courier,monospace;">fin </span><br />
Then we read file iteratively. First we read set of characters into <span style="font-family: "Courier New",Courier,monospace;">char </span>array then we append it to <span style="font-family: "Courier New",Courier,monospace;">fileContent</span> variable.<br />
After reading whole content we can do several manipulations with the file content in this example I have printed the file content to the standard output stream.<br />
<br />
Class : <a href="http://java.sun.com/javase/6/docs/api/java/io/FileReader.html" target="_blank">FileReader</a><br />
Since : JDK1.1Kanishka Dilshanhttp://www.blogger.com/profile/08604043101957122711noreply@blogger.com2tag:blogger.com,1999:blog-7879737190470784260.post-46365694300480752382010-05-12T22:05:00.000-07:002010-05-12T22:05:37.794-07:00String Class in JavaString objects contain sequence of charters. Strings can be concatenate using ( + ) operator which is a special java language feature. String class represent a string using UTF -16 <a href="http://java.sun.com/javase/6/docs/api/java/lang/Character.html#unicode" target="_blank"><span style="font-size: x-small;">(unicode character representation in java)</span></a><span style="font-size: x-small;"> </span><br />
<span style="font-size: small;">There are different constructors available in Java we have to select the most suitable construct for our purpose. <a href="http://java.sun.com/javase/6/docs/api/java/lang/String.html" target="_blank"><span style="font-size: x-small;">(Click here to see the constructor summary)</span></a></span><br />
<span style="font-size: small;">Following methods are available in the String class.</span><br />
<span style="font-size: small;"><span style="font-family: "Courier New",Courier,monospace;">length() </span></span><br />
<div style="font-family: "Courier New",Courier,monospace;"><span style="font-size: small;">charAt(int index)</span></div><div style="font-family: "Courier New",Courier,monospace;"><span style="font-size: small;">compareTo(String str)</span></div><div style="font-family: "Courier New",Courier,monospace;"><span style="font-size: small;">compareToIgnoreCase(String str)</span></div><div style="font-family: "Courier New",Courier,monospace;"><span style="font-size: small;">concat(String str)</span></div><div style="font-family: "Courier New",Courier,monospace;"><span style="font-size: small;">endsWith(String suffix)</span></div><div style="font-family: "Courier New",Courier,monospace;"><span style="font-size: small;">equals(Object obj)</span></div><div style="font-family: "Courier New",Courier,monospace;"><span style="font-size: small;">equalsIgnoreCase(String str)</span></div><div style="font-family: "Courier New",Courier,monospace;"><span style="font-size: small;">indexOf(String str)</span></div><div style="font-family: "Courier New",Courier,monospace;"><span style="font-size: small;">lastIndexOf(String str)</span></div><div style="font-family: "Courier New",Courier,monospace;"><span style="font-size: small;">replace(char oldChar,char newChar)</span></div><div style="font-family: "Courier New",Courier,monospace;"><span style="font-size: small;">split(String regex)</span></div><div style="font-family: "Courier New",Courier,monospace;"><span style="font-size: small;">startsWith(String prefix)</span></div><div style="font-family: "Courier New",Courier,monospace;"><span style="font-size: small;">substring(int beginIndex)</span></div><span style="font-size: small;"><span style="font-family: "Courier New",Courier,monospace;">trim(String s)</span></span><br />
Lets see some example written to demonstrate the above methods.<br />
Compare the code with given output.<br />
<span style="font-size: small;"> </span> <br />
<pre class="java" name="code">//© http://imagocomputing.blogspot.com/
class StringDemo {
public static void main(String args[]){
String str1="Sri Lanka is the most beautiful country";
String str2="Java is a OOP language";
System.out.println("Length of str1 : " + str1.length());
System.out.println(str1.compareTo(str2));
System.out.println(str1.endsWith("try"));
System.out.println(str1.equals(str2));
System.out.println(str1.equalsIgnoreCase(str2));
System.out.println(str1.indexOf("Lanka"));
System.out.println(str1.lastIndexOf("t"));
String newStr=str2.replace("J","L");
System.out.println("Replaced string : " + newStr);
System.out.println(str1.startsWith("Sri"));
String subStr=str1.substring(22);
String beforeTrim=" Hello Sri Lanka ";
String afterTrim=beforeTrim.trim();
System.out.println("Before trim : " + beforeTrim);
System.out.println("Aftre trim : " + afterTrim);
}
}
</pre><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiz3HJFhRl5mlyk5ODYLV5cYRj0oU6_RJDgDQcXB6AO7pnODf5R7thBxYgfUH2QcmokT_S5EzWFOwb8TG46_78wONxQIWN2-VjW5mNMyQI16OMVe74Dh6UQA8J-Fc3G2_QDeGV9CDwfeIY/s1600/stringdemo.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEiz3HJFhRl5mlyk5ODYLV5cYRj0oU6_RJDgDQcXB6AO7pnODf5R7thBxYgfUH2QcmokT_S5EzWFOwb8TG46_78wONxQIWN2-VjW5mNMyQI16OMVe74Dh6UQA8J-Fc3G2_QDeGV9CDwfeIY/s320/stringdemo.png" /></a></div>Kanishka Dilshanhttp://www.blogger.com/profile/08604043101957122711noreply@blogger.com0tag:blogger.com,1999:blog-7879737190470784260.post-40987037939531761692010-05-05T20:55:00.000-07:002010-05-05T20:55:26.730-07:00Using StringTokenizer Class<a href="http://java.sun.com/j2se/1.4.2/docs/api/java/util/StringTokenizer.html" target="_blank"><span style="font-family: "Courier New",Courier,monospace;">StringTokenizer</span></a> is shipped in java.util package. This can be used to split a string using a given delimiter. Space character is the default delimiter for any string.<br />
There are three important methods in <a href="http://java.sun.com/j2se/1.4.2/docs/api/java/util/StringTokenizer.html" target="_blank"><span style="font-family: "Courier New",Courier,monospace;">StringTokenizer</span></a> class.<br />
<ul><li><b><a href="http://java.sun.com/j2se/1.4.2/docs/api/java/util/StringTokenizer.html#countTokens%28%29" target="_blank">countTokens()</a> : returns the number of tokens.</b></li>
<li><b><a href="http://java.sun.com/j2se/1.4.2/docs/api/java/util/StringTokenizer.html#hasMoreElements%28%29" target="_blank">hasMoreTokens()</a> : returns true if more tokens are available .</b></li>
<li><b><a href="http://java.sun.com/j2se/1.4.2/docs/api/java/util/StringTokenizer.html#nextToken%28%29" target="_blank">nextToken()</a> :returns the current token.</b></li>
</ul><b>lets see some java code to understand these methods.</b><br />
<b><br />
</b><br />
<pre class="java" name="code">//© http://imagocomputing.blogspot.com/
import java.util.StringTokenizer;
class TokenizerDemo {
public static void main(String args[]){
String MyStr="Sajith#Nimal#Kamal#Sunil";
StringTokenizer tokens=new StringTokenizer(MyStr,"#");
System.out.println("Real String : " + MyStr);
System.out.println("Number of tokens: " + tokens.countTokens());
int i=1;
while(tokens.hasMoreTokens()){
System.out.println("Token " + i +" \t: " + tokens.nextToken());
i++;
}
}
}
</pre>output :<br />
<div class="separator" style="clear: both; text-align: center;"></div><div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhIjAcjhUy3h_iWZql-nIoQAJqWnnhyphenhyphengPxlGFRRhyphenhyphen5Ky9e_qr3ALcJ4QAg_d_EBDIs63pntE9oyMY-Or8KU5lHFDO7JLOycA5LTDlMyAg5NBymDRSK7vSl2BEbL1gtdNQqkZsqSGLkihyphenhypheno/s1600/tokenizer.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhIjAcjhUy3h_iWZql-nIoQAJqWnnhyphenhyphengPxlGFRRhyphenhyphen5Ky9e_qr3ALcJ4QAg_d_EBDIs63pntE9oyMY-Or8KU5lHFDO7JLOycA5LTDlMyAg5NBymDRSK7vSl2BEbL1gtdNQqkZsqSGLkihyphenhypheno/s320/tokenizer.png" /></a></div><br />
<br />
A Practical Example:<br />
<pre class="java" name="code">//© http://imagocomputing.blogspot.com/
import java.util.StringTokenizer;
class GetExtensionDemo {
static String getFileExtension(String filePath){
StringTokenizer stk=new StringTokenizer(filePath,".");
String FileExt="";
while(stk.hasMoreTokens()){
FileExt=stk.nextToken();
}
return FileExt;
}
public static void main(String[] args){
String path1="/usr/bin/myProg.pl";
System.out.println("File path : " + path1 + " File extension : " + getFileExtension(path1));
String path2="C:\\about.bmp";
System.out.println("File path : " + path2 + " File extension : " + getFileExtension(path2));
}
}
</pre>Output :<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg9vGYiw8Al6BHsCr8wlg_5AQ46qiQEwftZq2m41TS7CjHAwwsp0kDJZkuZggySPgTOby-os54gO6_AfMR_qQIquQBy8QNNR-S_EkzkL0185NhmH7GHNwFacijhemyMYrM3smOAMXb5w7E/s1600/tokenizerprac1.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="82" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEg9vGYiw8Al6BHsCr8wlg_5AQ46qiQEwftZq2m41TS7CjHAwwsp0kDJZkuZggySPgTOby-os54gO6_AfMR_qQIquQBy8QNNR-S_EkzkL0185NhmH7GHNwFacijhemyMYrM3smOAMXb5w7E/s400/tokenizerprac1.png" width="400" /></a></div><dl><dt><b>Since : </b>JDK1.0</dt>
<dt> </dt>
</dl>Kanishka Dilshanhttp://www.blogger.com/profile/08604043101957122711noreply@blogger.com0tag:blogger.com,1999:blog-7879737190470784260.post-78004980718622830772010-04-19T07:30:00.000-07:002010-04-19T07:30:03.203-07:00Getting Keyboard Inputs IIIn previous method for getting keyboard inputs we used buffered readers and input stream readers. There is a special class called Scanner available in java.util package which can be used to get keyboard inputs. Using a Scanner object we can read converted values directly into our program which means we haven't to convert read values explicitly. Scanner class be used to perform many other tasks. Lets see a simple Java program to understand its usage.<br />
<br />
<pre class="java" name="code">//© learnjavaapi.blogspot.com
import java.util.Scanner;
class ScannerDemo{
public static void main(String args[]){
int num1;
float num2,tot;
String name;
Scanner scn=new Scanner(System.in);
System.out.print("Enter your name \t: " );
name=scn.nextLine();
System.out.print("Enter a Float value \t: " );
num2=scn.nextFloat();
System.out.print("Enter an Integer value \t: " );
num1=scn.nextInt();
tot=num1+num2;
System.out.println("Hi "+name+" total is \t: "+ tot );
}
}
</pre><br />
Output :<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhy82kb41k0zaJDJRve5RPiKmmCnNy4W-Uh94xci9rVUm4HdEqq0P8-QpUvNXwQSz1meFX_QIoX2xL5r91U6vlFo9Lqcr0VIKW83B-BrfvcRt1YzaLVlRCaJa5p9v_sjk4SBwCkkHk4K9w/s1600/scannerdemo.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" height="157" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhy82kb41k0zaJDJRve5RPiKmmCnNy4W-Uh94xci9rVUm4HdEqq0P8-QpUvNXwQSz1meFX_QIoX2xL5r91U6vlFo9Lqcr0VIKW83B-BrfvcRt1YzaLVlRCaJa5p9v_sjk4SBwCkkHk4K9w/s400/scannerdemo.png" width="400" /></a></div><br />
In above example I have used the created Scanner object to read three different data. String,int and float. See the java documentation for more details about Scanner class.<br />
Class : Scanner<br />
Since : Java 1.5<br />
<a href="http://java.sun.com/javase/6/docs/api/java/util/Scanner.html" target="_blank">Scanner</a>Kanishka Dilshanhttp://www.blogger.com/profile/08604043101957122711noreply@blogger.com0tag:blogger.com,1999:blog-7879737190470784260.post-68158329094832266452010-04-18T05:36:00.000-07:002010-04-18T05:36:04.792-07:00Getting Keyboard Inputs IIn order to get inputs from the keyboard we can use standard input stream (System.in ) available in the java.lang package. Generally standard input stream contains byte stream coming from the keyboard. Of cause we can change the standard input. In this example I have used an InputStreamReader object to read the input stream. Lets see a simple java program written to demonstrate how to get keyboard inputs in java.<br />
<br />
<pre class="java" name="code">//© learnjavaapi.blogspot.com
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
class GetInput{
public static void main(String args[]) throws IOException{
InputStreamReader in=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(in);
System.out.print("Please Enter your name : ");
String name=br.readLine();
System.out.println("Hi "+ name +" how are you ? ");
in.close();
br.close();
}
}
</pre><br />
Output :<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj5cxo4ajsiyBBVi-s228aXpzagk1h9pf7nuM382eXCSTh-EyuZxW13C7tbTfYESbxsXAqlnkM3gTiPkBIl5bevaoSAUYgU6uO1bgUn1hEn329YGWnXMfgcVqPEo7VSeFkTAImd7xNgFU0/s1600/key_input.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj5cxo4ajsiyBBVi-s228aXpzagk1h9pf7nuM382eXCSTh-EyuZxW13C7tbTfYESbxsXAqlnkM3gTiPkBIl5bevaoSAUYgU6uO1bgUn1hEn329YGWnXMfgcVqPEo7VSeFkTAImd7xNgFU0/s320/key_input.png" /></a></div><br />
Let me explain important parts of this program.<br />
In the first three lines I have imported essential classes. By using <span style="font-family: "Courier New",Courier,monospace;"><b style="color: #3d85c6;">throws</b> </span>keyword I have thrown <b><span style="font-family: "Courier New",Courier,monospace;">IOException </span></b>from my program. So all input/output exceptions are ignored in our program. By creating <b><span style="font-family: "Courier New",Courier,monospace;">InputStreamReader</span></b> object called <b><span style="font-family: "Courier New",Courier,monospace;">in</span></b> our program is ready to get keyboard inputs. For better input handling <b><span style="font-family: "Courier New",Courier,monospace;">BufferedReader </span></b><span style="font-family: "Courier New",Courier,monospace;"><span style="font-family: inherit;">object <b><span style="font-family: "Courier New",Courier,monospace;">br</span></b> is used. This joining is called wrapping <b><span style="font-family: "Courier New",Courier,monospace;">InputStreamReader</span></b> object within <b><span style="font-family: "Courier New",Courier,monospace;">BufferedReader </span></b></span></span><span style="font-family: "Courier New",Courier,monospace;"><span style="font-family: inherit;">object</span></span><span style="font-family: "Courier New",Courier,monospace;"><span style="font-family: inherit;"><b><span style="font-family: "Courier New",Courier,monospace;"></span></b><span style="font-family: "Courier New",Courier,monospace;"><span style="font-family: inherit;"></span>. InputStreamReader </span></span></span><span style="font-family: "Courier New",Courier,monospace;"><span style="font-family: inherit;">reads bytes from the input stream and decodes them into characters.</span></span><br />
<span style="font-family: "Courier New",Courier,monospace;"><span style="font-family: inherit;">JavaDoc:</span></span><br />
<div style="font-family: "Courier New",Courier,monospace;"><b><a href="http://java.sun.com/javase/6/docs/api/java/io/InputStreamReader.html" target="_blank">InputStreamReader</a></b></div><div style="font-family: "Courier New",Courier,monospace;"><b><a href="http://java.sun.com/javase/6/docs/api/java/io/BufferedReader.html" target="_blank">BufferedReader</a></b></div><div style="font-family: "Courier New",Courier,monospace;"><b><a href="http://java.sun.com/javase/6/docs/api/java/io/IOException.html" target="_blank">IOException</a></b></div><br />
<span style="font-family: "Courier New",Courier,monospace;"><span style="font-family: inherit;"> </span></span>Kanishka Dilshanhttp://www.blogger.com/profile/08604043101957122711noreply@blogger.com0tag:blogger.com,1999:blog-7879737190470784260.post-18207375876616475392010-04-17T10:38:00.000-07:002010-04-17T10:42:38.881-07:00Compute Elapsed Time in NanosecondsTo compute some execution time we can use nanoTime() method in the System class. There are several other ways to calculate some execution time. But most accurate way is using nanoTime() method. nanoTime() method returns the current value which is a long value of the most precise system timer in Java. But this value is an approximate value. <br />
<pre class="Java" name="code">//© learnjavaapi.blogspot.com
class ExeTime{
public static void main(String srgs[]){
long before=System.nanoTime();
long sum=0;
//some long execution
for(int i=0;i<10000;i++){
sum+=i;
}
long now=System.nanoTime();
System.out.println("Time difference : " + (now-before) + " nS");
}
}
</pre>Since : Java 1.5<br />
Output :<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh10t-byixuLlr7OYh4lJdvfrVrA30wtos4cw47h0GE2qhXwsf86lN8-jW6BxDiHFOc83qDikmimfe31qoVVQLMXH6cXKg7ST1b0z1l1WzdFvKaWGMWA4kwLEvvwKstdSiMD1Kvo-rc5Fk/s1600/time_diff.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEh10t-byixuLlr7OYh4lJdvfrVrA30wtos4cw47h0GE2qhXwsf86lN8-jW6BxDiHFOc83qDikmimfe31qoVVQLMXH6cXKg7ST1b0z1l1WzdFvKaWGMWA4kwLEvvwKstdSiMD1Kvo-rc5Fk/s320/time_diff.png" /></a></div><br />
<a href="http://java.sun.com/javase/6/docs/api/java/lang/System.html#nanoTime%28%29" target="_blank">References</a>Kanishka Dilshanhttp://www.blogger.com/profile/08604043101957122711noreply@blogger.com0tag:blogger.com,1999:blog-7879737190470784260.post-68703367780626645452010-04-17T07:34:00.000-07:002010-04-17T07:34:41.822-07:00Java Wrapper Classes :: Converting String Values Into Double ValuesIn previous example we discussed how to convert string values into integer values. Double values and float values are used in floating-point calculations. We can use following methods available in relevant classes.<br />
<br />
<b>Syntax : Converting String values into Double values</b><br />
<pre class="Java" name="code">double d1=Double.parseDouble("89223.4234312454");
</pre><br />
<b>Syntax : Converting String values into Float values</b><br />
<pre class="Java" name="code">float f1=Float.parseFloat("2.32323");
</pre><br />
Note : Remember that the Float is not a keyword. It is a class name.Kanishka Dilshanhttp://www.blogger.com/profile/08604043101957122711noreply@blogger.com0tag:blogger.com,1999:blog-7879737190470784260.post-44263147835567447882010-04-17T06:55:00.000-07:002010-04-17T07:23:43.026-07:00Java Wrapper Classes :: Converting String Values Into Integer Values<b><span style="font-size: small;">What is Java API ?</span></b><br />
<span style="font-size: small;"> Java API is a short term for Java Application Programming Interface. Java API contains thousands of classes which are very useful for java programmers. Programmers can use these already provided java classes to enhance their productivity. Java documentation is available in following site.</span><br />
<span style="font-size: small;"><a href="http://java.sun.com/javase/6/docs/" target="_blank">http://java.sun.com/javase/6/docs/</a></span><br />
<br />
<span style="font-size: small;">This is the first example of Learn Java API blog. I assume the readers of this blog have basic knowledge of java programming. </span><br />
<span style="font-size: small;">Integer wrapper class can be used to manipulate integer variables. We use parseInt() method in Integer class for this example.</span><br />
<br />
<pre class="Java" name="code">//© learnjavaapi.blogspot.com
class ConvertInt{
public static void main(String srgs[]){
String n1="12";
String n2="45";
int num1,num2;
//String concatenation
System.out.println(n1+n2);
//Integer conversion
try{
num1=Integer.parseInt(n1);
num2=Integer.parseInt(n2);
System.out.println(num1+num2);
}catch(NumberFormatException e){
System.out.println("Please give a valid number!");
}
}
}
</pre><br />
Output :<br />
<div class="separator" style="clear: both; text-align: center;"><a href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgVvty_LQpr70Igf6kW6uZ78AqndihwmvIWjkrb0Fw1d6bg65hKfuahMF3eaXkVRPLqRyst3JPt6xM9Rbs1hw8upIOS34fqAoZx8zdl5NV5wuNn05Hx9R8vdS-EfxxLKl_Vl1gOsKUB2yI/s1600/ex1convertInt.png" imageanchor="1" style="margin-left: 1em; margin-right: 1em;"><img border="0" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgVvty_LQpr70Igf6kW6uZ78AqndihwmvIWjkrb0Fw1d6bg65hKfuahMF3eaXkVRPLqRyst3JPt6xM9Rbs1hw8upIOS34fqAoZx8zdl5NV5wuNn05Hx9R8vdS-EfxxLKl_Vl1gOsKUB2yI/s320/ex1convertInt.png" /></a></div><br />
<span style="font-size: small;">Explanation :</span><br />
<span style="font-size: small;">n1 and n2 contain string values of given number. Statement in line 08 performs a string concatenation because of n1 and n2 are string values. Hence you can see the output as </span><span style="font-family: "Courier New",Courier,monospace; font-size: small;">1245</span><span style="font-size: small;"> twelve and forty five .</span><br />
<span style="font-size: small;">Statement in line 13 performs numeric add operation. hence the 2nd output is 57 which is equal to 12+45 . A </span><span style="font-size: small;"><span style="font-family: "Courier New",Courier,monospace;">NumberFormatException</span> will be thrown if an error occur while converting numbers. </span>Kanishka Dilshanhttp://www.blogger.com/profile/08604043101957122711noreply@blogger.com0