TechAlpine – The Technology world

10 Java Tips – Series II

Java Tips

Java Tips – Series II

Introduction : This is the 2nd part of Java tips series. We have tried to focus more on the hands-on coding part rather that the theoretical one. Hope this will help you learn the concepts and implement them in practical projects. It will also help you to prepare for Java based interviews. Enjoy reading.







What is collections framework in java?

A: Collection is a group of objects.  java.util package provides important types of collections. There are two fundamental types of collections they are Collection and Map. Collection types hold a group of objects, like Lists and Sets. But Map types hold group of objects as key, value pairs like HashMap and Hashtable. Collections framework is one of the most important area in Java platform.

How to extend an array after initialization? 

A: Following example shows how to extend an array after initialization by creating a new array. Here the code is basically appending the new values to an existing array. The arraycopy() method should be used carefully otherwise there may a problem of data loss in the existing array.

public class Main {

public static void main(String[] args) {

String[] names = new String[] { “X”, “Y”, “Z” };

String[] extended = new String[5];

extended[3] = “D”;

extended[4] = “E”;

System.arraycopy(names, 0, extended, 0, names.length);

for (String str : extended){

System.out.println(str);

}

}

}

And the result will be as follows

X
Y
Z
D
E

How to fill (initialize at once) an array?

A: This example will fill (initialize all the elements of the array in one short) an array by using Array.fill (arrayname, value) method and Array.fill (arrayname, starting index, ending index, value) method of Java Util class.

import java.util.*;

public class FillTest {

public static void main(String args[]) {

int array[] = new int[6];

Arrays.fill(array, 100);

for (int i=0, n=array.length; i < n; i++) {

System.out.println(array[i]);

}

System.out.println();

Arrays.fill(array, 3, 6, 50);

for (int i=0, n=array.length; i< n; i++) {

System.out.println(array[i]);

}

}

}

If you run the code then the result will be as follows.

100
100
100
100
100
100
100
100
100
50
50
50

How to multiply two matrices of different dimensions?

A: Following example shows multiplication of two rectangular matrices with the help of two user defined methods multiply ( int [] [] ,int [] []) and mprint(int [] []).

