- Do the following in Java:
- Declare a String object named compiler and assign "javac" to it
- Declare a String object named sourceCode and assign "StringsExercises.java" to it
- Declare and display a String object named cmdLine and assign it compiler and sourceCode concatenated together so that it displays:
javac StringsExercises.java
- Write a method that counts the number of lines in a String object. For example, for the following String:
"Two roads diverged in a yellow wood\nAnd sorry I could not travel both\nAnd be one traveler long I stood\nAnd looked down one as far as I could\nTo where it bent in the undergrowth\n\nThen took the other as just as fair\nAnd having perhaps the better claim\nBecause it was grassy and wanted wear\nThough as for that the passing there\nHad worn them really about the same\n\nAnd both that morning equally lay\nIn leaves no step had trodden black\nOh I kept the first for another day\nYet knowing how way leads on to way\nI doubted if I should ever come back\n\nI shall be telling this with a sigh\nSomewhere ages and ages hence\nTwo roads diverged in a wood and I\nI took the one less traveled by\nAnd that has made all the difference\n"
the method would return 23
- Optional: Display the lengths of each line
- What does the following display:
System.out.println( compiler.substring( 0, 4 ) );
System.out.println( sourceCode.substring( 2, 6 ) );
System.out.println( sourceCode.substring( 17 ) );
- What does the following display (and why)?
System.out.println( "I have " + 5 + " fingers on one hand, and " + 5 + " fingers on one hand, so I a total of have " + 5 + 5 + " fingers!");
- What does the following display (and why)?
System.out.println( "\"java\" is found at index: " + cmdLine.indexOf( "java" ) );
System.out.println( "\"java\" is found at index: " + cmdLine.indexOf( "java", 5 ) );
System.out.println( "\"java\" is found last at index: " + cmdLine.lastIndexOf( "java" ) );
- Discuss with someone else what is the most important difference between a String object and a StringBuffer or StringBuilder object.
- Optional: Complete the above steps with a StringBuffer or StringBuilder object
- Complete the following:
- Declare a String object named name and assign it your name
- Declare a String object named nameLowerCase and assign it a lowercase version of your name using a String method
- What will the following display?
System.out.println( "name == nameLowerCase: " + (name == nameLowerCase) );
System.out.println( "name.equals( nameLowerCase ): " + (name.equals( nameLowerCase ) ));
System.out.println( "name.compareTo( nameLowerCase ): " + (name.compareTo( nameLowerCase ) ));