Welcome to the fourth part of our Core Java series. In the last part, we discussed different conditional statements and how to iterate over a loop. If you are new, please check out the previous posts in this series.
Let’s discuss some more aspects of Java Language.
To convert a string to integer datatype, we can use parseInt
method of Integer
class. We’ll discuss class and methods later in detail.
Example -
1 2 3 4
String str = "25"; int no; no = str; // Compile time error no = Integer.parseInt(str);
The input of parseInt should be a numeric type string. We can convert a string into double or float with Double.parseDouble(str)
and Float.parseFloat
respectively.
Java provides a console class
inside io
package which provides the functionality of reading or writing onto the console. Let’s see an example -
1 2 3 4 5 6 7 8 9 10 11 12 13
import java.io.*; class ReadData { public static void main(String args[]) { String name, age; Console con = System.console(); System.out.println("Enter your name"); name = con.readLine(); System.out.println("Enter your age"); age = con.readLine(); System.out.println("Hello " + name + ". Your age is " + age); } }
Console con = System.console();
provides an object of console class which can be used to access its methods. This is how we define an object in Java.con.readLine();
takes input from console and stores it in the string variable.
Now let’s learn about arrays and string class as we need them in almost all the programs in some way or other.
An array is a collection of variables of the same datatype. Each element in the array is assigned a unique number to identify it, which is known as its index. This index starts with 0.
In Java, an array is created in two steps: first declare the array variable and second, define the array.
Declaring Array Variable -
1 2
int arr[]; int[] arr;
These statements declare an array variable that will refer to an array which is yet to define. At this point, memory is not allocated for the array.
Defining Array -
1 2
arr = new int[5]; // Integer array with length 5 int arr = new int[10];
When an array is created in Java, all array elements are initialized to their default values automatically.
1
2
3
4
5
integer value - 0
float value - 0.0
boolean value - false
character value - '\U0000'(null character)
class type value - null
In Java, each array has a length variable associated with it that returns the number of elements in the array.
1
2
int arr[] = new int[10];
System.out.print(arr.length);
Output: 10
Below are different methods to initialize an array with elements -
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
int arr[] = {
1,
2,
3
};
int arr[] = new int[] {
1,
2,
3
};
int arr[] = new int[3] {
1,
2,
3
};
int x[] = {
1,
2,
3
};
int arr[] = x;
By passing an integer value in square braces([]) we can access its elements. Example -
1
2
3
4
5
6
int arr[] = {
10,
20,
30
};
System.out.println(arr[1]); // Output will be 20
If we pass any index beyond the length of the array, it’ll throw an ArrayIndexOutOfBoundException
.
We can also iterate over the array using a for
loop.
1
2
for (int i = 0; i < array.length; i++)
System.out.println(array[i]);
There are many variants of arrays like 2-D array and 3-D array.
A double dimensional array
is a grid of rows and columns that is used to store tabular data. To access one individual element we require two indices: row index and element index.
Let’s see how to declare a 2-D array:
1
2
3
4
5
6
7
8
int arr[][];
int[] arr[];
int[][] arr;
arr = new int[4][3]; // 4 rows where each row has 3 elements
System.out.println(arr.length); // 4 (number of rows)
System.out.println(arr[2].length); // 3 (number of elements in that row)
String class objects are used to store character sequences.
1 2 3
String s = null; String s = "Java"; String s = new string("Java");
String class objects are immutable. That means they cannot be changed after initialization. When we try to change them, a new object is created.
Similar to integer arrays, we can also create an array of strings.
String arr[] = new String[3]{"c++","java","python"};
String class provides many methods to handle strings. Some of them are as follows -
length() - returns number of characters in the string.
replace(char,char) - replaces a character with another character.
trim() - removes leading and trailing spaces.
toLowerCase()/toUpperCase() - changes the case of a string to lower/upper.
charAt(int index) - returns character at a particular index.
substring(int) - returns a specified portion of the string from the given index onwards.
Equality operator(==) cannot be used to compare two string objects or any other class objects. It performs shallow comparison which means it compares whether the two reference variables hold the same reference or not. It doesn’t compare the content.
In Java, we use theequals()
method to do deep comparison of two string objects. It does case sensitive comparison. The equalIgnoreCase()
method is used to perform case insensitive comparison.
1 2 3 4 5 6 7 8 9 10
String s1 = "java"; String s2 = "java"; if (s1 == s2) // true (shallow comparison, true because refers to the same object in the string pool) if (s1.equals(s2)) // true String s3 = new String("java"); // doesn't check in pool to provide reference. It always creates a fresh object if (s1 == s3) // false if (s1.equals(s3)) // true because content is still same
String buffer objects are also used to store character sequences but they are mutable, which means that they can be altered directly. Let’s see how to create one -
1
2
3
4
StringBuffer s1 = null;
StringBuffer s2 = new StringBuffer();
StringBuffer s3 = new StringBuffer("java");
StringBuffer s4 = new StringBuffer(10); // character length as parameter
Some of the methods supported by this class -
append(String) - used to append a string at the end of existing string.
insert(int, String) - inserts a string at the specified index.
deleteCharAt(int index) - removes the character at the given index.
delete(int start, int end) - deletes a portion at the given start and end point.
reverse() - reverses the content of a string buffer object.
Note - StringBuffer objects can’t be compared using equals() method. We need to convert them into string first using toString()
method and then compare them.
That’s all for now. In our next part we’ll move on to object oriented programming in Java. Till then happy coding :)