Skip to content

Introduction to java

Shreyansh Murarka edited this page Nov 30, 2017 · 1 revision

This document provides some basic methods that are useful when doing competitive programming in Java.

Introduction

In Java, everything needs to be inside a class. Inside a class you need to define a main method as shown

class Demo{
    public static void main(String args[]){
        System.out.println("Hello World");
    }
}

This is a simple Hello World program. Notice that the main method is declared as public static and has a return type void. It also takes a string array as it's input parmeter which is used for passing command-line arguments.

Strings

In Java, String is a predifined class which has a lot of functions inbuilt which makes manipulation of Strings very simple. The following code illustrates basic usage of String in Java. For a complete list of available functions click here.

class StringDemo{
    public static void main (String[] args){
        String s= "IECSECodeWinter";
        // or String s= new String ("IECSECodeWinter");
 
        // Returns the number of characters in the String.
        System.out.println("String length = " + s.length());
 
        // Returns the character at ith index.
        System.out.println("Character at 3rd position = " + s.charAt(3));
 
        // Return the substring from the 3rd index character
        // to end of string
        System.out.println("Substring " + s.substring(3));
 
        // Returns the substring from 2 to 4 index.
        System.out.println("Substring  = " + s.substring(2,5));
 
        // Concatenates string2 to the end of string1.
        String s1 = "IECSE";
        String s2 = "CodeWinter";
        System.out.println("Concatenated string  = " + s1.concat(s2));
        // or System.out.println("Concatenated string = " + s1+s2);
 
        // Returns the index within the string
        // of the first occurrence of the specified string.
        String s4 = "Learn Share Learn";
        System.out.println("Index of Share " + s4.indexOf("Share"));
 
        // Returns the index within the string of the
        // first occurrence of the specified string,
        // starting at the specified index.
        System.out.println("Index of a  = " + s4.indexOf('a',3));
 
        // Checking equality of Strings
        Boolean out = "Code".equals("code");
        System.out.println("Checking Equality  " + out);
        out = "Code".equals("Code");
        System.out.println("Checking Equality  " + out);
 
        out = "Code".equalsIgnoreCase("cODe ");
        System.out.println("Checking Equality" + out);
 
        int out1 = s1.compareTo(s2);
        System.out.println("If s1 = s2" + out);
 
        // Converting cases
        String word1 = "RandomStuffHerE";
        System.out.println("Changing to lower Case " + word1.toLowerCase());
 
        // Converting cases
        String word2 = "Iecse";
        System.out.println("Changing to UPPER Case " + word1.toUpperCase());
 
        // Trimming the word
        String word4 = " Learn Share Learn ";
        System.out.println("Trim the word " + word4.trim());
 
        // Replacing characters
        String str1 = "IECSECodzWintzr";
        System.out.println("Original String " + str1);
        String str2 = str1.replace('z' ,'e') ;
        //Does not change value in str1
        System.out.println("Replaced z with e -> " + str2);
    } 
}

While the String class is good and provides a lot of funtionalities, it's one key drawback is that it's implementation is such that it is immutable. So Java provides 2 additional classes, StringBuffer and StringBuilder to overcome this difficulty and provides a lot of other functions as well. Also read this and this.

ArrayList

ArrayList in Java this is a part of the collections framework and is present in the util package, i.e., to use ArrayList you will need to add import java.util.* or import java.util.ArrayList in the beginning of your code to use it. ArrayList in Java is very similar to Vector in C++. It provides you with a sort of array which does dynamically increases it's size when needed while preserving the random-access feature of arrays. However, we cannot use ArrayList to store primitive datatypes. To get around this drawback, we use the Wrapper classes of these primitive datatypes instead. Look at the following code demonstrating the use of ArrayList.

import java.util.*;
class ArrayListDemo{
    public static void main(String[] args){
        // size of ArrayList
        int n = 5;
 
        //declaring ArrayList with initial size n
        ArrayList<Integer> arrli = new ArrayList<Integer>(n);

        //also can declare like this
        //ArrayList<Integer> arrli = new ArrayList<Integer>();
        //This sets the initial size as 10.
 
        // Appending the new element at the end of the list
        for (int i=1; i<=n; i++)
            arrli.add(i);
 
        // Printing elements
        System.out.println(arrli);
 
        // Remove element at index 3
        arrli.remove(3);
 
        // Displaying ArrayList after deletion
        System.out.println(arrli);
 
        // Printing elements one by one
        for (int i=0; i<arrli.size(); i++)
            System.out.print(arrli.get(i)+" ");
    }
}

Read this for a detailed description of constructors and methods available.

Miscellaneous

Arrays

Arrays is a pre-defined class in Java present in the util package. There are a lot of methods which allow us to quickly manipulate the array. You can perform binary search, sort the array and a lot of other things in just a single line of code. Consider an int arr[]. If we wanted to sort it, we would just have to do Arrays.sort(a);. This would sort a in ascending order. Similarly it has a lot of other methods.

Math

Another useful class is the Math class that is present in Java. It has pre-defined functions to do almost all trivial mathematical operations like log, sin, cos, tan, abs, power, round, ceil, floor etc. If we wanted to find the maximum of two numbers a and b and store it in c, we would just do int c=Math.max(a,b);.

Further Read

Clone this wiki locally