Overview

This tutorial will teach coders how to convert Strings into other data types such as ints, and character arrays. Also, it will include how to convert back from those types to a String.

From String

Often, you are given input in the form of a string, but you want that input to be something else. There are some easy ways to fix this problem.

First, let's declare ourselves a string to use in examples.

String example = "Hello World";

Now, let's say that we wanted to turn our string into an array of characters. The Java String class will help us out. All we need to do is execute the following command.

char outArray[] = example.toCharArray();

That was easy enough. But what if our string contains numbers and we'd like to use them as ints, shorts, longs, or something of that sort. That is also easy, but we need a new string.

String x = "1234";

Now our string actually contains a number, so we can turn it in to an int.

int y = Integer.parseInt(x);

Similiar parsing functions exist like Double.parseDouble() and Long.parseLong().

To String

Sometimes, after you turn the string into an int or CharArray, then you must do a few operations on those data types and then turn it back in to a string before you return it. First let's turn a charArray in to a string.

char inArray[] = {'C','a','t'}; String outString = String.valueOf(inArray);

And now, we'll do the integer.

int x = 12; String y = String.valueOf(x);

Now that you've mastered your first tutorial, try the challenge below.

Challenge

Write four programs, one to do each of the conversions that we discussed.

String -> CharArray
Sample Inputs:
"Goldfish"
"This is fun."

Sample Outputs:
{'G','o','l','d','f','i','s','h'}
{'T','h','i','s',' ','i','s',' ','f','u','n','.'}

String -> Int
Sample Inputs:
"1"
"314159"

Sample Outputs:
1
314159

CharArray -> String and
Int -> String
Use the above outputs as inputs and vice versa.

plants