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

String/Arrays in Java

This document provides instructions for Lab 03 on strings and arrays in Java. The objective is for students to understand primitive vs. reference data types, conditional statements, math functions, loops, and user input. Relevant chapters from the textbook are listed. The document explains arrays, including declaring, creating, initializing arrays. It discusses the Arrays and Math classes, and methods for strings like length(), charAt(), toLowerCase(). Exercises are provided on generating vehicle plates, an airline reservation system using a seating chart array, checking sentences for capitalization and periods, and generating random sentences using word arrays.

Uploaded by

Saif Hassan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
167 views

String/Arrays in Java

This document provides instructions for Lab 03 on strings and arrays in Java. The objective is for students to understand primitive vs. reference data types, conditional statements, math functions, loops, and user input. Relevant chapters from the textbook are listed. The document explains arrays, including declaring, creating, initializing arrays. It discusses the Arrays and Math classes, and methods for strings like length(), charAt(), toLowerCase(). Exercises are provided on generating vehicle plates, an airline reservation system using a seating chart array, checking sentences for capitalization and periods, and generating random sentences using word arrays.

Uploaded by

Saif Hassan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

Sukkur IBA University

Faculty of Computer Science


Object Oriented Programming (Fall-2019)
Lab 03 – String, Arrays in Java
Instructor: Dr. Ghulam Mujtaba / Saif Hassan Date: 4th Sep, 2019

Objective
After completing this lab, the students should be able to
- Understand the difference between primitive data types and user-
defined/reference type data types
- Understand the conditional statements
- Understand the usage of mathematic functions
- Understand the for, while and do while loops
- Learn how to take user’s input

Relevant Lecture Material


Textbook: Introduction to Java Programming, Daniel Liang
Chapters: 2, 3,4,5

Arrays
An array stores a sequence of values that are all of the same type. We want
not just to store values but also to be able to quickly access each individual
value. The length of an array is established when the array is created. After
creation, its length is fixed. Each item in an array is called an element,
and each element is accessed by its numerical index. The method that we use
to refer to individual values in an array is to number and then index them—
if we have n values, we think of them as being numbered from 0 to n−1.

Making an array in a Java program involves three distinct steps:


 Declare the array name.
 Create the array.
 Initialize the array values.

We refer to an array element by putting its index in square brackets after


the array name.
To use an array in a program, you must declare a variable to reference the
array and specify the array’s element type. Here is the syntax for declaring
an array variable:

elementType[] arrayRefVar;

The elementType can be any data type, and all elements in the array will
have the same data type.

Unlike declarations for primitive data type variables, the declaration of an


array variable does not allocate any space in memory for the array. It
creates only a storage location for the reference to an array. If a variable
does not contain a reference to an array, the value of the variable is null.
You cannot assign elements to an array unless it has already been created.
After an array variable is declared, you can create an array by using the
new operator and assign its reference to the variable with the following
syntax:
arrayRefVar = new elementType[arraySize];
Java has a shorthand notation, known as the array initializer, which
combines the declaration, creation, and initialization of an array in one
statement using the following syntax:

elementType[] arrayRefVar = {value0, value1, ..., valuek};


Arrays Class
Arrays class which is in java.util.Arrays package, is a provision by Java
that provides you a number of methods through which arrays can be manipulated.
This class also lets you perform sorting and searching operations on an
array.

Java Math Class

The Java programming language supports basic arithmetic with its arithmetic
operators: +, -, *, /, and %. The Math class provides methods and constants
for doing more advanced mathematical computation.

The Math is located in the java.lang package, and not in the java.math package.
Thus, the fully qualified class name of the Math class is java.lang.Math .

The methods in the Math class are all static, so you call them directly from
the class, like this:

Math.cos(angle);

Note: Using the static import language feature, you don't have to
write Math in front of every math function:
import static java.lang.Math.*;

This allows you to invoke the Math class methods by their simple names. For
example:

cos(angle);

Constants

The Math class includes two constants:

 Math.E, which is the base of natural logarithms, and


 Math.PI, which is the ratio of the circumference of a circle to its
diameter.

Basic Math Mehtods

The Math class includes more than 40 static methods. They can be categorized as
trigonometric methods, exponent methods, and service methods. Service methods
include the rounding, min, max, absolute, and random methods.

Trigonometric Methods
The Math class contains the following methods.

The parameter for sin, cos, and tan is an angle in radians. The return value
for asin, acos, and atan is a degree in radians in the range between -pi/2
and pi/2. One degree is equal to pi/180 in radians, 90 degrees is equal to
pi/2 in radians, and 30 degrees is equal to pi/6 in radians.

