Conversions part 2
Conversions part 2
java
Copy code
String str = "hello";
char[] chars = str.toCharArray(); // Convert String to char array
java
Copy code
for (char ch : chars) {
System.out.println(ch);
}
java
Copy code
char[] chars = {'h', 'e', 'l', 'l', 'o'};
String str = new String(chars); // Convert char array to String
java
Copy code
System.out.println(str); // Output: hello
String to Integer:
java
Copy code
String numStr = "123";
int num = Integer.parseInt(numStr); // Convert String to int
java
Copy code
System.out.println(num + 5); // Output: 128
Integer to String:
java
Copy code
int num = 456;
String numStr = Integer.toString(num); // Convert int to String
java
Copy code
System.out.println("Number: " + numStr); // Output: Number: 456
java
Copy code
String str = "hello";
List<Character> charList = new ArrayList<>();
for (char ch : str.toCharArray()) {
charList.add(ch); // Convert String to List of characters
}
java
Copy code
System.out.println(charList); // Output: [h, e, l, l, o]
java
Copy code
List<Character> charList = Arrays.asList('h', 'e', 'l', 'l', 'o');
StringBuilder sb = new StringBuilder();
for (Character ch : charList) {
sb.append(ch); // Convert List of characters to String
}
String str = sb.toString();
java
Copy code
System.out.println(str); // Output: hello
java
Copy code
String str = "apple,banana,orange";
List<String> words = Arrays.asList(str.split(",")); // Convert String to List
of Strings
Purpose: To split a string into smaller substrings and store them in a list.
Example:
java
Copy code
System.out.println(words); // Output: [apple, banana, orange]
java
Copy code
List<String> words = Arrays.asList("apple", "banana", "orange");
String result = String.join(",", words); // Convert List of Strings to a
single String
java
Copy code
System.out.println(result); // Output: apple,banana,orange
String to double:
java
Copy code
String numStr = "45.67";
double num = Double.parseDouble(numStr); // Convert String to double
java
Copy code
System.out.println(num + 5); // Output: 50.67
double to String:
java
Copy code
double num = 78.9;
String numStr = Double.toString(num); // Convert double to String
java
Copy code
System.out.println("Value: " + numStr); // Output: Value: 78.9