Wednesday, September 2, 2009

HTML mailto attribute

The mailto is a quick way to add the facility of receiving feedback from visitor on your web site. With the HTML mailto, you create a link which when clicked by the visitor launches (if it's not already running) their email program with a new email message window. The visitor could then formulate the email message and send it off to you.

Note: HTML Mailto assumes that the visitor has configured an email client (Outlook Express, Netscape Messenger, Thunderbird or any other) to send emails.

In its simplest form, the HTML mailto requires an email address. However, mailto can be made slightly more professional if we use it properly.


The Basic form of HTML mailto

mailto looks like:


Send me an
email




And this is displayed as



A more complex HTML mailto


We will now learn how to create a more complex HTML mailto by adding an email subject and the email body so that it looks a little more professional. And this will definitely save your visitors some typing too!



Send me an email






Careful inspection of the above code will highlight two points. Firstly, the email address is separated from the other information by a ? sign (question mark) and secondly, body and subject properties are themselves separated using an &.

[Those of you familiar with server-side scripting will find a similarity between this mailto tag and the GET method.]

Remember, the prefilled email Subject and email body values can be changed by the visitor! But this fancy mailto looks better than plain one, doesn't it?

In addition to the body and subject, we can also provide HTML mailto with CC (Carbon Copy) and BCC (Blind Carbon Copy). This, as you would have guessed, requires us to append these values to the HTML mailto attribute just like we had done for body and subject. [Refer code and image below]




Send me an email





Thursday, August 27, 2009

JDK API search in Google Toolbar

For those of you who use the Google Toolbar, the following links will add a Java API search button to your toolbar. I've found this to be a very handy way to locate the javadoc for the platform.

Add Java SE 6 API search box to Google Toolbar

Add OpenJDK API search box to Google Toolbar

Tuesday, July 14, 2009

All About CSS

URL : http://www.cssportal.com/


Here at CSSPortal, we have gathered as much information as possible to try and help you learn CSS and improve your web design skills.



At this site, you'll find a range of quality resources all geared towards CSS, if you're looking for a new design for your website, then please check out our range of CSS templates or if you would like to design your own site, you may wish to check out some software to help, go to CSS software for some great programs. Also at CSSPortal, you'll find all the CSS properties, CSS books and a nice collection of CSS examples.

CSS Menu Generator has been updated to make it more user friendly.

- CSS properties list has been updated to include CSS 3 Properties.
- New CSS tool has just been released, Format CSS Code.
- Check out our new page about CSS3 Examples.

URL : http://www.cssportal.com/

Different Style in HTML Text Field

CSS Text Box Element



CSS Code



/* Text Box with Different Border: */
.tb-border {
border: 1px solid #0000FF;
}

/* Text Box with Background Color: */
.tb-background {
background-color : #99FFCC;
border: 1px solid #008000;
}

/* Text Box with Background Image: */
.tb-bg-image {
background-image: url(bg.png);
border: 1px solid #6297BC;
}

/* Text Box with Focus: */
.tb-focus {
border: 1px solid #888377;
}
.tb-focus:focus {
background-color: #F4EEDD;
}

/* Text Box with Side Image: */
.tb-bg-side {
background-image: url(Portal.gif);
background-repeat:no-repeat;
background-position:left;
border: 1px solid #6297BC;
padding-left:16px;
}

/* Text Box with Rounded Corners: */
.tb-rounded {
border:0;
background: transparent url(rounded.gif) no-repeat top left;
height: 22px;
width: 230px;
padding-top:2px;
}

/* Text Box with Gradient: */
.tb-gradient {
border:0;
background: transparent url(gradient.gif) no-repeat top left;
height: 22px;
width: 230px;
padding-top:2px;
}




Source: http://www.cssportal.com/form-elements/text-box.htm
Demo: View Demo

jCarousel-jQuery plugin

jCarousel description


jCarousel is a jQuery plugin for controlling a list of items in horizontal or vertical order.
jCarousel is a jQuery plugin for controlling a list of items in horizontal or vertical order.
The items, which can be static HTML content or loaded with (or without) AJAX, can be scrolled back and forth (with or without animation).

To use the jCarousel component, include the jQuery library, the jCarousel source file, the jCarousel core stylesheet file and a jCarousel skin stylesheet file inside the head tag of your HTML document.
--------------------------------------------------
--------------------
Home Page: http://sorgalla.com/jcarousel/
Demo: View Demo
Download :
Download jCarousel
Documentation: http://sorgalla.com/projects/jcarousel/
Examples : http://sorgalla.com/jcarousel/
----------------------------------------------------------------------

Monday, July 6, 2009

How to turn on log4j debug

use this jvm flag : -Dlog4j.debug

How to disable copy paste and autocomplete for an HTML textbox


INPUT size=12 name=”FundsTransferTo” maxlength=12 onCopy=”return false” onDrag=”return false” onDrop=”return false” onPaste=”return false” autocomplete=off;

Wednesday, June 10, 2009

Batch File To Create Restore Point








runas /user:local\administrator
@
echo off
title Test Utility
:prompt
color 4f
cls
echo Pick a Category
echo.
echo Type 1 to System Utilities
echo Type 2 to ""
echo Type 3 to ""

set /p answer=
if ‘%answer%’ == ‘1’ system

:system
cls
Echo Type 1 to System Restore
Echo Type 2 to ""
Echo Type 15 to Main Menu

set /p answer=
if '%answer%' == '1' goto system restore

:system restore
cls
IF EXIST %systemroot%\system32\restore\rstrui.exe= %systemroot%\system32\restore\rstrui.exe else
IF EXIST C:\Windows\System32\rstrui.exe = C:\Windows\System32\rstrui.exe
echo.
echo Pres Any Key to goto Menu
pause >nul
goto prompt

Create .VBS file To Create Restore Point

Step-1 Open Notepad
Step-2 Copy below code to Noteoad

set SRP = getobject("winmgmts:\\.\root\default:Systemrestore")
CSRP = SRP.createrestorepoint ("Restore Point Created By-Chintan Patel", 0, 100)

Step3 Save as RestorePoint.vbs
Step-4 Double click on RestorePoint.vbs to Take Restore Point


Note:
If you want to Take Restore Point when system start,
then drag that file in to STARTUP

How to Start the System Restore Tool from a Command Prompt



To start the System Restore tool when you cannot start your Windows Me-based computer normally or in Safe mode, you can temporarily change the Windows shell from Explorer.exe to Progman.exe:
  1. Start your computer by using the Windows Me Startup disk.
  2. At the Startup menu, choose Minimum Boot.
  3. At the command prompt, type edit c:\windows\system.ini, and then press ENTER.
  4. Edit the shell= line so that it looks like this:
    shell=progman.exe
  5. Press ALT+F, and then press S to save the changes to the System.ini file.
  6. Press ALT+F, and then press X.
  7. Remove your Windows Me Startup disk, and then restart your computer. When your computer restarts, Program Manager should start. If Program Manager does not start, repeat steps 1 through 7, being careful to follow these steps exactly, and then continue to the next step.
  8. On the File menu, click Run, type msconfig in the Command Line box, and then press ENTER.
  9. Click Launch System Restore to begin restoring your computer to a previous, functional state.


Notes

  • After you configure your computer to start Program Manager (Progman.exe), you can also start the System Restore tool by typing c:\windows\system\restore\rstrui.exe at a command prompt, and then pressing ENTER.
  • If you still cannot use System Restore, repeat steps 1 through 6. In step 4, change the shell= line so that it reads:
    shell=explorer.exe
    This sets the Windows shell back to Explorer.exe so that you can continue troubleshooting.

Tuesday, June 9, 2009

Have You Visit eHow ?

Have You Visit eHow ?


Print (Silent Print) From Java Applet

import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import java.net.*;

import javax.print.*;
import javax.print.attribute.*;
import javax.print.attribute.standard.*;
import javax.swing.*;

public class CopyOfPrinterApplet extends JApplet {

private PrintRequestAttributeSet aset;
DocFlavor DocFlavor;
public Doc doc;
DocPrintJob printerJob;
JTextPane pane;


/**
* DOCUMENT ME!
*/
public void init() {
getContentPane().setLayout(new BorderLayout());

pane = new JTextPane();
pane.setSize(150, 100);
pane.setContentType("text/html");
pane.setText(

"<center><b><big>Applet Test</big></b>

"

+ "</center>");

getContentPane().add(pane, "Center");

JPanel buttons = new JPanel();
buttons.setBackground(Color.white);

JButton print = new JButton("Print");

buttons.add(print);

getContentPane().add(buttons, "South");

print.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
print();
}
});
}

