Please disable adblock to view this page.

← Go home

Arrays snippet w/ string illustration (Java)

April 27, 2016
Published By : Pratik Kataria
Categorised in:

public class Collection {

	public static void main( String [] args){
		int [] arr, arr1;		//int arr []; is also allowed but not preferred
		
		arr = new int[5];
		
		arr1 = new int[] {10, 12, 33,43};
		
		for(int i : arr){
			System.out.println(i);
		}
		
		System.out.println("-------------------------");
		
		for(int i = 0; i < arr1.length ; i++){
			System.out.println(arr1[i]);
		}
		
		System.out.println("-------------------------");
		
		int [] [] arr3 = new int[3][];
		
		arr3[0] = new int[2];
		arr3[1] = new int[3];
		arr3[2] = new int[2];
		
		for(int i = 0; i < arr3.length ; i++){
			
			for(int j=0;j<arr3[i].length;j++){
					System.out.printf(arr3[i][j] + " "); //printf so that on each loop new line is not automatically generated
			}
			System.out.println();
		}
		
		System.out.println("-------------------------");
		
		for(String str : args){				//This is for command line arguement. The class name is not counted as arguement in case of java but in C++ it is counted
			System.out.println(str);
		}
		System.out.println("-------------------------");
		
		String str, str1;
		
		str = "Pratik";
		
		System.out.println(str);
		
		str1 = "Professional";
		
		if(str.contains("a")){
			System.out.println("The String "+str+" contains 'a' at location " + str.lastIndexOf("a"));
		}
		
		if(str.equals(str1)){
			System.out.println("Both Strings are equal \n");
			
		}
		else
			System.out.println("Both Strings are not equal. \n");
			
		
		

		
	}
	
}

Output:

Pratik
The String Pratik contains ‘a’ at location 2
Both Strings are not equal.

View Article Page
Download

Pratik Kataria is a budding programmer, web designer and developer.