10 Java Tips – Series II

Java Tips

Java Tips – Series II

Введення : 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 {

державної статичної сили основних(Рядок[] аргументи) {

Рядок[] names = new String[] { “X”, “Y”, “Z” };

Рядок[] extended = new String[5];

extended[3] = “D”;

extended[4] = “Це”;

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

для (String str : extended){

System.out.println(str);

}

}

}

And the result will be as follows

X
Y
Z
D
Це

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, значення) method and Array.fill (arrayname, starting index, ending index, значення) method of Java Util class.

import java.util.*;

public class FillTest {

державної статичної сили основних(String args[]) {

int array[] = new int[6];

Arrays.fill(array, 100);

для (int i=0, n=array.length; я < п; я ) {

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

}

System.out.println();

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

для (int i=0, n=array.length; я< п; я ) {

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

}

}

}

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 ( десяткового [] [] ,десяткового [] []) and mprint(десяткового [] []).

public class Matrix{

public static int[][] multiply(десяткового[][] m1, десяткового[][] m2){

int m1rows = m1.length;

int m1cols = m1[0].length;

int m2rows = m2.length;

int m2cols = m2[0].length;

якщо (m1cols != m2rows){

throw new IllegalArgumentException(“matrices

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

десяткового[][] result = new int[m1rows][m2cols];

для (int i=0; я< m1rows; я ){

для (int j=0; j< m2cols; j ){

для (int k=0; k< m1cols; k ){

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

return result;

)

}

}

}

}

/** Matrix print.

*/

public static void mprint(десяткового[][] a){

int rows = a.length;

int cols = a[0].length;

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

для (int i=0; я< rows; я ){

System.out.print(“{“);

для (int j=0; j< cols; j ){

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

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

}

}

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

}

державної статичної сили основних(Рядок[] 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 {

державної статичної сили основних(String args[]) {

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

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

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

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

Object[] c = list.toArray();

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

}

}

The code sample will produce the following result

[A, Це, 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 {

державної статичної сили основних(Рядок[] аргументи) {

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

int min = (десяткового) Collections.min(Arrays.asList(numbers));

int max = (десяткового) 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 {

державної статичної сили основних(Рядок[] аргументи) {

ArrayList arrayList = new ArrayList();

arrayList.add(“A”);

arrayList.add(“Б В”);

arrayList.add(“C”);

arrayList.add(“D”);

arrayList.add(“Це”);

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, Б В, C, D, Це]

After Reverse Order: [Це, D, C, Б В, 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 {

державної статичної сили основних(String args[]) Кидає виняток {

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(Струнний повідомлення, int array[]) {

System.out.println(message

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

для (INT I = 0; я < array.length; я ) {

якщо (я != 0){

System.out.print(“, “);

}

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

}

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 {

державної статичної сили основних(String args[]) Кидає виняток {

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(Струнний повідомлення, int array[]) {

System.out.println(message

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

для (INT I = 0; я < array.length; я ) {

якщо(я != 0){

System.out.print(“, “);

}

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

}

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.

імпорт 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;

для( ; ; ) {

спробувати {

repaint();

Thread.sleep(250);

ch = str.charAt(0);

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

str = str + ch;

}

зловити(InterruptedException електронної) {}

}

}

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.

============================================= ============================================== Buy best TechAlpine Books on Amazon
============================================== ---------------------------------------------------------------- electrician ct chestnutelectric
error

Enjoy this blog? Please spread the word :)

Follow by Email
LinkedIn
LinkedIn
Share