/**
* DOCUMENT ME!
*/
void prep() {

URL url = null;
aset = new HashPrintRequestAttributeSet();
aset.add(MediaSizeName.ISO_A4);
aset.add(new Copies(1));

try {
url =
new URL("http://www.emanuelblagonic.com/wp-content/uploads/2007/06/google-homepage.jpg");
} catch (MalformedURLException e) {
e.printStackTrace();
}
PrintService pservices =
PrintServiceLookup.lookupDefaultPrintService();
System.out.println(pservices.getName());

DocFlavor flavor = javax.print.DocFlavor.INPUT_STREAM.JPEG;
PrintRequestAttributeSet attr_set = new HashPrintRequestAttributeSet();
attr_set.add(new Copies(1));
PrintService[] service = PrintServiceLookup.lookupPrintServices(flavor, attr_set);

doc = new SimpleDoc(url, javax.print.DocFlavor.URL.PDF, null);

try {
System.out.println("DOC : \n " + doc.getPrintData());
} catch (IOException e) {
e.printStackTrace();
}
/* Create a Print Job */
printerJob = pservices.createPrintJob();
}

/**
* DOCUMENT ME!
*/
void print() {
prep();
System.out.println("Printer Name : " +
printerJob.getPrintService());
try {
printerJob.print(doc, aset);

} catch (PrintException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Done Printing.");
}

}

Wednesday, May 27, 2009

What does rt.jar stand for in Java/JDK/JRE?

The most likely answer is, rt stands for RunTime. Some tend to think it stands for RooT, since this jar contains all java build-in classes. But I have yet to find any official Sun documents regarding this acronym.
Whether it stands for RunTime, RooT, or anything else is not important. The question I have is, why would the java creator chose to use such a undescriptive name. Maybe it can make your classpath shorter? But we rarely put rt.jar in system classpath.
Here are 2 reasons I don't like the name rt.jar:
* While experienced developers take it for granted, java beginners don't know what it is other than it's a jar. So it's one more questions in beginners' mind.
* The shorter the name, the easier it is to cause naming conflicts, at least visually. While rt.jar will always reside under $JAVA_HOME/jre/lib, it is possible your applications may have another jar also named rt.jar.
I know rt.jar will be with us as long as java is, but just for the sake of discussion, how would you name it differently? Maybe java.jar, or java-core.jar?
PS: What does jar stand for? Jar stands for Java Archive. A jar file usually has file name extension .jar. It contains mainly java class files but any types of files can be included, e.g., XML files, HTML files, properties files, gif/jpg image files, text files, PDF files, and binary files, and so on.
PS: What is the difference between a jar file and a zip file? Basically, a jar file is the same as a zip file, except that the jar file contains a META-INF directory to store metadata or attributes. The most well-known file is META-INF/MANIFEST.MF. You can customize the content of a MANIFEST.MF when creating a jar file, and if you don't, a default one is generated and included. For example:
Manifest-Version: 1.0
Created-By: 1.5.0_06 (Sun Microsystems Inc.)
It's perfectly fine to have other configuration files and directories under META-INF.

Java Jar File Naming Conventions and Examples.

