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.

Адкрыты клас Main {

дзяржаўнай статычнай сілы асноўных(Радок[] аргументы) {

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

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

extended[3] = “Рэ”;

extended[4] = “Гэта”;

System.arraycopy(імёнаў, 0, extended, 0, names.length);

для (String str : extended){

System.out.println(вул);

}

}

}

And the result will be as follows

X
і
Z
Рэ
Гэта

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(масіў, 100);

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

System.out.println(масіў[я]);

}

System.out.println();

Arrays.fill(масіў, 3, 6, 50);

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

System.out.println(масіў[я]);

}

}

}

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; Да< m1cols; k ){

result[я][j] += m1[я][Да] * m2[Да][j];

return result;

)

}

}

}

}

/** Matrix print.

*/

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

int rows = a.length;

int cols = a[0].length;

System.out.println(“масіў[“+rows ”][“+cols ”] = {“);

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

System.out.print(“{“);

для (int j=0; j< смещ_по_столбцам; 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

масіў[2][3]={

{3, 2, 3}

{5, 9, 8}

};

масіў[3][2]={

{4, 7}

{9, 3}

{8, 1}

};

масіў[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.

імпарт java.util.ArrayList;

import java.util.Arrays;

імпарт java.util.List;

Адкрыты клас Main {

дзяржаўнай статычнай сілы асноўных(String args[]) {

String a[] = { “A”, “Гэта”, “I” };

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

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

list.addAll(Arrays.asList(сі));

аб'ект[] 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;

Адкрыты клас Main {

дзяржаўнай статычнай сілы асноўных(Радок[] аргументы) {

цэлы лік[] 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.

імпарт java.util.ArrayList;

import java.util.Collections;

Адкрыты клас Main {

дзяржаўнай статычнай сілы асноўных(Радок[] аргументы) {

ArrayList arrayList = new ArrayList();

arrayList.add(“A”);

arrayList.add(“Сі”);

arrayList.add(“C”);

arrayList.add(“Рэ”);

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, Рэ, Гэта]

After Reverse Order: [Гэта, Рэ, 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[]) throws Exception {

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

Arrays.sort(масіў);

printArray(“Sorted array”, масіў);

int index = Arrays.binarySearch(масіў, 1);

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

+ index);

int newIndex = -index – 1;

array = insertElement(масіў, 1, newIndex);

printArray(“With 1 даданыя”, масіў);

}

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(масіў[я]);

}

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[]) throws Exception {

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

Arrays.sort(масіў);

printArray(“Sorted array”, масіў);

int index = Arrays.binarySearch(масіў, 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(масіў[я]);

}

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(вул, 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