Spaces:
Running
Running
| Java has variables of reference type. | |
| In a reference type variable, the variable is placed in reference to the actual value. | |
| String b = "bye!"; | |
| - immutable | |
| - but can point to another string | |
| ================ | |
| String name = "Jack Java"; | |
| String address = "Java rd. " + "64" + ", 12345, Javatown"; | |
| String phonenum = "040-" + (12345 * 23456); //multiply, then concat as strings | |
| System.out.println(name); | |
| System.out.println(address); | |
| System.out.println(phonenum); | |
| Program outputs: | |
| Jack Java | |
| Java rd. 64, 12345, Javatown | |
| 040-289564320 | |
| ================ | |
| String length - .length() | |
| String first = "Hey"; | |
| System.out.println(first.length()); | |
| System.out.println("Hello everyone".length()); | |
| int length = (first + "!!!").length(); | |
| System.out.println(length); | |
| Program outputs: | |
| 3 | |
| 14 | |
| 6 | |
| ================ | |
| single characters - charAt(i) | |
| Scanner reader = new Scanner(System.in); | |
| System.out.print("Give a string: "); | |
| String str = reader.nextLine(); | |
| for (int i=0; i<str.length(); i++) { | |
| System.out.println(str.charAt(i)); | |
| } | |
| Program outputs: | |
| Give a string: Test | |
| T | |
| e | |
| s | |
| t | |
| // returns a 'character' - which is a number type | |
| char first = 'O'; | |
| char second = 'k'; | |
| System.out.println(first + second); | |
| Program outputs: | |
| 186 | |
| // A character can be converted into a string | |
| // 1 either by using the method toString in the Character class | |
| char cr = 'X'; | |
| String str = Character.toString(cr); | |
| Program outputs: | |
| X | |
| // 2 or usually more easily by CONCATenating a character with an EMPTY STRING: | |
| char first = 'O'; | |
| char second = 'k'; | |
| System.out.println("" + first + second); | |
| Program outputs: | |
| Ok | |
| ================ |