Archive

Posts Tagged ‘Java’

Java: How to convert String to array?

February 11th, 2009

Sometime you get a string in a fixed format and you want individualise it and store them into array so you can manipulate it easier with your other functions.

For example,

String array = "one,two,three,four,five,six,seven,eight,nine";

will become

String[] words = {one,two,three,four,five,six,seven,eight,nine};

Below code is demonstrating how fixed format string can be broken down and stored into array.

Class: StringToArray.java
Read more...

Programming

How to copy text file in Java?

January 30th, 2009

Code below demonstrating how to copy data from one text file to another in Java.

This testing method, is calling FileCopier.copyFile(File, File) to copy content of file test1.css to file test2.css

    public static void main(String[] args) {
        FileCopier.copyFile(new File("D:/TEMP/test1.css"), 
                            new File("D:/TEMP/test2.css"));
    }

Class: FileCopier.java
Read more...

Programming , ,

Understand Java break and continue Statements

January 19th, 2009

Let's get it right and understand on usage of break and continue Statements in Java Programming Language.

break Statement

This statement causes iteration to stop/exit immediately, any line remained after this statement will be ignored by the JVM.

It is used in the following loop

  • for
  • while
  • do...while
  • switch

continue Statement

This statement skips the current iteration of the loop, any line after this statement will not be executed by the JVM until the condition is met.
Read more...

Programming ,

Generate Random Password in Java

January 16th, 2009

This article demonstrates how to generate random password or string using java.util.Random.

You can define your own set of characters in this string variable

private static final String charset = "!0123456789abcdefghijklmnopqrstuvwxyz";

Class: RandomPassword.java
Read more...

Programming ,

Use Calendar instead of Date in Java

January 14th, 2009

Common Issue

When you use java.util.Date object with JDK version higher than 1.1

Date d = new Date();
d.getMonth();

You will get deprecated warning messages when you try to compile

The method getMonth() from the type Date is deprecated

However you can supress the warning message by adding @SuppressWarnings("deprecation") to you main() method

@SuppressWarnings("deprecation")
public static void main(String[] args) {
    ...
}

or adding @SuppressWarnings("unchecked") to other method

@SuppressWarnings("unchecked")
public void otherMethod() {
    ...
}

Note that this can only be used in JDK 5.0+

Alternative

Now let's forget about working around the deprecated method, let's learn how to use java.util.Calendar instead
Read more...

Programming , ,

What are Java Operators?

January 12th, 2009

In Java Language, there are 4 types of operators

  1. Arithmetic
  2. Relational
  3. Logical
  4. Bitwise

The rest of this post includes a small class to demonstrate on how those operators are used.

Arithmetic Operators

+  : Addition

-  : Subtraction

*  : Multiplication

/  : Division

%  : Modulus

++ : Increment

-− : Decrement

Read more...

Programming ,

A good practice to Compare String in Java

December 7th, 2008

Many people confused or don't understand the concept to use String object properly.
In most case, when they try to compare 2 identical string objects they don't get matching result.

When you have to do string comparison, there are few points to remember:

  • These operators <, <=, >, or >= cannot be used
  • These operator == and != don't compare character in the string or string outside String pool. Only use these operator when you want to check if String value is NULL
  • Use String .equals , String .compareTo and Collator .compare to get accurate comparison result. Use these operators when String value is not NULL

The following class demonstrate how string are being compare in different way and the result of each

import java.text.Collator;
 
public class TestCompareObject {
 
  public static void main(String[] args) {
      String s1 = "Same String Value but could be different result";
      String s2 = "Same String Value but could be different result";
      String s3 = new String ("Same String Value but could be different result");
      Collator c = Collator.getInstance();
 
      System.out.println("1. s1 == s2 ? : " + (s1 == s2 ? "true" : "false"));
      System.out.println("2. s1 == s3 ? : " + (s1 == s3 ? "true" : "false"));
      System.out.println("2. s1.compareTo(s3) : " +
              (s1.compareTo(s3) == 0 ? "equal" : "not equal"));
      System.out.println("3. s1.equals(s3) : " +
              (s1.equals(s3) ? "true" : "false"));
 
      int c_compare = c.compare(s1, s3);
      System.out.println("4. Collator compare(s1, s3) ? : " +
              (c_compare == 0 ? "equal" : "not equal") );
  }
 
}

Below is the output of this program

1. s1 == s2 ? : true
2. s1 == s3 ? : false
2. s1.compareTo(s3) : equal
3. s1.equals(s3) : true
4. Collator compare(s1, s3) ? : equal

Programming , , ,

How to Read Text File in Java?

December 6th, 2008

Example below showing how to read text file

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
 
/**
 * Example class for Reading text file
 *
 * @author Manet Yim (manet.yim at gmail dot com)
 */
public class ReadTextFile {
 
    public void readTextFile() {
 
        // Create new file object
        File file = new File("C:\Temp\TestFolder\TestFile.txt");
 
        try {
            // create file reader instance
            FileReader fr = new FileReader(file);
            // create memory buffer to store data read from file
            BufferedReader br = new BufferedReader(fr);
            // variable to store text from file
            String line = "";
            while ( (line = br.readLine()) != null ){
                System.out.println(line);
            }
            // close file reader
            fr.close();
            // close buffer reader
            br.close();
 
        }
        // it is required to catch exception in case file is not found
        catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        // it is required to catch exception in case file cannot be read
        catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    public static void main(String[] args) {
        ReadFile app = new ReadFile();
        app.readTextFile();
    }
 
}

Programming , , , ,

What are Primitive Data Types in Java Language?

September 8th, 2008

This is the question that might rise by the Java programming beginner. Well, the answer to this question is: Primitive Data Types are the type that is preliminary defined by the Language which normally known as Keywords or reserved words.

In Java Language there are 8 primitive data types supported.

  • byte: is an 8-bit signed two's complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive).
    Default value: 0
  • short: 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).
    Default value: 0
  • int: 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).
    Default value: 0
  • long: 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).
    Default value: 0L
  • float: is a single-precision 32-bit IEEE 754 floating point. The value range can be found here.
    Default value: 0.0f
  • double: The double data type is a double-precision 64-bit IEEE 754 floating point. The value range can be found here.
    Default value: 0.0d
  • boolean: has only two possible values: true and false.
    Default value: false
  • char: 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 value: '\u0000'

Number and String are not primitive data type. They are java Object defined under java.lang. They come with subclass or methods for manipulating the value of the object itself.

Reference:

Programming ,

How to write One Line if-else statment in Java?

September 6th, 2008

Do you want to shorten your code? Below is a trick how to write one single line if-else statement.

Syntax

(condition) ? true-result : false-result

Where

  • condition: is your if condition
  • true-result: is executed when condition is true
  • false-result: is executed when condition is false

Example

System.out.println((1 + 2 == 4) ? "true" : "false");

This line of code will print "false" because the condition 1+2 not equals to 4

System.out.println((2 + 2 == 4) ? dothis() : dothat());

This line of code will dothis() method because the condition 2+2 equals to 4

Programming