Welcome to the fourth part of our Core Java series. In the last part, we discussed about different Conditional Statements and how to iterate over a loop. If you are new, please checkout the previous parts. Let’s discuss some more aspects of Java Language.

Conversion from string to numeric data

To convert a string to integer datatype, we can use parseInt method of Integer class. Class and methods we’ll discuss later in detail.

Example -

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, float also with Double.parseDouble(str) and Float.parseFloat respectively.

How to read data from console

Java provide a console class inside io package which provides the functionality of reading or writing onto console. Let’s see an example -

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 store 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.

Arrays

An array is a collection of variables of same datatype. Each element in the array is assigned a unique number to identify which is known as 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.

  1. Declaring Array Variable -
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.

  1. Defining Array -
arr = new int[5]; 		// Integer array with length 5
int arr = new int[10];

In Java when an array is created, all array elements are initialized to their default values automatically.

integer value - 0
flaot 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 number of elements in the array.

int arr[] = new int[10];
System.out.print(arr.length);

Output: 10

Array initialization and Accessing Array elements

Below are different methods to initialize an array with elements -

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 -

int arr[] = {10,20,30};
System.out.println(arr[1]);				// Output will be 20

If we pass any index beyond the length of array, it’ll throw an ArrayIndexOutOfBoundException.

We can also iterate over the array using a for loop.

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 dimentional 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:

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

String class objects are used to store characters sequences.

String s = null;
String s = "Java";
String s = new String("Java");

String class objects are immutable. That means they cannot be changed after initialization. It creates a new object when we try to change it.

Similarly to integer arrays, we can also create 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 -

  1. length() - returns number of characters in the string.
  2. replace(char,char) - replaces a character with another character.
  3. trim() - removes leading and trailing spaces.
  4. toLowerCase()/toUpperCase() - use to change the cases of a string to lower/upper.
  5. charAt(int index) - returns character at a particular index.
  6. substring(int) - returns a specified portion of the string from the given index onwards.

String Comparison

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 holds the same reference or not. It doesn’t compares the content.

In Java, we use equals() method to do deep comparison of two string objects. It does case sensitive comparison. equalIgnoreCase() method is used to perform case insensitive comparison.

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

StringBuffer Class

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 -

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 -

  1. append(String) - used to append a string at the end of existing string.
  2. insert(int, String) - inserts a string at the specified index.
  3. deleteCharAt(int index) - removes the charater at the given index.
  4. delete(int start, int end) - to delete a portion at the given start and end point.
  5. 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 them 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 :)