0% found this document useful (0 votes)
40 views

Computer Programming 2 Week 11

The equals method is used to check if two objects are equal. It returns a boolean value of true if they are equal and false if they are not. The equals method can be used to compare strings and objects but not primitive data types like int. To compare primitive data types, they must first be converted to objects. The charAt and replace methods can be used to access and modify individual characters in a string.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
40 views

Computer Programming 2 Week 11

The equals method is used to check if two objects are equal. It returns a boolean value of true if they are equal and false if they are not. The equals method can be used to compare strings and objects but not primitive data types like int. To compare primitive data types, they must first be converted to objects. The charAt and replace methods can be used to access and modify individual characters in a string.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 9

The equals Method in Java

 You can check two strings to see if they are the same. For this, use the
equals method in Java. Here's some code:

 In this code, we want to check if one email address is the same as another.
The first two lines set up two string variables, one for each email address.
The third line sets up a Boolean variable. That's because the equals
method returns a value of true or false. The fourth line is where we use
the method:
isMatch = email_address1.equals( email_address2 );

 In between the round brackets of the equals method, you place the string
you're trying to check. The other string goes before the equals method.
Java will then tell you (true or false) whether the two are the same. The IF
statement checks which one it is.

 The equals method only compares objects, however. It's OK for strings,
because they are objects. But you can't use the equals method to compare
int variables. For example, this code would get you an error:

int num1 = 12;


int num2 = 13
Boolean isMatch = false;

isMatch = num1.equals(num2);

 The int variable is a primitive data type, and not an object. You can turn
the primitive int data type into an object, though:
int num1 = 12;
Integer num_1 = new Integer(num1);

 Here, the int variable called num1 is being turned into an Integer object.
Note the use of the new keyword. In between the round brackets of Integer,
you put the primitive int data type you want to convert to an object.

Video tutorial:

https://www.youtube.com/watch?v=9PsQdsjij1o

The charAt method in Java

 You can check to see which single character is in a particular string. The
charAt method is used for this in Java. Here's some code to try:

String email_address = "meme@me.com";

char aChar = email_address.charAt( 4 );


System.out.println( aChar );

 This code checks which letter as at position 4 in the email address string.
The return value is a variable of type char:
char aChar = email_address.charAt( 4 );

 When the above code is run, the output is the character @. The number
between the round brackets of charAt is the position in the string you're
trying to check. Here, we want to get at the character in position 4 of the
email_address string. Again, the count starts at 0, just like substring.

 One good use for charAt is for taking a letter from a string variable that is
typed by a user, and then converting it to a single char variable. For
example, you could ask the user to type Y to continue or an N to exit. Have
a look at this code:
 We can't use the Scanner class directly to get a single letter to store in a
char variable. So we use the next( ) method to get the next string that the
user inputs. There's a next integer, next long, next double - even a next
Boolean. But there's no next char. Even if the user inputs a single
character it will still be a string and not a char. (Remember: a char variable
stores a Unicode number as an integer.)

 We can use charAt to get a character from any string that the user inputs,
even if the user inputs a single letter:
char aChar = aString.charAt( 0 );

 All we're saying is "Get the character at position 0 in the string called
aString, then store it in the aChar variable".

 We've added an IF statement to test what is in the aChar variable. (Note


the use of single quotes around the letter Y.)

Video Tutorial:

https://www.youtube.com/watch?v=F3WBayULxFQ

The replace Method in Java

 The replace method in Java is used to replace all occurrence of a


character/s in a particular string. Take this sentence:
"Where are you books?"
 We want to replace "you" with "your". Here's the code:

 There are several ways to use the replace method, and they differ in what
you put between the round brackets of the method. We're replacing one
sequence of characters with another. Think of the comma separating the
two as the word "with". You'd then have "Replace you with your".

 You can also replace single character:


aString.replace( '£', '@' )

 The above code reads "Replace £ with @".

Video tutorial:

https://www.youtube.com/watch?v=A4K-uKY8N-A

Trim whitespace in Java

 You can trim white space from your strings White space is things like
space characters, tabs, and newline characters - the characters you can't
see, in other words. The trim method is easy to use:
String amend = " white space ";
amend = amend.trim( );

 So the trim method goes after the string you want to amend. The blank
characters before the word "white" and after "space" in the code above will
then be deleted.

 If you're getting input from a user then it's always a good idea to use trim
on the inputted strings.

Video tutorial:
https://www.youtube.com/watch?v=7f0Dci6nZNs

Java Formatted Strings

 Strings of text can be formatted and output with the printf command. The
printf command understands a series of characters known as a format
specification. It then takes a string of text and formats it, based on the
format specification passed over. As an example, supposed we wanted the
Output window to display text in neat columns, like this:

 The first column is left-justified, and the second column is right-justified.


The code for the Exam_Name and Exam_Grade headings was this:

String heading1 = "Exam_Name";


String heading2 = "Exam_Grade";

System.out.printf( "%-15s %15s %n", heading1, heading2);

 To get the left-justified column, you need a percentage symbol, a minus


symbol, the number of characters, and then the letter "s" (lowercase). So
''%-15s'' means fifteen characters left-justified.

 To get a right-justified column the same sequence of characters are used,


except for the minus sign.

 To get a newline %n is used. Note that the characters are surrounded with
double quotes.

 After a comma, you type the text that you want formatting. The first
comma in the code above separates the format specification from the text
being formatted.
 Here's some tables of the various options.

String Formatting

 If you want to format numbers then you can either use the "d" character
or, for floating point numbers, the "f" character.

Integer Formatting

Floating Point Number Formatting


 Here are some code examples of String, integer and floating point
formatting. Try them out for yourself.
System.out.printf( "%s %d %n", "Total:", 34573 );

 The text "Total:" will be formatted as a string (%s), while the numbers
34573 will be formatted as numbers (%d).
Output:
Total: 34573

 System.out.printf( "%s %10d %n", "Total:", 34573 );


 Same as above but the numbers occupy 10 places, with spaces to
the left as padding.

 System.out.printf( "%-10d %10d %n",22334, 34573 );


 Two set of numbers. The first one is left-justified; the second one is
right-justified
Output:
22334 34573

 System.out.printf( "%010d %10d %n", 22334, 34573 );


 Two sets of numbers again. The first one is padded with leading
zeros, this time. The second one is right-justified, but spaces are
used as padding to the left instead of zeros.
Output:
0000022334 34573

 System.out.printf( "%f %n", 345.73);


 Format a floating point number, and add a new line character. The
floating point number will have six decimal places.
Output:
345.730000

 System.out.printf( "%f %n", 345.73);


 Same as above but will format to only two decimal places.
Output:
34.57

 Finally, here's the table again from the start of this formatting section:

 And here's the code for the above formatted output:


 Have a play around with formatting, and see how you get on. If you get
error messages you may have gotten your "s" formatting confused with
your "d" formatting!

Video tutorial:

https://www.youtube.com/watch?v=moQ3Kr8ouiU

Activity:

1. Write a Java program to replace all the 'd' characters with 'f' characters.
Sample Output:
Original string: The quick brown fox jumps over the lazy dog.
New String: The quick brown fox jumps over the lazy fog.
2. Write a Java program to reverse every word in a string using methods.
Sample Output:
The given string is: This is a test string
The string reversed word by word is:
sihT si a tset gnirts

You might also like