Lab Tutorial 5
Lab Tutorial 5
Lab Tutorial 5
Fall 2016
Lab 5
1) Characters in JAVA
Character is a single digit, letter or symbol. Java provides char as primitive data type also a
meta-class, “Character” that contain some useful methods to be used.
Note: We cannot add, subtract or multiply characters, but we can compare them using ==, !=, <,
… etc. operators.
Syntax to make char array:
chararrayName [] = { value1, value2,….};
Activity 2:Declare a char type array and store characters of your name in it,
with 1st letter in uppercase and others in lower.
Activity 3:Declare a function that takes char as parameter and returns true if
it‟s a symbol (i.e.: $,%,+…), otherwise false.
1
COMP 295 JAVA Programming
Fall 2016
3) Strings in JAVA
Stringsare a sequence of characters. Strings are objects (i.e.: Build-in class) and not a primitive
data type.A String is an array of characters.
// To initialize a String.
s2 = "Hello World!";
// Adding Strings.
s3 = "Hello";
s4 = " World!";
s = s3 + s4;
6) Concatenating Strings:
Concatenation means combining two or more Strings or variables as String.
The String class includes a method for concatenating two strings:
2
COMP 295 JAVA Programming
Fall 2016
string1.concat(string2);
This returns a new string that is string1 with string2 added to it at the end.
Strings are more commonly concatenated with the + operator, as in
which prints:
JAVA is Fun!
Note:Such a concatenation can be a mixture of any objects. For each object that is not a String,
its toString() method is called to convert it to a String.
Activity 4:Declare 2 Strings „a‟ & „b‟, initialize one with constructor calland
other without constructor call. Print their contents. Now make a new String
made up of first char of „a‟ and last char of „b‟.
Activity 6:Make a function that takes char array as parameter, pass and
convert char array created in Activity2 into String with all uppercase letters.
Return greeting of the form “HELLO BOB”.
Activity 7:Given a string, return a new string made of 3 copies of the first 2
chars of the original string. The string may be any length. If there are fewer
than 2 chars, use whatever is there.
Eg.: Input= Hello Output= HeHeHe. Input= h Output= hhh