util.jar is the worst jar file name I can think of. All I know is it contains some utility/helper classes. But it is unclear if they belong to an application server, or a framework, or any application sub-systems. You will need to ask someone or some docs to know what it is. It's part of the DataDirect JDBC Driver distribution.
On the other hand, good jar file names are always self-explanatory, for example: struts.jar, jboss-system.jar, commons-pool-1.1.jar
Some thoughts on jar file naming conventions:
1. Always use extension ".jar", not ".zip"
Theoretically, jar files can have any extension or no extension at all. If you specify it in the system classpath, it should be loadable. The problem is with automatic library detection and loading by containers and frameworks. It's expensive to scan all files so some sort of extension restriction is needed. For this reason, J2EE/JavaEE platform spec requires all library jar files use ".jar" extension, such as WEB-INF/lib/mybeans.jar.
2. Use hyphen (-) instead of underscore (_) as word separator
First, it's easier to type - than _; secondly, when the file name is underlined (e.g., in a hyperlink), the _ is invisible. Hyphen has been shunned in file names partly because it is an illegal character in java identifier. But this concern is unwarranted.
3. Append version number if distributed standalone
because they can be dropped into any applications, which may need specific versions. We don't want users to have to compare file size or extract some META-INF files to know its version. Some examples: hibernate3.jar, commons-logging-1.0.3.jar, and
log4j-1.2.8.jar.
4. Don't append version number if bundled inside other larger deliverables
because the enclosing deliverables, such as an application server (e.g., JBoss 4.0.4, jakarta-tomcat-5), a tool(e.g., apache-ant-1.6.5), aleady have the version numbers, thus no version number for jboss.jar, catalina.jar, and ant.jar.

The Worst Java Job Interview Questions.

Why are you looking for a job?
Strictly speaking, this is not a java question, but it shows up in almost every job interview I've been to. The interviewer is testing the candidate's motivation for a job change. Invariably, the answer will be something like, advancing career and professional development. Of course, the candidate won't tell you he/she is looking for a 15% salary increase to cover the gas price increase, or he doesn't get along with his co-workers, or he didn't get the promotion or bonus, or he was rated Under-Perform in last year's performance review.
Which OS do you use in your development work, Linux, Windows, or Solaris?
Java is cross-platform, and I couldn't care less about OS while I'm writing java code. Unless the job is specifically about porting applications to other OS and deploying/distributing applications, I don't see how this is relevant. J2EE, JavaEE and Web applications are all made up of components that are managed by the application server, and thus shielded from the underlying OS.
Are you familiar with Oracle Database, or DB2?
Java persistence can now be easily achieved with ORM frameworks such as Hibernate, TopLink. The latest release of EJB 3 and Java Persistence API has standardize the way persistence is done in Java, J2EE, and JavaEE. The goal of these industry efforts is to let Java developers forget database stuff, which should be left to DBA. Even if Java developers in this project need to deal with database directly, I suppose they need to know about database design concepts and SQL, not some Oracle or DB2 stored procedures.

A New Option in Jar Command in JDK 6

DK 6 adds a new feature to the jar command: e. Other options of the jar command are still the same. This is the partial usage from JDK 6 beta 2:
C:\tools\jdk6\bin>jar
Usage: jar {ctxui}[vfm0Me] [jar-file] [manifest-file] [entry-point] [-C dir] files ...
Options:
...
-e specify application entry point for stand-alone application
bundled into an executable jar file
...
For example, I run jar command to package a self-contained application in a jar file:
C:\ws\nb\scrap\build\classes>C:\tools\jdk6\bin\jar cvfe ..\..\dist\hello-world.jar com.javahowto.test.HelloWorld com
added manifest
adding: com/(in = 0) (out= 0)(stored 0%)
adding: com/javahowto/(in = 0) (out= 0)(stored 0%)
adding: com/javahowto/test/(in = 0) (out= 0)(stored 0%)
adding: com/javahowto/test/HelloWorld.class(in = 572) (out= 348)(deflated 39%)
Then I can distribute hello-world.jar to users, who can run hello-world app like this:
C:\download\hello>java -jar hello-world.jar
Hello world!
Users can run it with any version of java; it doesn't have to be JDK 6. What the extra e option does is simply adding a Main-Class entry in the jar's META-INF\MANIFEST.MF:
Manifest-Version: 1.0
Created-By: 1.6.0-beta2 (Sun Microsystems Inc.)
Main-Class: com.javahowto.test.HelloWorld
This new feature is helpful when packaging simple self-contained apps, and application client modules in J2EE/JavaEE, both of them require a Main-Class entry in MANIFEST.MF. So I don't have to create one beforehand, or have Apache Ant generate one.

How to run Tomcat manager web application

1. Add the security role manager to $CATALINA_HOME/conf/tomcat-users.xml, and assign this role to a username, say tomcat:


2. Start Tomcat:
$CATALINA_HOME/bin/startup.sh
(%CATALINA_HOME%\bin\startup.bat on windows)
3. Browser the URL http://localhost:8080, and click the Tomcat Manager link on the upper-left corner. In the basic login page, enter username tomcat and password tomcat, as specified in conf/tomcat-users.xml. Tomcat Manager web application allows you to view Tomcat server info, deploy and undeploy webapps, and other simple management tasks.

Who set my CLASSPATH?

I never set CLASSPATH environment variable. Instead I always use the explicit -classpath or -cp options when running java, javac, javap, etc. The other day I was surprised to see a CLASSPATH environment variable is set:
C:\tmp> set CLASSPATH
CLASSPATH=.;C:\Program Files\Java\jre1.5.0_09\lib\ext\QTJava.zip
C:\tmp> dir "C:\Program Files\Java\jre1.5.0_09\lib\ext\QTJava.zip"
06/12/2006 09:57 AM 1,180,476 QTJava.zip
It seems when I installed apple's quicktime plugin, it automatically set this CLASSPATH in my environment. I don't like this. I always assume a clean environment when running any java applications. So I removed it:
C:\tmp> set CLASSPATH=
C:\tmp> set CLASSPATH
Environment variable CLASSPATH not defined
I can tolerate an installer modifying my PATH, but not CLASSPATH.

Line tools NetBeans plugin

