• Skip to main content
  • Skip to primary sidebar

CodeBlogMoney

Make Money using Coding and Blogging

Java

Byte Array to String in Java

June 10, 2020 by Jimmy

This article explain how to convert byte array to String.

Byte Array to String code

public class ByteArrayToString {
	
	public static void main(String[] args)
    { 
		byte[] byteArray= {67,111,100,101,32,
				           66,108,111,103,32,
				           77,111,110,101,121};
		
		//Convert byte[] to String		
	    String convertedToString = new String(byteArray);  
	    
	    System.out.println("Byte Array to String : " + convertedToString);
    }
}

Output

Byte Array to String : Code Blog Money

String to Byte Array

public class StringtoByteArray {
	
	public static void main(String[] args)
    { 
		String sampleString = "CodeBlogMoney";
		
		byte[] byteArray = sampleString.getBytes();
		
		System.out.println("Byte Array data :\n");
		
		for(byte b : byteArray) {
			System.out.print(b + " ");
		}
    }
}

Output

Byte Array data :

67 111 100 101 66 108 111 103 77 111 110 101 121 

Filed Under: Java

Iterate Java List using Loop, forEach, Iterator and more

June 9, 2020 by Jimmy

While programming array is essential to store list of fruits, list of employee, list of states and many more. Array has limitation and slow to travers through when the list of items are getting bigger and dynamically incresing.

AraryList in Java supports to store N numbers of items. After storing those items in the list, it needs iteration to find item which are available in the Array. We need to loop it one by one to fetch the required item.

Here are ways to Iterate or Loop List in Java.

1. For Loop

This is a basic for loop which we learn in Programming 101.

import java.util.ArrayList;
import java.util.List;

public class JavaLoopList {

	public static void main(String[] args) {

		List<String> actorList = new ArrayList<String>();

		actorList.add("Robert Downey, Jr.");
		actorList.add("Tom Hanks");
		actorList.add("Leonardo DiCaprio");
		actorList.add("Will Smith");
		actorList.add("Tom Cruise");
		actorList.add("Dwayne Johnson");

		for ( int i = 0; i < actorList.size(); i++ ) {
			System.out.println( "Actron Name:-> " + actorList.get(i) );
		}
	}
}

Output

--Using Foor Loop--

Actron Name:-> Robert Downey, Jr.
Actron Name:-> Tom Hanks
Actron Name:-> Leonardo DiCaprio
Actron Name:-> Will Smith
Actron Name:-> Tom Cruise
Actron Name:-> Dwayne Johnson

This code uses for loop which uses size() to get the available items in the List and going one by one to get the items from the list and print on the console.

2. Next Generation For Loop

import java.util.ArrayList;
import java.util.List;

public class NextGenerationForLoop {

	public static void main(String[] args) {

		List<String> actorList = new ArrayList<String>();

		actorList.add("Robert Downey, Jr.");
		actorList.add("Tom Hanks");
		actorList.add("Leonardo DiCaprio");
		actorList.add("Will Smith");
		actorList.add("Tom Cruise");
		actorList.add("Dwayne Johnson");

		for ( String actorName : actorList ) {
			
			System.out.println( "Actron Name:-> " + actorName );
			
		}
	}
}

Output

--Using Next Generation Foor Loop--

Actron Name:-> Robert Downey, Jr.
Actron Name:-> Tom Hanks
Actron Name:-> Leonardo DiCaprio
Actron Name:-> Will Smith
Actron Name:-> Tom Cruise
Actron Name:-> Dwayne Johnson

3. While loop: Programming 101

import java.util.ArrayList;
import java.util.List;

public class JavaWhileLoopList {

	public static void main(String[] args) {

		List<String> actorList = new ArrayList<String>();

		actorList.add("Robert Downey, Jr.");
		actorList.add("Tom Hanks");
		actorList.add("Leonardo DiCaprio");
		actorList.add("Will Smith");
		actorList.add("Tom Cruise");
		actorList.add("Dwayne Johnson");

		System.out.println("--Using While Loop--\n");

		int index = 0;
		
		while (index < actorList.size()) {
			
			System.out.println("Name:-> "+actorList.get(index));
			index++;
		}
	}
}

Output

--Using While Loop--

