Java List to Comma Separated String Example

package com.pretech;
import java.util.*;
public class ListToString {
	public static void main(String[] args) {
		List<String> list = new ArrayList<String>();
		list.add("welcome");
		list.add("to");
		list.add("pretech blog");
		System.out.println(getListAsCommaSeparatedString(list));
	}
	public static String getListAsCommaSeparatedString(List stringList) {
		String result = null;
		boolean firstItem = true;
		if (stringList != null && !stringList.isEmpty()) {
			StringBuffer sb = new StringBuffer();
			for (Iterator i = stringList.iterator(); i.hasNext();) {
				if (firstItem) {
					firstItem = false;
				} else {
					sb.append(",");
				}
				sb.append(i.next().toString().trim());
			}
			result = sb.toString();
		}
		return result;
	}
}

Output



welcome,to,pretech blog


How to get OS name in Java?

System.getProperty("os.name") return the Operating System name in java.

Example

package com.pretech;
public class OSNameExample {
	public static void main(String[] args) {
		System.out.println(System.getProperty("os.name"));
	}
}

Output



Windows 7


How to generate password in java?

In Java SecureRandom class provides a cryptographically strong random number generator (RNG). Here is one simple example to generate password using SecureRandom class and applying simple rules.

Example

package com.pretech;
import java.security.SecureRandom;
public class SecureRandomExample {
	private static final int PASSWORD_LENGTH = 8;
	private static final int[][] PASSWORD_RULES = new int[][] { { '0', '9' },
			{ 'A', 'Z' }, { 'a', 'z' } };
	public static void main(String[] args) {
		try {
			System.out.println(generatePassword("pretech", PASSWORD_LENGTH,
					PASSWORD_RULES));
			System.out.println(generatePassword("pretech1", PASSWORD_LENGTH,
					PASSWORD_RULES));
			System.out.println(generatePassword("pretech2", PASSWORD_LENGTH,
					PASSWORD_RULES));
			System.out.println(generatePassword("pretech3", PASSWORD_LENGTH,
					PASSWORD_RULES));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public static String generatePassword(String seed, int len, int[][] rules)
			throws Exception {
		StringBuffer password = new StringBuffer();
		try {
			SecureRandom rnd = new SecureRandom();
			rnd.setSeed(seed.getBytes());
			int rulesCount = rules.length;
			int numPos = rnd.nextInt(len);
			for (int i = 0; i < len; i++) {
				int rulesIndex = 0;
				if (i != numPos) {
					rulesIndex = rnd.nextInt(rulesCount);
				}
				int base = rules[rulesIndex][0];
				int ch = base + rnd.nextInt(rules[rulesIndex][1] - base);
				password.append((char) ch);
			}
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return password.toString();
	}
}

Output



fQ334mua
6P17f3Eg
62142a5j
v05si1va


How to convert comma separated String to ArrayList ?

Example

package com.pretech;
import java.util.*;
public class StringtoListExample {
	public static void main(String[] args) {
		System.out.println(getCommaSeparatedStringAsList("Welcome,to,pretech,blog"));
	}
	public static List getCommaSeparatedStringAsList(String commaSeparatedString) {
		List result = new ArrayList();
		if ((commaSeparatedString != null)
				&& (commaSeparatedString.length() > 0)) {
			StringTokenizer tokenizer = new StringTokenizer(
					commaSeparatedString, ",");
			while (tokenizer.hasMoreTokens()) {
				result.add(tokenizer.nextToken().trim());
			}
		}
		return result;
	}
}

Output



[Welcome, to, pretech, blog]


How to check if a string contains only digits in java

We know Integer.parseInt(number) will throw NumberFormatException if we are passing any non digit charactors, using this here is one simple example which is checking the given string contains only digit or not.

Example

package com.pretech;
public class NumberCheck {
	
	public static void main(String[] args) {
		System.out.println(isNumber("121221"));
		System.out.println(isNumber("pretech123"));
	}
	  private static boolean isNumber(final String number) {
	        boolean bisNumber = false;
	        if (number == null) {
	            bisNumber = false;
	        }
	        try {
	            Integer.parseInt(number);
	            bisNumber = true;
	        } catch (NumberFormatException ne) {
	            bisNumber = false;
	        }
	        return bisNumber;
	    }
}

Output



true
false

How to read Excel file using java and Apache poi API ?

Apache POI

The Apache POI Project classes are very useful for generating/accessing data from MS Excel files containing text (numeric/non-numeric), lists, rows and images. The library is especially useful in combination with Java technology-based classes. The Apache POI API enables a Java developer to access Microsoft Excel data files programmatically. See more about poi

Maven Dependency

Below maven dependency required to get poi jars

 <dependency>
		<groupId>org.apache.poi</groupId>
		<artifactId>poi</artifactId>
		<version>3.7</version>
    </dependency>

Creating the HSSFWorkbook Object


HSSFWorkbook is the layout of the entire data to be accessed in the form of various objects. All kinds of text elements can be accessed via HSSFWorkbook. We can create an instance of the HSSFWorkbook object as follows.

HSSFWorkbook workbook =  new HSSFWorkbook (new FileInputStream(String filename)); 
//filename  is the name of the MS Excel file which will be accessed/read/ written.
// Constructor of HSSFWorkbook takes name of the file. 

Accessing data from HSSFWorkbook instance


Once the HSSFWorkbook instance is created as mentioned in the first step, then we are ready to access data from given excel file as follows.

HSSFSheet sheet = workbook.getSheetAt (int sheetindex); 
//sheetindex is the index of the sheet of Excel file (starts from 0). 
HSSFSheet sheet = workbook.getSheet(String sheetname); 
//sheetname is the name of the sheet of Excel file 
HSSFRow row = sheet.getRow(int rowno);
//rowno is the row number. 
Java.util.Iterator iterator = sheet.rowIterator(); 
HSSFRow row = (HSSFRow) rowIterator.next();  
HSSFSheet.rowIterator() 
//returns java.util.Iterator, which fetches all rows of the sheet to HSSFRow sequentially.  
HSSFCell cell = row.getCell(short cellno); 
HSSFRow.getCell() // returns the cell of a particular row to HSSFCell. 
String stringValue = cell.getStringCellValue();
double numericValue  = cell.getNumericCellValue(); 
//Method HSSFCell.getStringCellValue() helps us to read string data and method
//HSSFCell.getNumericCellValue helps us to read numeric data from the given cell.

Example


In this example we will see how to read excel cell using poi. Create a maven project with above poi dependency in pom.xml  file and create an excel file with below data (This file should be placed in project folder as Student.xls)


image


package com.pretech;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Iterator;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class ReadExcelExample {
	public static void main(String[] args) throws Exception {
		readExcel("Student.xls");
	}
	public static void readExcel(String filename) throws Exception {
		try {
			HSSFWorkbook wb = new HSSFWorkbook(new FileInputStream(filename));
			HSSFSheet sheet = wb.getSheetAt((int) 0);
			if (sheet != null) {
				Iterator<?> rowIterator = sheet.rowIterator();
				while (rowIterator.hasNext()) {
					HSSFRow row = (HSSFRow) rowIterator.next();
					HSSFCell cellStudentID = row.getCell(0);
					HSSFCell cellStudentName = row.getCell(1);
					try {
						String studentId = cellStudentID.getStringCellValue();
						String studentName = cellStudentName
								.getStringCellValue();
						System.out
								.println(studentId + "        " + studentName);
					} catch (NullPointerException e) {
						continue;
					}
				}
			} else {
				System.out.println("Sheet not found");
			}
		} catch (FileNotFoundException fne) {
			System.out.println("File not found");
		}
	}
}

Output



Student_name        Student_Address
Santhosh        Bangalore
Raju        Chennai
Raghav        Hydrabad
Dinesh        Pune
Suraj        Mumbai

How to test private method using PowerMock

PowerMock provides org.powermock.reflect.Whitebox class to test private methods, here one example to test private methods using PowerMock.

Main Class

package com.pretech;
public class EmployeeDetails {
	
	private int calculateSalary(int basic, int hra, int da) {
		return basic + hra + da;
	}
}

Test Class

package com.pretech;
import org.junit.Assert;
import org.junit.Test;
import org.powermock.reflect.Whitebox;
public class EmployeeDetailsTest {
	@Test
	public void testCalculateSalary() throws Exception {
		EmployeeDetails empDetails = new EmployeeDetails();
		int sum = Whitebox.<Integer> invokeMethod(empDetails,
				"calculateSalary", 1000, 500, 250);
		Assert.assertEquals(1750, sum);
	}
}

Output



image


How to Mock new instances using PowerMockito

In the previous example (Mocking Static methods) we created mock values for Static methods, in this example we will see how to mock new instances which are inside methods and there is no public method to set values.

Let us consider below EmployeeDetails class, in this example connection new instance is creating inside createConnection method, during testing we do not want to create a real Connection object for testing. PowerMockito provides PowerMockito.whenNew(..) method to set mock objects when new objects are creating inside the main class.

EmployeeDetails.java

package com.pretech;
public class EmployeeDetails {
	public boolean createConnection() {
		Connection con = new Connection();
		con.connectToDb();
		System.out.println("Connected to Employee Table");
		return true;
	}
}

Connection.java

package com.pretech;
public class Connection {
	public void connectToDb() {
		System.out.println("Creating Database connection");
	}
}

EmployeeDetailsTest.java

package com.pretech;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.legacy.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest({EmployeeDetails.class})
public class EmployeeDetailsTest {
	
	@Mock
         Connection connection;
	@Test
	public void testcreateConnection() throws Exception {
	PowerMockito.whenNew(Connection.class).withNoArguments().thenReturn(connection);
         EmployeeDetails empDetails=new EmployeeDetails();
         Assert.assertTrue(empDetails.createConnection());
	}
}


Notes :PowerMock requires below annotations inside test classes

@RunWith(PowerMockRunner.class)
@PrepareForTest({EmployeeDetails.class})

Output



image

How to Mock Static Methods using PowerMockito

PowerMockito extends Mockito functionality with several new features such as mocking static and private methods. In this example we will see how to mock static methods using PowerMockito. PowerMockito provides PowerMockito.mockStatic(..) method to create Mock object for Static methods and Mockito.when(….) we can set the method call and expected values.

Let us consider below scenario using a static method which requires mocking to test getEmployee method.

EmployeeDetails.java

public class EmployeeDetails {
	public Employee getEmployee(String empName) {
		return EmployeeProvider.getEmployee(empName);
	}
	
}

EmployeeProvider.java

package com.pretech;
public class EmployeeProvider {
	public static Employee getEmployee(String empName) {
		Employee emp = new Employee();
		return emp;
	}
}

Employee.java

public class Employee {
	private String empName;
	private String empAddress;
	//Getters and setters
}

EmployeeDetailsTest.java

import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.legacy.PowerMockRunner;
@RunWith(PowerMockRunner.class)
@PrepareForTest({EmployeeProvider.class})
public class EmployeeDetailsTest {
	@Mock
	Employee emp;
	@Test
	public void testgetEmployee() throws Exception {
	Mockito.when(emp.getEmpName()).thenReturn("Vinod");
	Mockito.when(emp.getEmpAddress()).thenReturn("Bangalore");
        PowerMockito.mockStatic(EmployeeProvider.class);
        Mockito.when(EmployeeProvider.getEmployee("Vinod")).thenReturn(emp);
        EmployeeDetails empDetails=new EmployeeDetails();
        Assert.assertEquals("Bangalore",empDetails.getEmployee("Vinod").getEmpAddress());
	}
	
}


Notes
PowerMock requires below annotations inside test classes

@RunWith(PowerMockRunner.class)
@PrepareForTest({EmployeeProvider.class})


Output



image


Dependencies used in this example.

<properties>
    <powermock.version>1.5.1</powermock.version>
</properties>
<dependencies>
    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-module-junit4-legacy</artifactId>
        <version>${powermock.version}</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-api-mockito</artifactId>
        <version>${powermock.version}</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-api-easymock</artifactId>
        <version>1.5.1</version>
    </dependency>
</dependencies>

Java Executor Simple Example

Java Executor introduced in Java 1.5 and is part of java.util.concurrent API, it is an object which executes Runnable tasks similar to calling new Thread (Runnable).start () method. But it will not create new threads each time and reusing threads which are already created. See more about Executor. In this example we will create fixed thread pool to execute Runnable tasks.
java.util.concurrent.Executors providing the implementations for Executor interface, below are the main implementation to create thread pool.
Executors.newCachedThreadPool : Creates a thread pool of unlimited size, but if threads get freed up, they are reused
Executors.newFixedThreadPool : Create a thread pool of fixed size, if pool is exhausted, tasks must wait till a thread becomes free
Executors.newSingleThreadExecutor : Creates only a single thread, tasks are executed sequentially from the queue

Example

package com.pretech;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
public class ExecutorExample {
	public static void main(String[] args) {
		Executor executor = Executors.newFixedThreadPool(2);
		executor.execute(new Thread1());
		executor.execute(new Thread2());
	}
}
class Thread1 implements Runnable {
	public void run() {
		System.out.println("Thread one executing");
	}
}
class Thread2 implements Runnable {
	public void run() {
		System.out.println("Thread two executing");
	}
}

Output



Thread one executing
Thread two executing


Reference : Java Concurrancy Framwork

Model Context Protocol (MCP) — Complete Guide for Backend Engineers

  Model Context Protocol (MCP) — Complete Guide for Backend Engineers Build Tools, Resources, and AI-Driven Services Using LangChain Moder...

Featured Posts