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

Lab 04 - Loops, Arrays and Strings: Comparison For Loop While Loop Do While Loop

The document discusses loops, arrays, and strings in Java. It provides an introduction and comparison of for, while, and do-while loops. It explains when to use each type of loop and provides syntax examples. The document also discusses Java arrays, including advantages and disadvantages. Finally, it covers Java strings, treating them as objects, and provides examples of common string methods.

Uploaded by

Usama Chauhdary
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views

Lab 04 - Loops, Arrays and Strings: Comparison For Loop While Loop Do While Loop

The document discusses loops, arrays, and strings in Java. It provides an introduction and comparison of for, while, and do-while loops. It explains when to use each type of loop and provides syntax examples. The document also discusses Java arrays, including advantages and disadvantages. Finally, it covers Java strings, treating them as objects, and provides examples of common string methods.

Uploaded by

Usama Chauhdary
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Department of Electrical Engineering Military College of Signals NUST

Lab 04 – Loops, arrays and strings


Objective:
Understanding and writing Loops, arrays and strings in Java

Comparison for loop while loop do while loop

Introduction The Java for loop is a The Java while loop The Java do while
control flow is a control flow loop is a control
statement that statement that flow statement
iterates a part of executes a part of that executes a
the programs multipl the programs part of the
e times. repeatedly on the programs at least
basis of given once and the
boolean condition. further execution
depends upon the
given boolean
condition.

When to use If the number of If the number of If the number of


iteration is fixed, it is iteration is not iteration is not
recommended to use fixed, it is fixed and you
for loop. recommended to must have to
use while loop. execute the loop
at least once, it is
recommended to
use the do-while
loop.

Object Oriented Programming


Department of Electrical Engineering Military College of Signals NUST

Syntax for(init;conditio while(condition) do{


n;incr/decr){ { //code to be
// code to be //code to be executed
executed executed }while(conditio
} } n);

Example //for loop //while loop //do-while loop


for(int int i=1; int i=1;
i=1;i<=10;i++){ while(i<=10){ do{
System.out.printl System.out.print System.out.prin
n(i); ln(i); tln(i);
} i++; i++;
} }while(i<=10);

Syntax for for(;;){ while(true){ do{


infinitive //code to be //code to be //code to be
loop executed executed executed
} } }while(true);

Java Arrays

Normally, an array is a collection of similar type of elements which has contiguous memory
location.

Java array is an object which contains elements of a similar data type. Additionally, The
elements of an array are stored in a contiguous memory location. It is a data structure where we
store similar elements. We can store only a fixed set of elements in a Java array.

Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd
element is stored on 1st index and so on.

Object Oriented Programming


Department of Electrical Engineering Military College of Signals NUST

Unlike C/C++, we can get the length of the array using the length member. In C/C++, we need
to use the sizeof operator.

In Java, array is an object of a dynamically generated class. Java array inherits the Object
class, and implements the Serializable as well as Cloneable interfaces. We can store primitive
values or objects in an array in Java. Like C/C++, we can also create single dimentional or
multidimentional arrays in Java.

Advantages

o Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
o Random access: We can get any data located at an index position.

Disadvantages

o Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its
size at runtime. To solve this problem, collection framework is used in Java which grows
automatically.

Java String

In Java, string is basically an object that represents sequence of char values. An array of
characters works same as Java string. For example:

char[] ch={'j','a','v','a','t','p','o','i','n','t'};

String s=new String(ch);

is same as:

String s="javatpoint";

Java String class provides a lot of methods to perform operations on strings such as compare(),
concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.`

Object Oriented Programming


Department of Electrical Engineering Military College of Signals NUST

Example

public class StringExample{


public static void main(String args[]){
String s1="java";//creating string by java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);

Java String class methods

The java.lang.String class provides many useful methods to perform operations on sequence of
char values.

No. Method Description

1 char charAt(int index) returns char value for the particular


index

2 int length() returns string length

3 static String format(String format, returns a formatted string.


Object... args)

4 static String format(Locale l, String returns formatted string with given


format, Object... args) locale.

5 String substring(int beginIndex) returns substring for given begin


index.

6 String substring(int beginIndex, int returns substring for given begin


endIndex) index and end index.

7 boolean contains(CharSequence s) returns true or false after matching


the sequence of char value.

Object Oriented Programming


Department of Electrical Engineering Military College of Signals NUST

8 static String join(CharSequence returns a joined string.


delimiter, CharSequence... elements)

9 static String join(CharSequence returns a joined string.


delimiter, Iterable<? extends
CharSequence> elements)

10 boolean equals(Object another) checks the equality of string with the


given object.

11 boolean isEmpty() checks if string is empty.

12 String concat(String str) concatenates the specified string.

13 String replace(char old, char new) replaces all occurrences of the


specified char value.

14 String replace(CharSequence old, replaces all occurrences of the


CharSequence new) specified CharSequence.

15 static String equalsIgnoreCase(String compares another string. It doesn't


another) check case.

16 String[] split(String regex) returns a split string matching regex.

17 String[] split(String regex, int limit) returns a split string matching regex
and limit.

18 String intern() returns an interned string.

19 int indexOf(int ch) returns the specified char value index.

20 int indexOf(int ch, int fromIndex) returns the specified char value index
starting with given index.

21 int indexOf(String substring) returns the specified substring index.

22 int indexOf(String substring, int returns the specified substring index


fromIndex) starting with given index.

Object Oriented Programming


Department of Electrical Engineering Military College of Signals NUST

23 String toLowerCase() returns a string in lowercase.

24 String toLowerCase(Locale l) returns a string in lowercase using


specified locale.

25 String toUpperCase() returns a string in uppercase.

26 String toUpperCase(Locale l) returns a string in uppercase using


specified locale.

27 String trim() removes beginning and ending


spaces of this string.

28 static String valueOf(int value) converts given type into string. It is an


overloaded method.

package helloworld;
import java.util.Scanner;
public class testclass {

public static void main(String[] args) {

String s1="hello string";


String s1upper=s1.toUpperCase();
System.out.println(s1upper);
}
}

Lab Tasks:

1. Write java program to produce an n times multiplication table, where n is entered by the
user.
2. Declare and initialize array of 10 elements and assign it value 10 20 ---- 100.
3. Repeat question 2 and take elements from user.
4. Write a program that allow the user to enter age of five individual where age range from
25 to 60 using a ‘for’ loop, and using another loop find how many individuals are elder
than 30.

5. Read a string and write a program to capitalize every letter of a string.

Object Oriented Programming


Department of Electrical Engineering Military College of Signals NUST

Post Lab

1. Create a pyramid in java:

*
* *
* * *
* * * *
* * * * *

2. Define a 1-D array. A company pays its salespeople on a commission basis. The salespeople
receive Rs 200 per week plus 9% of their gross sales for that week. For example, a salesperson
who grosses Rs 5000 in sales in a week receives 200 plus 9 % of 5000, or a total of Rs 650. Write
a program (using an array of counters) that determines how many of the salespersons earned
salaries in each of the following ranges.
• 200-299
• 300-399
• 400-499
• 500-599
• 600-699
• 700-799
• 800-899
• 900-999
• 1000 -over

3. Read a string and a word from the user. Write a program to find the frequency of occurrence of
a word in the string

Object Oriented Programming

You might also like