Name:-> Robert Downey, Jr.
Name:-> Tom Hanks
Name:-> Leonardo DiCaprio
Name:-> Will Smith
Name:-> Tom Cruise
Name:-> Dwayne Johnson

4. Iterator with While Loop

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class JavaIteratorWhileLoopList {

	public static void main(String[] args) {

		List<String> actorList = new ArrayList<String>();

		actorList.add("Robert Downey, Jr.");
		actorList.add("Tom Hanks");
		actorList.add("Leonardo DiCaprio");
		actorList.add("Will Smith");
		actorList.add("Tom Cruise");
		actorList.add("Dwayne Johnson");

		System.out.println("--Using Iterator with While Loop--\n");

		Iterator<String> actoreIterator = actorList.iterator();
		
		while (actoreIterator.hasNext()) {
			
			System.out.println("Name:-> "+actoreIterator.next());
		}
	}
}

Output

--Using Iterator with While Loop--

Name:-> Robert Downey, Jr.
Name:-> Tom Hanks
Name:-> Leonardo DiCaprio
Name:-> Will Smith
Name:-> Tom Cruise
Name:-> Dwayne Johnson

5. ListIterator with While loop

import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

public class JavaListIteratorWhileLoopList {

	public static void main(String[] args) {

		List<String> actorList = new ArrayList<String>();

		actorList.add("Robert Downey, Jr.");
		actorList.add("Tom Hanks");
		actorList.add("Leonardo DiCaprio");
		actorList.add("Will Smith");
		actorList.add("Tom Cruise");
		actorList.add("Dwayne Johnson");

		System.out.println("--Using ListIterator with While Loop--\n");

		ListIterator<String> actoreIterator = actorList.listIterator();
		
		while (actoreIterator.hasNext()) {
			
			System.out.println("Name:-> "+actoreIterator.next());
		}
	}
}

Output

--Using ListIterator with While Loop--

Name:-> Robert Downey, Jr.
Name:-> Tom Hanks
Name:-> Leonardo DiCaprio
Name:-> Will Smith
Name:-> Tom Cruise
Name:-> Dwayne Johnson

6 Iterable.forEach()

import java.util.ArrayList;
import java.util.List;

public class JavaListIteratorForEachList {

	public static void main(String[] args) {

		List<String> actorList = new ArrayList<String>();

		actorList.add("Robert Downey, Jr.");
		actorList.add("Tom Hanks");
		actorList.add("Leonardo DiCaprio");
		actorList.add("Will Smith");
		actorList.add("Tom Cruise");
		actorList.add("Dwayne Johnson");

		System.out.println("-- Using Iterable.forEach() --\n");

		actorList.forEach((actorName) -> {
            System.out.println("Actor Name:-> "+actorName);
        });
		
	}
}

Output

-- Using Iterable.forEach() --

Actor Name:-> Robert Downey, Jr.
Actor Name:-> Tom Hanks
Actor Name:-> Leonardo DiCaprio
Actor Name:-> Will Smith
Actor Name:-> Tom Cruise
Actor Name:-> Dwayne Johnson

7 Stream.forEach

import java.util.ArrayList;
import java.util.List;

public class JavaStreamForEachList {

	public static void main(String[] args) {

		List<String> actorList = new ArrayList<String>();

		actorList.add("Robert Downey, Jr.");
		actorList.add("Tom Hanks");
		actorList.add("Leonardo DiCaprio");
		actorList.add("Will Smith");
		actorList.add("Tom Cruise");
		actorList.add("Dwayne Johnson");

		System.out.println("-- Using Stream.forEach() --\n");

		actorList.stream().forEach(
				(actrorName) -> System.out.println("Name:->" + actrorName ) );
		
	}
}

Output

-- Using Stream.forEach() --

Name:->Robert Downey, Jr.
Name:->Tom Hanks
Name:->Leonardo DiCaprio
Name:->Will Smith
Name:->Tom Cruise
Name:->Dwayne Johnson

Filed Under: Java

Java get Hostname

June 8, 2020 by Jimmy

Java get Hostname

This blog helps you to get the hostname and IP address of where the program is running. It uses the InetAddress class of Java which uses the Internet Protocol address.

While development and testing most developer uses own computer or laptop to run the program. so the program will provide the hostname of the system where this code is executed.

This code uses java.net library of java to get the Hostname.

Here is the code which get hostname using Java.

