int n = 46; double x = 2.18; char c = 'A'; String s = "apple"; String t = "102"; String u = "B"; // Convert int to other datatypes. System.out.println((double) n); System.out.println((char) n); System.out.println(String.valueOf(n)); // Convert double to other datatypes. System.out.println((int) x); System.out.println((char) x); System.out.println(String.valueOf(x)); // Convert char to other datatypes. System.out.println((int) c); System.out.println((double) c); System.out.println(String.valueOf(c)); // Convert String to other datatypes. System.out.println(Integer.parseInt(t)); System.out.println(Double.parseDouble(t)); System.out.println(u.charAt(0));You can use casts to convert one numeric type to another. For example:
double x = 65.3782732; int n = (int) x; char c = (char) n;char counts as a numeric type because it contains the Unicode numeric code of a character.
public class Main { public static void main(String[ ] args) { // Test these String methods: // indexOf isBlank isEmpty length toUpperCase String s = "umbrella"; String t = " \n \t "; String u = ""; System.out.println(s.indexOf("bre")); // Output: 2 System.out.println(s.isBlank( ) + " " + t.isBlank( ) + " " + u.isBlank( )); // Output: false true true System.out.println(s.isEmpty( ) + " " + t.isEmpty( ) + " " + u.isEmpty( )); // Output: false false true System.out.println(s.length( ) + " " + t.length( ) + " " + u.length( )); // Output: 8 5 0 System.out.println(s.toUpperCase( )); // Output: UMBRELLA } }
int i = 1; while(i <= 100) { System.out.println(i); i++; }
for(initialization; condition; iteration) { body }
for(int i = 1; i <= 100; i++) { System.out.println(i); }
import java.util.Scanner; public class Main { public static void main(String[ ] args) { Scanner in = new Scanner(System.in); System.out.print("Enter word for a one digit integer: "); String word = in.nextLine( ); // Declare and initialize num to 0 to avoid // an uninitialized variable warning. int num = 0; switch(num) { case "zero": num = 0; break; case "one": num = 1; break; case "two": num = 2; break; case "three": num = 3; break; case "four": num = 4; break; case "five": num = 5; break; case "six": num = 6; break; case "seven": num = 7; break; case "eight": num = 8; break; case "nine": num = 9; break; default: num = -1; break; } if (num == -1) { System.out.println("Illegal input."); } else { System.out.println("The integer is " + num + "."); } in.close( ); } }
34 56 72 91 15
List Indices | 0 | 1 | 2 | 3 | 4 |
List Values | 34 | 56 | 72 | 91 | 15 |
// Method 1: int[ ] a = {34, 56, 72, 91, 15}; // Method 2: int[ ] a = new int[5]; // This method initializes the array to all zeros. // Method 3: int[ ] a = new int[5]; a[0] = 34; a[1] = 56; a[2] = 72; a[3] = 91; a[4] = 15;
// Traditional loop for(int i = 0; i < a.length; i++) { System.out.println(a[i]); } // Modern for-each loop for(int n : a) { System.out.println(n); }