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.
The size of an array cannot be changed after creation.
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,
In Line 1 of the code above, we must specify the first element, which is the size of the row!
Get Dimensions
This can be done by calling the .length property twice
Read Multi-d Array
Java ArrayList
Java ArrayList 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
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!
Search for element
This line will return the index of the specified element (value). This is equal to searching an element in the array!
Remove element
This line will remove the element at the specified position (index). And again, the shifting of other elements are all done internally!
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 String! 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,
In Java, String cannot be regarded as char[]. Thus using string[] is not allowed! This is different from String in C in CS1010.
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.
If your index is out of the bound, it will cause a StringIndexOutOfBoundsException.
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.,SnappleandappstartsWith: checks if one string has the other as a substring at the beginning e.g.,AppleandAppendsWith: checks if one string has the other as a substring at the end e.g.,Crabandab
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,
.next(): read a string that ends with a whitespace.nextLine(): read an entire line of text, as well as the\ncharacter.
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.
StringBuilder and String are two different types, thus in the return statement above, we need to convert StringBuilder to String.
Whenever we need to return a String from a method, we can create a StringBuilder, do the manipulation on the StringBuilder, and then return StringBuilder.toString().
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:
After getting the "useful" substring, you may want to Parse String further.
The great use of .next()
.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