package com.cbm.hostnamejava;

import java.net.InetAddress;
import java.net.UnknownHostException;

public class JavaGetHostName {
	
public static void main(String[] args) throws UnknownHostException{
		 
       InetAddress inetAddress = InetAddress.getLocalHost();
  
       String hostname = inetAddress.getHostName();
          
       System.out.println("Hostname of current host: " + hostname);
            
       System.out.println("IP address of current host: " + inetAddress);
 
    }

}

Output:

Hostname of current host: DESKTOP-TTSBKDU
IP address of current host: DESKTOP-TTSBKDU/192.168.0.110

InetAddress getLocalHost()

getLocalHost() of InetAddress return the local host It get the name from the system and assigned to InetAddress.

This method throws UnknownHostException incase if system is not able to retrieve the hostname or not able to associate with IP address.

Code with Exception Handling

import java.net.InetAddress;
import java.net.UnknownHostException;

public class JavaGetHostName {

	public static void main(String[] args) {

		try {

			InetAddress inetAddress = InetAddress.getLocalHost();

			String hostname = inetAddress.getHostName();

			System.out.println("Hostname of current host: " + hostname);

			System.out.println("IP address of current host: " + inetAddress);
			
		} catch (UnknownHostException exception) {

			System.out.println("Exception:->" + exception.getMessage());
		}

	}

}

More article to read:

String to Char Array Java

Useful tool to https://codebeautify.org/hostname-to-ip

Filed Under: Java

String to Char Array Java

June 7, 2020 by Jimmy

String to Char Array Java

This blog helps to convert Java String to a character array.

1. Logical Approach without any inbuilt functions.

Follow these steps:

  1. Create a String variable and assign a value.
  2. Use the length of the String variable to create an array of characters.
  3. Use a loop to iterate the String using an index.
  4. Assign a value at the index to a character array.
  5. Once loops complete, Characters array will be ready to use.
  6. Use a loop to print the character array.

Code:

public class StringToCharArray {
	
	 public static void main( String args[] ) 
	    { 
		    //1. Create a String variable and assign a value
	        String cbm = "CodeBlogMoney"; 
	        
	        int lengthOfString = cbm.length();
	  
	        //2.Use the length of the String variable to create an array of characters 
	        char[] arrayOfCharacters = new char[ lengthOfString ]; 
	  
	        // 3. Use a loop to iterate the String using an index.
	        for ( int i = 0; i < lengthOfString; i++ ) { 
	        	
	        	// 4 Assign a value at the index to a character array.
	        	arrayOfCharacters[i] = cbm.charAt(i); 
	        
	        } // 5. Once loops complete, Characters array will be ready to use.
	  
	        // 6. Use a loop to print the character array
	        for ( char valueofChar : arrayOfCharacters ) { 
	            
	        	System.out.println( valueofChar ); 
	        
	        } 
	    } 
}

Output of above code:

C
o
d
e
B
l
o
g
M
o
n
e
y

2. Using toCharArray() function

java.lang.String has toCharArray() which converts String to array of characters and return the new object of array.

Follow these steps

  1. Define a string object with value.
  2. Use toCharArray() to return the array of characters
  3. Print the values of the character of array.

Code

public class StringToCharArrayUsingInbuildMethod {
	
	 public static void main( String args[] ) 
	    { 
		    //1. Define a string object with value
	        String cbm = "CodeBlogMoney"; 
 
	        //2.Use toCharArray() to return the array of characters
	        char[] arrayOfCharacters = cbm.toCharArray(); 
	          
	        // 3. Print the values of the character of array.
	        for ( char valueofChar : arrayOfCharacters ) { 
	            
	        	System.out.println( valueofChar ); 
	        
	        } 
	    } 
}

Output of above code:

C
o
d
e
B
l
o
g
M
o
n
e
y

More articles to check out.

JSON Example with Data Types Including JSON Array

Few online string tools to check out.

https://codebeautify.org/string-functions

Filed Under: Java Tagged With: Array, String

Primary Sidebar

Categories

  • Blogging
  • HTML
  • Java
  • JavaScript
  • jQuery
  • JSON
  • MySql
  • Performance
  • PHP
  • Problem Solving
  • Python
  • Testing
  • XML

Copyright © 2021 · Metro Pro on Genesis Framework · WordPress · Log in