githubEdit

Java Basics for DSA

Data Type

Numeric Type Conversion

Convert between numeric types

As we have seen in CS2030S, Java is a strongly typed language, thus it will do widening type conversion automatically, but narrowing type conversion must be done explicitly.

The syntax for casting a type is to specify the target type in parentheses, followed by the variable's name or the value to be cast. For example,

System.out.println((int) 1.7);

String to Numeric Types

From String to int, we can use the parseInt() provided in the Integer class. For example,

String s = "100";
int index = Integer.parseInt(s);

Single Dimensional Array

In Java, we create a single dimensional array using the following convention

elementType[] arrayRefVar = new elementType[arraySize];

For example,

double[] myList = new double[10];

Array size and Default values

The size of array can be accessed by calling the .length field of an array object.

circle-exclamation

When an array is created, its elements are assigned the default value of 0 for the numeric primitive data types, \u0000 for char types, and false for boolean types.

Copy an array

We can use Array.copyOf() to copy an array in Java

Multidimensional Array

In Java, we create a multidimensional (two dimensions here) array using the following convention

For example,

Sometimes, we may want to create a multidimensional array with different column size between each row. This kind of arrays is called Ragged Array and its creation is as follows,

circle-exclamation

Get Dimensions

This can be done by calling the .length property twice

Read Multi-d Array

chevron-rightVariable-Length Arrayhashtag

Don't know whether it's a good practice in Java anot. But at least it's a very bad practice in C 😂

In CS2040S, we can just create the variable length array as we want. For example, if we want to create an array whose size depends on the input, we can do

Similarly, this works for a two-dimensional and multi-dimensional array. Just to remember when you create a multi-dimensional array in Java with new, you must specify the sizes for all dimensions except the last one.

circle-check

Java ArrayList

Java ArrayListarrow-up-right is a powerful implementation of variable-length array in Java!

Creation

For example, to create an Integer ArrayList, we can use the following

After creating an ArrayList, we can treat it as an array! And ArrayList has provided many many powerful and useful operations than the normal Java Array.

Basic Manipulation

1

Add element

  • The first line appends the specified element (value) to the end of the list.

  • The second line inserts the specified element (value) at the specified position (index). And the movement of other elements is all down internally!

2

Search for element

This line will return the index of the specified element (value). This is equal to searching an element in the array!

3

Remove element

This line will remove the element at the specified position (index). And again, the shifting of other elements are all done internally!

4

Print element in the ArrayList

We can simply use a for-each loop to print out all the elements in the ArrayList.

String

Some parts are borrowed from NUS CS2113's explanation on Stringarrow-up-right! It's awesome and worth to refer to!

char in Java is very similar to char in C. So, I will just skip it and talk about String only.

String can be declard as follows,

triangle-exclamation

Get length

This can be done by calling the .length() method of a String object. For example,

String message = "Welcome to Java";
System.out.println("The length of " + message + " is " + message.length()); 

// It will display "The length of Welcome to Java is 15"

Find char in String

The s.charAt(index) method can be used to retrieve a specific character in a string s.

circle-exclamation

Search within String

The indexOf method searches for a single character (or a substring) in a string and returns the index of the first occurrence. The method returns -1 if there are no occurrences.

Some other useful methods when doing search within String

  • contains: checks if one string is a sub-string of the other e.g., Snapple and app

  • startsWith: checks if one string has the other as a substring at the beginning e.g., Apple and App

  • endsWith: checks if one string has the other as a substring at the end e.g., Crab and ab

Concatenate Strings

Just to save time, we can use the + operator. As you have seen below

String message = "Welcome to Java";
System.out.println("The length of " + message + " is " + message.length()); 

// It will display "The length of Welcome to Java is 15"

To quickly display a numeric value / variable in the println statement, we can just put at least one string in the statement and put the numeric value / variable. For example,

Read a String

There are two methods to do this,

  1. .next(): read a string that ends with a whitespace

  2. .nextLine(): read an entire line of text, as well as the \n character.

chevron-rightToken-based input and Line-based inputhashtag

Token-based input: .next(), .nextByte(), .nextShort(), nextInt(), nextLong(), nextFloat(), and .nextDouble(). These methods read individual elements separated by whitespace characters rather an entire line.

Line-based input: .nextLine().

triangle-exclamation

Read a char

This is done by read the whole line and retrieve the char at 0 index. For example,

String Manipulation

The normal String in Java is immutable. So, using conventional method like loops to manipulate on String is impossible. Luckily, Java has provided a special class called StringBuilder, which makes "String" mutable.

For example, if we want to manipulate with each character in a string, which is to change them into lower case.

triangle-exclamation
circle-check

String Iteration

Given a String s / Or your input in Java, the way that Prof Halim does to iterate through it is as follows,

Access substring

The substring method returns a new string that copies letters from an existing string, starting at the given index.

If it’s invoked with two arguments, they are treated as a start and end index:

circle-check

The great use of .next()

As we have seen before, .next() is a token-based input. It stops reading when it hits a whitespace. So, if we have a line of strings and we want to read each string, we can use .next(). For example,

And if our input is

We will store T1 in si and T2 in sj.

Replace parts in String

Another useful method is replace, which finds and replaces instances of one string within another.

String formatting

Sometimes programs need to create strings that are formatted in a certain way. String.format takes a format specifier followed by a sequence of values and returns a new string formatted as specified.

The above method returns a time string in 12-hour format. The format specifier \%02d means “two digit integer padded with zeros”, so timeString(19, 5) returns the string "07:05 PM".

Parse String

Wrapper classes provide methods for parsing strings to other types e.g., Integer.parseInt converts a string to (you guessed it) an integer. The other wrapper classes provide similar methods, like Double.parseDouble and Boolean.parseBoolean.

Wrapper classes also provide toString, which returns a string representation of a value.

Last updated