I don't like overloading my IDE with a bunch of plugins, but this is a must-have for my NetBeans (currently version 5.5.1).
[Update] Those features in line tool has been integrated into NetBeans proper 6.x. So if you are running NetBeans 6.1 (the latest as of 5/2008), line tool plugin is no longer needed.
I use it everyday to copy and paste lines of text without using CTRL-C CTRL-V. This is its official description:
Line Tools Support following operations in text editors:
1. Move Line (or lines spanned by selection) Up
2. Move Line (or lines spanned by selection) Down
3. Copy Line (or lines spanned by selection) Up
4. Copy Line (or lines spanned by selection) Down
5. Sort lines spanned by selection in ascending order
6. Sort lines spanned by selection in descending order
7. Remove duplicate lines while sorting. Maintain the caret position, the selection and the order of start and end of the selection when moving/copying the lines.
This is the first plugin I will install for every new NetBeans release. Unfortunately, NetBeans can't automatically migrate my installed plugins.
Oddly, this plugin doesn't show up in the official NetBeans plugin portal. The place to go is the author's (Sandip Chitale) blog.
You can choose either download the *.nbm file and manually install it, or add a new update center (Sandip Chitale's update center) to your NetBeans. After adding the update center, you will able to download a lot more good stuffs by Sandip Chitale.

How to create a thread

Execution in Java always take form of a thread. In simple programs only one thread occurs, often referred to as the 'main thread'.
In some programs though concurrent threads is necessary, or if you are building a Swing application with for example a progress bar you don't want the main thread to handle the updates of the UI.
Then you create an additional thread to take care of that. There are two main ways of creating a thread. The first is to extend the Thread class and the second is to implement the Runnable interface.
Extending Thread:
 
public class MyThread extends Thread {
/**
* This method is executed when the start() method is called on the thread
* so here you will put the 'thread code'.
*/
public void run() {
System.out.println("Thread executed!");
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Thread thread = new MyThread();
thread.start();
}
}
Implementing the Runnable interface:
 
public class MyRunnable implements Runnable {
/**
* As in the previous example this method is executed
* when the start() method is called on the thread
* so here you will put the 'thread code'.
*/
public void run() {
System.out.println("Thread executed!");
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
//create a Thread object and pass it an object of type Runnable
Thread thread = new Thread(new MyRunnable());
thread.start();
}
}

Setting thread priorities

Setting a threads priority can be very useful if one thread has more critical tasks to perform than another.
The Thread class has a method called setPriority(int level) with which you can alter the priority a Thread instance has.
The priority level range from 1 (least important) to 10 (most important) and if no level is explicitly set, a Thread instance has the priority level of 5.
In the first example below no priorites are set, so both threads have the priority level 5. The TestThread class implements the Runnable interface and in its
run() method loops from 1 to 10 and output the number along with its Thread id, which is passed to the constructor.
 
/**
* Main.java
*
* @author
*/
public class Main {
/**
* Starts two threads and wait for them to finish.
*/
public void setPrioritiesOnThreads() {
Thread thread1 = new Thread(new TestThread(1));
Thread thread2 = new Thread(new TestThread(2));
thread1.start();
thread2.start();
try {
//Wait for the threads to finish
thread1.join();
thread2.join();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
System.out.println("Done.");
}
/**
* Starts the program
*
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().setPrioritiesOnThreads();
}
class TestThread implements Runnable {
int id;
public TestThread(int id) {
this.id = id;
}
public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println("Thread" + id + ": " + i);
}
}
}
}
 
 
 
Since both threads have the same priority, the output will be a mix between them and could look like this:
 
Thread2: 1
Thread1: 1
Thread2: 2
Thread1: 2
Thread2: 3
Thread1: 3
Thread2: 4
Thread1: 4
Thread2: 5
Thread1: 5
Thread2: 6
Thread1: 6
Thread2: 7
Thread2: 8
Thread2: 9
Thread2: 10
Thread1: 7
Thread1: 8
Thread1: 9
Thread1: 10
Done.
 
The output could look different from on execution to another since we have no control of how the CPU will prioritize them.
If we set the priority on the threads we still haven't got exact control of the execution, but at least we can tell the CPU which one we think is
most important. The next example is identical to the one above except for the lines where the priority of the threads are set:
 
/**
* Main.java
*
* @author
*/
public class Main {
/**
* Starts two threads, setting priorities on them
* and wait for them to finish.
*
*/
public void setPrioritiesOnThreads() {
Thread thread1 = new Thread(new TestThread(1));
Thread thread2 = new Thread(new TestThread(2));
//Setting priorities on the Thread objects
thread1.setPriority(Thread.MAX_PRIORITY);
thread2.setPriority(Thread.MIN_PRIORITY);
thread1.start();
thread2.start();
try {
//Wait for the threads to finish
thread1.join();
thread2.join();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
System.out.println("Done.");
}
/**
* Starts the program
*
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().setPrioritiesOnThreads();
}
class TestThread implements Runnable {
int id;
public TestThread(int id) {
this.id = id;
}
public void run() {
for (int i = 1; i <= 10; i++) {
System.out.println("Thread" + id + ": " + i);
}
}
}
}
 
 
The output from the code looked like this when executed:
 
Thread1: 1
Thread1: 2
Thread1: 3
Thread1: 4
Thread1: 5
Thread1: 6
Thread1: 7
Thread1: 8
Thread1: 9
Thread1: 10
Thread2: 1
Thread2: 2
Thread2: 3
Thread2: 4
Thread2: 5
Thread2: 6
Thread2: 7
Thread2: 8
Thread2: 9
Thread2: 10
Done.
 
It is however not certain that the first thread will be prioritized to finish before the second thread starts every time.
It is, as mentioned earlier, up to the CPU to decide.

Remove duplicate items from an ArrayList

This code example shows how to remove duplicate items from an ArrayList.

ArrayList arrayList1 = new ArrayList();
arrayList1.add("A");
arrayList1.add("A");
arrayList1.add("B");
arrayList1.add("B");
arrayList1.add("B");
arrayList1.add("C");
//Create a HashSet which allows no duplicates
HashSet hashSet = new HashSet(arrayList1);
//Assign the HashSet to a new ArrayList
ArrayList arrayList2 = new ArrayList(hashSet) ;
//Ensure correct order, since HashSet doesn't
Collections.sort(arrayList2);
for (Object item : arrayList2)
System.out.println(item);



Note that you will have to sort the ArrayList if you want to be sure that the items remain
in correct order by calling the sort method of the Collection class.
This will produce the following output:
A
B
C




Creating and storing arrays in a map

Sometimes you want to create variable names dynamically, for example in a loop. One way of doing this is to not create the variables with different names but rather to store them in a Collection object that takes a key-value pair.
You can provide a unique key for the variable and then store its reference as the value.
In this examples first method we create 9 arrays which we store in a Map, each with different names. In the example below we use a TreeMap.
In the second method we print out the names of each key, and loop through the values of its value object (which is an array).
 
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
/**
*
* @author
*/
public class Main {
Map map = new TreeMap();
/**
* Example method for creating and storing arrays in a map
*/
public void createArrays() {
for (int i = 1; i <= 9; i++) {
int[] array = new int[3];
array[0] = i;
array[1] = i + 1;
array[2] = i + 2;
map.put(("array_" + i), array);
}
}
/**
* Example method for printing arrays stored in a map
*/
public void printArrays() {
Iterator iter = map.keySet().iterator();
while (iter.hasNext()) {
String arrayName = iter.next();
int[] array = map.get(arrayName);
System.out.println("Values for array " + arrayName + ":");
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
}
System.out.println();
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Main main = new Main();
main.createArrays();
main.printArrays();
}
}
The output of the code above will be:
Values for array array_1:
1
2
3
Values for array array_2:
2
3
4
Values for array array_3:
3
4
5
Values for array array_4:
4
5
6
Values for array array_5:
5
6
7
Values for array array_6:
6
7
8
Values for array array_7:
7
8
9
Values for array array_8:
8
9
10
Values for array array_9:
9
10
11

Convert a List (ArrayList) to an Array

This piece of Java code shows how to convert a List, in this case an ArrayList, to an Array by calling the method toArray() on the List object.
The toArray() method returns an array of the same type as the array provided as an argument to the method. The argument can be an empty array as in the example below.
 
/**
*
* @author
*/
public class Main {
public void ListToArray() {
List carList = new ArrayList();
carList.add("Dodge");
carList.add("Chevrolet");
carList.add("BMW");
carList.add("Toyota");
String[] carArray = carList.toArray(new String[0]);
for (String car : carArray) {
System.out.println(car);
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().ListToArray();
}
}
The code above generate the following output (the elements are ordered similarly in the array as in the list):
 
Dodge
Chevrolet
BMW
Toyota

Convert a List to a Set (ArrayList to HashSet)

This example shows how to convert from an ArrayList to a HashSet. Since most Collection objects have a constructor that allows for passing in another Collection object we are able to make these kinds of conversions easily.
In the example we create an ArrayList to which we add a few string items. Next we create a HashSet and provide the reference to the ArrayList as argument to the HashSet constructor.
Finally we just loop through the HashSet and print out the contents.
 
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
*
* @author
*/
public class Main {
/**
* Conversion from a List to a Set,
* or from an ArrayList to a HashSet object
*/
public void convertFromListToSet() {
List fruitsList = new ArrayList ();
fruitsList.add("Apples");
fruitsList.add("Bananas");
fruitsList.add("Oranges");
fruitsList.add("Grapes");
Set fruitsSet = new HashSet(fruitsList);
for (Object theFruit : fruitsSet)
System.out.println(theFruit);
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().convertFromListToSet();
}
}
The output from the code is not surprisingly the items in the same order as added to the ArrayList:
Apples
Bananas
Oranges
Grapes

Convert LinkedList to Array

This code example shows how to convert a LinkedList containing Strings to an array of Strings.
We begin by creating and populating the LinkedList with String representing different fruits. The actual conversion is done by calling the toArray() method of the list which returns the array. As input we create an empty String-array to tell the method to which type the elements should be converted.
There is actually another way of doing the conversion. Instead of passing an empty array to the toArray() method, we can pass an array of the same size as the List, and then it'll be populated with the elements. See an example further below.
 
package com.javadb.examples;
import java.util.LinkedList;
import java.util.List;
 
/**
*
* @author
*/
public class Main {
public void convertLinkedListToArray() {
List theList = new LinkedList();
theList.add("Apples");
theList.add("Bananas");
theList.add("Oranges");
theList.add("Grapes");
String[] fruits = theList.toArray(new String[0]);
for (int i = 0; i < fruits.length; i++) {
System.out.println(fruits[i]);
}
}
public static void main(String[] args) {
new Main().convertLinkedListToArray();
}
 
We could also have done the conversion like this:
 
String[] fruits = new String[theList.size()];
theList.toArray(fruits);
 
The output looks like this:
 
Apples
Bananas
Oranges
Grapes

List drives

This piece of code might come in handy on a Windows platform to list the drives of a computer.
 
import java.io.File;
public class FileUtil {
public void listDrives() {
File[] drives = File.listRoots();
for (int i = 0; i < drives.length; i++) {
System.out.println(drives[i]);
}
}
public static void main(String[] args) {
FileUtil fileutil = new FileUtil();
fileutil.listDrives();
}
}

Masking a password with the Console class

In Java 6 you can use the Console class to mask a password, or more precisely, no characters will be written as output to the console at all when you type the password.
This is achieved with help of the readPassword() method of the Console class. The method returns an array of char, which then easily is passed to the String class constructor to make it useful.
This example is best run in the console and not from within an IDE, since the System.console() method might return null in that case.
 
import java.io.Console;
/**
*
* @author
*/
public class Main {
/**
* Example method for entering password from the console
*/
public void passwordExample() {
Console console = System.console();
if (console == null) {
System.out.println("Couldn't get Console instance, maybe you're running this from within an IDE?");
System.exit(0);
}
console.printf("Testing password%n");
char passwordArray[] = console.readPassword("Enter your secret password: ");
console.printf("Password entered was: %s%n", new String(passwordArray));
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().passwordExample();
}
}

Using the RandomAccessFile class

This java code example illustrates how you can use the RandomAccessFile class.
The example in itself might seem pretty useless but the purpose is to show that you can both write to and read from a file with the same RandomAccessFile instance.
The RandomAccessFile class also enables you to get the current position of the file pointer by calling the method 'getFilePointer', or setting the file pointer position by calling the 'seek' method.
The behaviour of the RandomAccessFile class is similar to an array in the filesystem, but unlike an array you can alter the length of the file by calling the 'setLength' method.
If you are calling seek and then start to write data in an area that already contains data, it will be overwritten.
In this example we write two lines of code to the file, then we set the file pointer to the position at the end of the first line and read data from there and print it out.
 
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
/**
*
* @author
*/
public class Main {
/**
* Example method for using the RandomAccessFile class
*/
public void testRandomAccessFile(String filename) {
RandomAccessFile randomAccessFile = null;
try {
//Declare variables that we're going to write
String line1 = "First line\n";
String line2 = "Second line\n";
//Create RandomAccessFile instance with read / write permissions
randomAccessFile = new RandomAccessFile(filename, "rw");
//Write two lines to the file
randomAccessFile.writeBytes(line1);
randomAccessFile.writeBytes(line2);
//Place the file pointer at the end of the first line
randomAccessFile.seek(line1.length());
//Declare a buffer with the same length as the second line
byte[] buffer = new byte[line2.length()];
//Read data from the file
randomAccessFile.read(buffer);
//Print out the buffer contents
System.out.println(new String(buffer));
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (randomAccessFile != null)
randomAccessFile.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().testRandomAccessFile("myFile.txt");
}
}
The output to the file is:
First line
Second line
 
and the output to the console:
Second line

Reading objects from file using ObjectInputStream

This example shows how to read objects that has been serialized to a file with an ObjectOutputStream.
We simply create an instance of ObjectOuputStream and loop for as long as there are objects in the file.
The while condition could be argued since the readObject method will never return null, instead it will throw an EOFException when the end of the file is reached.
One could as well write 'while (true)' but as that is not good practice we won't do it here either. This example presumes that the number of objects in the file is unknown and therefore we cannot use a fixed number of iterations in the loop.
What this code example does instead is to catch the EOFException and just print out that the end of file is reached.
The file contains instances of the class Person and it was used in the corresponding example when an ObjectOutputStream was used to write objects to a file.
 
 
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
/**
*
* @author chintan patel
*/
public class Main {
/**
* Example method for using the ObjectInputStream class
*/
public void readPersons(String filename) {
ObjectInputStream inputStream = null;
try {
//Construct the ObjectInputStream object
inputStream = new ObjectInputStream(new FileInputStream(filename));
Object obj = null;
while ((obj = inputStream.readObject()) != null) {
if (obj instanceof Person) {
System.out.println(((Person)obj).toString());
}
}
} catch (EOFException ex) { //This exception will be caught when EOF is reached
System.out.println("End of file reached.");
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
//Close the ObjectInputStream
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().readPersons("myFile.txt");
}
}
The output from the code above looks like this:
James
Ryan
19
Obi-wan
Kenobi
30
End of file reached.
 
 

Writing objects to file with ObjectOutputStream

You can use the ObjectOutputStream class to write objects to an underlying stream.
In this code example we use it to write objects to a file using the FileOutputStream class as argument to the ObjectOutputStream constructor.
The class from which we create objects to write is a simple java class with three attributes, first name, last name and age. The important thing here is that it implements the Serializable interface.
Any object that is written on an ObjectOutputStream is serialized and therefore has to implement either the java.io.Serializable interface or the java.io.Externalizable interface.
This is what the Person class looks like:
 
import java.io.Serializable;
/**
*
* @author chintan patel
*/
public class Person implements Serializable {
private String firstName;
private String lastName;
private int age;
/**
* Creates a new instance of Person
*/
public Person() {
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
//Overriding toString to be able to print out the object in a readable way
//when it is later read from the file.
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append(firstName);
buffer.append("\n");
buffer.append(lastName);
buffer.append("\n");
buffer.append(age);
buffer.append("\n");
return buffer.toString();
}
}
 
----------------------------------------------------------------------------------
 
 
 
This is the code for creating instances of the Person class and writing them to an ObjectOuputStream:
 
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
/**
*
* @author chintan patel
*/
public class Main {
/**
* Example method for using the ObjectOutputStream class
*/
public void writePersons(String filename) {
ObjectOutputStream outputStream = null;
try {
//Construct the LineNumberReader object
outputStream = new ObjectOutputStream(new FileOutputStream(filename));
Person person = new Person();
person.setFirstName("James");
person.setLastName("Ryan");
person.setAge(19);
outputStream.writeObject(person);
person = new Person();
person.setFirstName("Obi-wan");
person.setLastName("Kenobi");
person.setAge(30);
outputStream.writeObject(person);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
//Close the ObjectOutputStream
try {
if (outputStream != null) {
outputStream.flush();
outputStream.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().writePersons("myFile.txt");
}
}

List file structure within folder or hard drive

This code example lists the files and folders and also the content in all subfolders.
With recursive calls the file/directory tree can be listed with
a relatively small amount of code.
The purpose of the getTabs method and the variable tabCounter is only to
make the output more viewable with indenting for each level.
 
 
import java.io.File;
public class FileStructure {
int tabCounter = 0;
public void listFilesAndFolders(String folder) {
File file = new File(folder);
if (!file.exists() !file.isDirectory()) {
System.out.println("Parameter is not a directory");
System.exit(1);
}
File[] fileArray = file.listFiles();
for (int i = 0; i < fileArray.length; i++) {
if (fileArray[i].isDirectory()) {
System.out.println(getTabs() + "- " + fileArray[i].getName());
tabCounter++;
listFilesAndFolders(fileArray[i].getAbsolutePath());
}
else {
System.out.println(getTabs() + fileArray[i].getName());
}
}
tabCounter--;
}
private String getTabs() {
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < tabCounter; i++)
buffer.append("\t");
return buffer.toString();
}
public static void main(String[] args) {
FileStructure fileStructure = new FileStructure();
fileStructure.listFilesAndFolders("C:\\temp");
}
}

Create a temporary file

Sometimes it come in handy to create a temporary file.
Here we create a temporary file with the prefix "temp_" as shown by the first parameter.
The second parameter is an optional suffix, if it\'s null as in the example, .tmp will be
used by default.
Optionally a third parameter can be defined pointing out the directory in which the file will
be created. If not specified (as below), the default temporary directory will be used.
 
 
import java.io.File;
import java.io.IOException;
public class FileUtil {
public void createTemporaryFile(String filename) {
try {
//Create the temp file
File f = File.createTempFile("temp_", null);
//Check where the default temp dir is located
System.out.println(f.getAbsolutePath());
//Delete the file when the program exists
f.deleteOnExit();
//Place any processing of the file here
// ...
}
catch (IOException ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
FileUtil fileutil = new FileUtil();
fileutil.createTemporaryFile("myfile.txt");
}
}

Read each line in a comma separated file into an array

In this example we read the lines of a comma separated file and split the values into an array.
This is done fairly easy with the split() method, which takes a separator as an argument and returns
an array of Strings.
 
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
 
public class CsvTest {
public void readFile() {
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("thefile.csv"));
String line = null;
while ((line = br.readLine()) != null) {
String[] values = line.split(",");
//Do necessary work with the values, here we just print them out
for (String str : values) {
System.out.println(str);
}
System.out.println();
}
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
}
catch (IOException ex) {
ex.printStackTrace();
}
finally {
try {
if (br != null)
br.close();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
}
public static void main(String[] args) {
CsvTest test = new CsvTest();
test.readFile();
}
}

List files of a certain type

To list files of a certain type, create an instance of the FileFilter
class and override it\'s accept method. Use that instance when calling
the list method of the File class.
 
import java.io.File;
import java.io.FilenameFilter;
public class FileUtil {
public void listFiles(String dir) {
File directory = new File(dir);
if (!directory.isDirectory()) {
System.out.println("No directory provided");
return;
}
//create a FilenameFilter and override its accept-method
FilenameFilter filefilter = new FilenameFilter() {
public boolean accept(File dir, String name) {
//if the file extension is .txt return true, else false
return name.endsWith(".txt");
}
};
String[] filenames = directory.list(filefilter);
for (String name : filenames) {
System.out.println(name);
}
}
public static void main(String[] args) {
FileUtil fileutil = new FileUtil();
fileutil.listFiles("C:\\\\temp");
}
}

Remove a line from a text file

This example shows how to delete a line from a file.
The method removeLineFromFile takes two parameters, the first parameter is the file to remove from and the second parameter is the content of the line to remove.
A tempfile is created and written to, except for the content that matches the second parameter.
This way very large files can be handled without demanding so much internal memory.
The original file is then deleted and the tempfile is renamed to the original filename.
 
For example, the file test.txt is located in the current directory and contains three lines, and we will remove the second line "bbbbb".
 
 
aaaaa
bbbbb
ccccc
 
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.File;
import java.io.FileWriter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
public class FileUtil {
 
public void removeLineFromFile(String file, String lineToRemove) {
try {
File inFile = new File(file);
if (!inFile.isFile()) {
System.out.println("Parameter is not an existing file");
return;
}
//Construct the new file that will later be renamed to the original filename.
File tempFile = new File(inFile.getAbsolutePath() + ".tmp");
BufferedReader br = new BufferedReader(new FileReader(file));
PrintWriter pw = new PrintWriter(new FileWriter(tempFile));
String line = null;
//Read from the original file and write to the new
//unless content matches data to be removed.
while ((line = br.readLine()) != null) {
if (!line.trim().equals(lineToRemove)) {
pw.println(line);
pw.flush();
}
}
pw.close();
br.close();
//Delete the original file
if (!inFile.delete()) {
System.out.println("Could not delete file");
return;
}
//Rename the new file to the filename the original file had.
if (!tempFile.renameTo(inFile))
System.out.println("Could not rename file");
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
public static void main(String[] args) {
FileUtil util = new FileUtil();
util.removeLineFromFile("test.txt", "bbbbb");
}
}
The file test.txt now looks like this:
 
aaaaa
ccccc

How to create a zip file

This code example shows how to create a zip file.
What we do is to create an input stream from the file we want to compress, and while we read from it we write the contents to an output stream.
This output stream is of type ZipOutputStream which takes an FileOutputStream as parameter.
Next we have to add a zip entry to the output stream before we start writing to it.
We will also clean up by closing the zip entry and both the input stream and output stream when we are done.
 
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
*
* @author chintan patel
*/
public class Main {
/**
* Creates a zip file
*/
public void createZipFile() {
try {
String inputFileName = "test.txt";
String zipFileName = "compressed.zip";
//Create input and output streams
FileInputStream inStream = new FileInputStream(inputFileName);
ZipOutputStream outStream = new ZipOutputStream(new FileOutputStream(zipFileName));
// Add a zip entry to the output stream
outStream.putNextEntry(new ZipEntry(inputFileName));
byte[] buffer = new byte[1024];
int bytesRead;
//Each chunk of data read from the input stream
//is written to the output stream
while ((bytesRead = inStream.read(buffer)) > 0) {
outStream.write(buffer, 0, bytesRead);
}
//Close zip entry and file streams
outStream.closeEntry();
outStream.close();
inStream.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().createZipFile();
}
}

How to list the contents of a zip file

To list the contents of a zip file you need to get the entries of the file since every file in a zip file is represented by an entry.
In this case we assume that the filename of the zip file is 'testfile.zip'. By calling the entries method of the ZipFile object we get an Enumeration back that can be used to loop through the entries of the file.
Note that we have to cast each element in the Enumeration to a ZipEntry.
Normally some more extensive processing of the entries would probably be done, but here we just print out the name of each entry (i.e the name of the file or directory in the zip file).
 
import java.io.IOException;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
/**
*
* @author chintan patel
*/
public class Main {
public void listContentsOfZipFile() {
try {
ZipFile zipFile = new ZipFile("testfile.zip");
Enumeration zipEntries = zipFile.entries();
while (zipEntries.hasMoreElements()) {
//Process the name, here we just print it out
System.out.println(((ZipEntry)zipEntries.nextElement()).getName());
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().listContentsOfZipFile();
}
}

Extract contents of a zip file

This example shows how to extract a zipfile containing one file (or entry).
The name of the zip file is 'compressed.zip' and we want to write the contents to a file called 'extracted.txt'.
We start by opening an input stream to the compressed file and an output stream to the file where we want the content to be extracted.
After that we get the next entry of the zip file (and the only entry in this case) - test so it's not null, and then start reading the contents from the input stream and writing each chunk read to the output stream.
As usual we should clean up properly afterwards so we close the input and output streams.
 
 
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
/**
*
* @author chintan patel
*/
public class Main {
/**
* Extracts a zip file
*/
public void extractZipFile() {
try {
String zipFileName = "compressed.zip";
String extractedFileName = "extracted.txt";
//Create input and output streams
ZipInputStream inStream = new ZipInputStream(new FileInputStream(zipFileName));
OutputStream outStream = new FileOutputStream(extractedFileName);
ZipEntry entry;
byte[] buffer = new byte[1024];
int nrBytesRead;
//Get next zip entry and start reading data
if ((entry = inStream.getNextEntry()) != null) {
while ((nrBytesRead = inStream.read(buffer)) > 0) {
outStream.write(buffer, 0, nrBytesRead);
}
}
//Finish off by closing the streams
outStream.close();
inStream.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().extractZipFile();
}
}

Convert a String to int

Use the static method parseInt of the Integer class to convert
a String to an int as below:
 
public void convertStringToInt() {
String sValue = "5";
int iValue = 0;
try {
iValue = Integer.parseInt(sValue);
}
catch (NumberFormatException ex) {
System.out.println("The String does not contain a parsable integer");
}
//Additional code goes here...
}
 
 
 
 
 
Alternatively you can pass a String to the Integer class constructor
and call the intValue-method of the object:
 
 
public void convertStringToInt() {
String sValue = "5";
int iValue;
try {
iValue = new Integer(sValue).intValue();
}
catch (NumberFormatException ex) {
System.out.println("The String does not contain a parsable integer");
}
//Additional code goes here...
}

Convert an int value to String

This code example shows how to convert an int value to a String object.
Actually there are a few possible ways of doing this and three of the most common methods of doing so is presented here.
First we use the static method toString() of the Integer class which takes an integer as argument and returns a String.
The second way of converting from int to String is to instantiate the Integer class and pass the int value to the constructor, and then call the toString() method on the object.
Finally the easiest way of converting from datatype int to String is to simply concatenate the int value to an empty String. That way the value will automatically be converted and appended to the String.
After every conversion the converted value along with the method of which it was converted is printed out to show that the object returned is really an instance of the String class.
 
 
 
/*
* Main.java
*
* @author chintan patel
*/
public class Main {
/*
* This method converts an int value to a String object.
*/
public void convertIntToString() {
int intToConvert = 50;
//One way of converting from int to String
String convertedValue = Integer.toString(intToConvert);
System.out.println(convertedValue + " : " + Integer.toString(intToConvert).getClass());
//Another way of converting from int to String
convertedValue = new Integer(intToConvert).toString();
System.out.println(convertedValue + " : " + new Integer(intToConvert).toString().getClass());
//A third way of converting from int to String
convertedValue = "" + intToConvert;
System.out.println(convertedValue + " : " + ("" + intToConvert).getClass());
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().convertIntToString();
}
}

Convert String to byte

This example shows how to convert a String to a byte.
The String can only contain digits (or start with the - sign) and the number has to be within the byte range, otherwise a NumberFormatException will be thrown.
The output from the code below is:
65
Tried to convert an invalid value
 
 
/**
*
* @author chintan patel
*/
public class Main {
/**
* Example method for converting a String to a byte
*/
public void convertStringToByte() {
try {
String s = "65";
byte b = Byte.valueOf(s);
System.out.println(b);
//Causes a NumberFormatException since the value is out of range
System.out.println(Byte.valueOf("129"));
} catch (NumberFormatException ex) {
System.out.println("Tried to convert an invalid value");
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().convertStringToByte();
}
}

Convert String to character array

This example shows how to do a String to character array conversion. The String class has a neat method for doing this, toCharArray().
In the code example below the String is converted to a char array and each element of the array is printed out.
 
 
/**
* Main.java
*
* @author chitnan patel
*/
public class Main {
/**
* Converts a String to a character array
*/
public void convertStringToCharArray() {
String str = "Abcdefg";
char[] cArray = str.toCharArray();
for (char c : cArray)
System.out.println(c);
}
/**
* Starts the program
*
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().convertStringToCharArray();
}
}
The output from the executed code:
 
A
b
c
d
e
f
g

Character array to String conversion

This java code example shows how to convert an array of characters to a String.
To accomplish this we can utilize one of the String class many contructors, which takes an array of characters as parameter.
 
/**
* Main.java
*
* @author chintan patel
*/
public class Main {
/**
* Converts an array of characters to a String
*/
public void convertCharArrayToString() {
char[] charArray = new char[] {'a', 'b', 'c'};
String str = new String(charArray);
System.out.println(str);
}
/**
* Starts the program
*
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().convertCharArrayToString();
}
}

Convert byte to String

This example shows three ways of converting a variable of datatype byte to a String.
The first example uses the wrapper class Byte and it's static method toString to convert the byte.
The second example just concatenates the byte with an empty String, and the value is automatically casted to a String.
The final example creates a byte array which is passed to the constructor of the String class.
The output of the code below is:
65
65
A
 
 
 
/**
*
* @author chintan patel
*/
public class Main {
/**
* Example method for converting a byte to a String.
*/
public void convertByteToString() {
byte b = 65;
//Using the static toString method of the Byte class
System.out.println(Byte.toString(b));
//Using simple concatenation with an empty String
System.out.println(b + "");
//Creating a byte array and passing it to the String constructor
System.out.println(new String(new byte[] {b}));
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().convertByteToString();
}
}