Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to display employee data in tabular format on console.

Java Code Example — Utility Programs

ADVERTISEMENT

Java Program to display employee data in tabular format on console.

Objective

Write a Java program to display a 2D array of Employee data in a formatted console table.

Algorithm / Approach

  1. Create a 2D String array containing IDs and Names.
  2. Use loops and print statements to draw the top border (+------------------+).
  3. Iterate through the array rows.
  4. For the name column, use String.format("%-10s", name) to left-align the string and pad it with spaces up to 10 characters.
  5. Print the vertical borders (|) around the data.
  6. Draw the bottom border.
EmpTable.java
class EmpTable
{
 public static void main(String [] ar)
 {
  String[][] emps = {
	 {"1001","Scott"},
	 {"1002","Michel"},
	 {"1003","Cruise"},
	 {"1004","Brosnan"}
	};
  
  System.out.print("+");
  for(int i=0;i<18;i++)
  System.out.print("-");
  System.out.println("+");
  String n;
  for(int j=0;j<4;j++)
  {
   System.out.print("| "+emps[j][0]);
   n=String.format("%-10s",emps[j][1]);
   System.out.println(" | "+n+"|");
  }
  
  System.out.print("+");
  for(int i=0;i<18;i++)
  System.out.print("-");
  System.out.println("+");
 }
}

Expected Output

+------------------+
| 1001 | Scott     |
| 1002 | Michel    |
| 1003 | Cruise    |
| 1004 | Brosnan   |
+------------------+

Explanation of the Program

  • Console applications don't have GUI tables, so you must use ASCII art formatting to make data readable.
  • The format specifier %-10s is the key to aligning the columns perfectly. The - forces left-alignment, and the 10 ensures that no matter how short the name is, it will consume exactly 10 spaces.

Complexity

Time Complexity O(n) - Where n is the number of employees.
Space Complexity O(1)
ADVERTISEMENT