Exponent Methods
There are five methods related to exponents in the Math class.
The Rounding Methods
The Math class contains five rounding methods

The Service Methods

The min, max, and abs Methods


The min and max methods return the minimum and maximum numbers of two numbers
(int, long, float, or double). For example, max(4.4, 5.0) returns 5.0, and
min(3, 2) returns 2.

The abs method returns the absolute value of the number (int, long, float,
or double).

This method generates a random double value greater than or equal to 0.0 and
less than 1.0 (0 <= Math.random() < 1.0). You can use it to write a simple
expression to generate random numbers in any range.

Java String Class


The char type represents only one character. To represent a string of
characters, use the data type called String. For example, the following code
declares message to be a string with the value "Welcome to Java".
String message = "Welcome to Java";
String is a predefined class in the Java library, just like the classes
System and Scanner. The String type is not a primitive type. It is known as
a reference type. Any Java class can be used as a reference type for a
variable. The variable declared by a reference type is known as a reference
variable that references an object. Here, message is a reference variable
that references a string object with contents Welcome to Java.
The java.lang.String class provides a lot of methods to work on string. By
the help of these methods, we can perform operations on string such as
trimming, concatenating, converting, comparing, replacing strings etc.

Getting String Length


You can use the length() method to return the number of characters in a
string. For example, the following code
String message = "Welcome to Java";
System.out.println("The length of " + message + " is "+ message.length());

Getting Characters from a String


The s.charAt(index) method can be used to retrieve a specific character in
a string s, where the index is between 0 and s.length()–1. For example,
message.charAt(0) returns the character W, as shown in figure. Note that the
index for the first character in the string is 0.

Converting Strings
The toLowerCase() method returns a new string with all lowercase letters and
the toUpperCase() method returns a new string with all uppercase letters.
For example,
"Welcome".toLowerCase() returns a new string welcome.
"Welcome".toUpperCase() returns a new string WELCOME.
The trim() method returns a new string by eliminating whitespace characters
from both ends of the string. The characters ' ', \t, \f, \r, or \n are known
as whitespace characters.

The Date Class


Java provides a system-independent encapsulation of date and time in the
java.util.Date class.
Exercises

Task1 (Generate vehicle plate numbers)


Assume a vehicle plate number consists of three uppercase letters followed
by four digits. Write a program to generate a plate number.

Task2 (Airline Reservations System)


A small airline has just purchased a computer for its new automated
reservations system. You’ve been asked to develop the new system. You’re to
write an application to assign seats on each flight of the airline’s only
plane (capacity: 10 seats).

Your application should display the following alternatives: Please type 1


for First Class and Please type 2 for Economy. If the user types 1, your
application should assign a seat in the firstclass section (seats 1–5). If
the user types 2, your application should assign a seat in the economy
section (seats 6–10).

Your application should then display a boarding pass indicating the person’s
seat number and whether it’s in the first-class or economy section of the
plane. Use a one-dimensional array of primitive type boolean to represent
the seating chart of the plane. Initialize all the elements of the array to
false to indicate that all the seats are empty. As each seat is assigned,
set the corresponding element of the array to true to indicate that the seat
is no longer available.

Your application should never assign a seat that has already been assigned.
When the economy section is full, your application should ask the person if
it’s acceptable to be placed in the first-class section (and vice versa). If
yes, make the appropriate seat assignment. If no, display the message "Next
flight leaves in 3 hours."

Task3 (Beautifying the sentences)


Write an application that takes a sentence from user and checks if the
sentence stars from a capital letter and ends with a full stop. If it doesn’t,
the program should add it.

Task4 (Random Sentences)


Write an application that uses random-number generation to create sentences.
Use four arrays of strings called article, noun, verb and preposition. Create
a sentence by selecting a word at random from each array in the following
order: article, noun, verb, preposition, article and noun. As each word is
picked, concatenate it to the previous words in the sentence.
The words should be separated by spaces. When the final sentence is output,
it should start with a capital letter and end with a period. The application
should generate and display 20 sentences.

The article array should contain the articles "the", "a", "one", "some" and
"any"; the noun array should contain the nouns "boy", "girl", "dog", "town"
and "car"; the verb array should contain the verbs "drove", "jumped", "ran",
"walked" and "skipped"; the preposition array should contain the prepositions
"to", "from", "over", "under" and "on".

Task5 (Undo/Redo Operations)


Write a program to achieve Undo/Redo like operations. Ask user any input
word by word let's say: "This is my program.” store in an array word by word.
a) Ask user to Undo/Redo (1 for undo, 2 for redo).
b) If user presses 1, then last word should be removed from array and
output: This is my.
c) If user presses 2, then last word removed must be added in last and
output: "This is my program".

You might also like