public class Matrix{

public static int[][] multiply(int[][] m1, int[][] m2){

int m1rows = m1.length;

int m1cols = m1[0].length;

int m2rows = m2.length;

int m2cols = m2[0].length;

if (m1cols != m2rows){

throw new IllegalArgumentException(“matrices

don’t match: “+ m1cols + ” != ” + m2rows);

int[][] result = new int[m1rows][m2cols];

for (int i=0; i< m1rows; i++){

for (int j=0; j< m2cols; j++){

for (int k=0; k< m1cols; k++){

result[i][j] += m1[i][k] * m2[k][j];

return result;

)

}

}

}

}

/** Matrix print.

*/

public static void mprint(int[][] a){

int rows = a.length;

int cols = a[0].length;

System.out.println(“array[“+rows+”][“+cols+”] = {“);

for (int i=0; i< rows; i++){

System.out.print(“{“);

for (int j=0; j< cols; j++){

System.out.print(” ” + a[i][j] + “,”);

System.out.println(“},”);

}

}

System.out.println(“:;”);

}

public static void main(String[] argv){

int x[][] ={

{ 3, 2, 3 },

{ 5, 9, 8 },

};

int y[][] ={

{ 4, 7 },

{ 9, 3 },

{ 8, 1 },

};

int z[][] = Matrix.multiply(x, y);

Matrix.mprint(x);

Matrix.mprint(y);

Matrix.mprint(z);

}

}

The code sample will produce the following result

array[2][3]={

{3, 2, 3}

{5, 9, 8}

};

array[3][2]={

{4, 7}

{9, 3}

{8, 1}

};

array[2][2]={

{63, 30}

{165, 70}

};







How to merge two arrays?

A: This example shows how to merge two arrays into a single array by the use of list.Addall(array1.asList(array2) method of List class and Arrays.toString () method of Array class. Be careful when assigning one array to another. Because if the references of the elements of both the arrays then there is chance of cascading effect.

import java.util.ArrayList;

import java.util.Arrays;

import java.util.List;

public class Main {

public static void main(String args[]) {

String a[] = { “A”, “E”, “I” };

String b[] = { “O”, “U” };

List list = new ArrayList(Arrays.asList(a));

list.addAll(Arrays.asList(b));

Object[] c = list.toArray();

System.out.println(Arrays.toString(c));

}

}

The code sample will produce the following result

[A, E, I, O, U]

How to search the minimum and the maximum element in an array?

A: This example shows how to search the minimum and maximum element in an array by using Collection.max () and Collection.min() methods of Collection class. Although there are some other ways also to find the max and min values from an array but this API is the most efficient one to work with arrays.

import java.util.Arrays;

import java.util.Collections;

public class Main {

public static void main(String[] args) {

Integer[] numbers = { 8, 2, 7, 1, 4, 9, 5};

int min = (int) Collections.min(Arrays.asList(numbers));

int max = (int) Collections.max(Arrays.asList(numbers));

System.out.println(“Min number: ” + min);

System.out.println(“Max number: ” + max);

}

}

The result will be as follows

Min number: 1

Max number: 9

How to reverse an arraylist?

A:  Collections API has a method called reverse (ArrayList). So this is used to reverse an array list. The following example will show you how to use the API to make the code work.

import java.util.ArrayList;

import java.util.Collections;

public class Main {

public static void main(String[] args) {

ArrayList arrayList = new ArrayList();

arrayList.add(“A”);

arrayList.add(“B”);

arrayList.add(“C”);

arrayList.add(“D”);

arrayList.add(“E”);

System.out.println(“Before Reverse Order: ” + arrayList);

Collections.reverse(arrayList);

System.out.println(“After Reverse Order: ” + arrayList);

}

}

The result of the above example would be as follows.

Before Reverse Order: [A, B, C, D, E]

After Reverse Order: [E, D, C, B, A]







How to sort an array and insert an element inside it?

A: The following example shows how to use sort () method and user defined method insertElement () to accomplish the task. The sort () method is used to sort the array from negative to positive value then the customized insertElement () method is used to add additional elements into it.

import java.util.Arrays;

public class MainClass {

public static void main(String args[]) throws Exception {

int array[] = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 };

Arrays.sort(array);

printArray(“Sorted array”, array);

int index = Arrays.binarySearch(array, 1);

System.out.println(“Didn’t find 1 @ ”

+ index);

int newIndex = -index – 1;

array = insertElement(array, 1, newIndex);

printArray(“With 1 added”, array);

}

private static void printArray(String message, int array[]) {

System.out.println(message

+ “: [length: ” + array.length + “]”);

for (int i = 0; i < array.length; i++) {

if (i != 0){

System.out.print(“, “);

}

System.out.print(array[i]);

}

System.out.println();

}

private static int[] insertElement(int original[],

int element, int index) {

int length = original.length;

int destination[] = new int[length + 1];

System.arraycopy(original, 0, destination, 0, index);

destination[index] = element;

System.arraycopy(original, index, destination, index

+ 1, length – index);

return destination;

}

}

How to sort an array and search an element inside it?

A: The following example shows how to use sort () and binarySearch () method to accomplish the task. The user defined method printArray () is used to display the output.

mport java.util.Arrays;

public class MainClass {

public static void main(String args[]) throws Exception {

int array[] = { 2, 5, -2, 6, -3, 8, 0, -7, -9, 4 };

Arrays.sort(array);

printArray(“Sorted array”, array);

int index = Arrays.binarySearch(array, 2);

System.out.println(“Found 2 @ ” + index);

}

private static void printArray(String message, int array[]) {

System.out.println(message

+ “: [length: ” + array.length + “]”);

for (int i = 0; i < array.length; i++) {

if(i != 0){

System.out.print(“, “);

}

System.out.print(array[i]);

}

System.out.println();

}

}

If you run the code then the application will show the result as given below.

Sorted array: [length: 10]

-9, -7, -3, -2, 0, 2, 4, 5, 6, 8

Found 2 @ 5

How to create a banner using Applet?

A:  The following example has used the Thread class and Graphics class to display the banner. The functionality of the thread is to give an effect of animation to the banner. To view the output the applet should be run In a browser which supports applet.

import java.awt.*;

import java.applet.*;

public class SampleBanner extends Applet

implements Runnable{

String str = “This is a simple Banner “;

Thread t ;

boolean b;

public void init() {

setBackground(Color.gray);

setForeground(Color.yellow);

}

public void start() {

t = new Thread(this);

b = false;

t.start();

}

public void run () {

char ch;

for( ; ; ) {

try {

repaint();

Thread.sleep(250);

ch = str.charAt(0);

str = str.substring(1, str.length());

str = str + ch;

}

catch(InterruptedException e) {}

}

}

public void paint(Graphics g) {

g.drawRect(1,1,300,150);

g.setColor(Color.yellow);

g.fillRect(1,1,300,150);

g.setColor(Color.red);

g.drawString(str, 1, 150);

}

}








You may be interested in Java Tips Series I also. Enjoy reading.

Please follow and like us:
0

Leave a Reply

Your email address will not be published. Required fields are marked *


6 − 3 =

============================================= ============================================== Buy TechAlpine Books on Amazon
============================================== ----------------------------------------------------------------

Enjoy this blog? Please spread the word :)

Follow by Email
Facebook
Facebook
Google+
http://techalpine.com/10-java-tips-series-ii">
LinkedIn