java_programming_chaitu_informative_blogs
java programming important questions

Hello...guys, today I want to show you an important Java programming interview question and its answer. This question was solved by myself as well as my friend.

Now the question I am showing is what I have encountered in the interview.

So I've solved that interview question for you. so I think it may be useful for those who are attending interviews. please try to understand the logic which is provided in the program.

Below I have given you the interview question and its requirements and guidelines which are provided by the interviewer.

Write a Java Console Program to create a simple phone-book application with the given specs. While coding, strictly follows the guidelines given as much as possible.

Program Specs :

1. Create a phone book program that stores a maximum of 5 contacts.

2. Each contact should have the following details:

#Name

#Gender

#Mobile No

#E-Mail

3. When adding a contact to the program, verify that the contact has a valid name, gender, and Mobile number. E-mail is optional.

4. The program should not allow contact with a duplicate Mobile number to be added to the program. For example: if the phone book program already has a contact <name: john, Mobile No: 9911223344>, then the program should not let the user add another contact <name: David, Mobile No:9911223344>, because the Mobile number 9911223344 is already stored as john's Mobile number. When this happens, show an appropriate error message.

5. Provide an option to search contacts by Name.

6. Provide an option to add contacts into pre-defined groups like Family and Friends.

7. Provide an option to view all the contacts in alphabetical order.

Guidelines :

You should save all the (maximum of 5) contacts in an array, You should not use any collection classes to implement the program.

Write the program in Object-Oriented Style.

Optional Feature :

Implement the following feature to get more scores in the evaluation.

# When displaying contacts on-screen format them as a box as shown below :

-------------------------------------------------------------------------

| Name: David | Gender: Male |

-------------------------------------------------------------------------

| E-Mail: Not Available | Mobile No: 9944223344 |

-------------------------------------------------------------------------

# The width of the box should be computed dynamically based on the largest

Name or E-Mail available in the address book.

# Don't give a static width to the box that can adopt typical lengthy Names and E-Mails.

# Labels like Name, E-Mail, Gender, and Mobile Number are Left Aligned and Values are right-aligned in a Cell.

Guidelines :

You should not use Formatter, printf (), or any other formatting classes or methods in Java.

You should write your own logic, you can use StringBuilder to build the String in the format.

Answers :

Filename: Contact.java

package chaitu.info.blogs;

import java.util.Arrays;

import java.util.Scanner;

/*Contact class which implements Phone interface, this class contains oops concepts like inheritance,  encapsulation, singleton features*/

public class Contact implements Phone {

private static ContactData[] family = new ContactData[5];

private static ContactData[] friend = new ContactData[5];

private static ContactData[] contacts = new ContactData[5];

private static int fIndex,frIndex,cIndex =0;

private static Contact contact=null;

static Scanner scan = new Scanner(System.in);

/*private constructor which makes Contact class as a Singleton class by Creating a getContact()*/

private Contact() {

}

/*getContact() is a helper method which is used to get the object of Contact class, it always provides single instance of Contact class*/

public static Contact getContact() {

if(contact==null) {

Contact contactObj = new Contact();

contact=contactObj;

}

return contact;

}

/*addContact() is used to get the information from the user and to store*/

@Override

public void addContact() {

ContactData contactData = new ContactData();

if(cIndex<=4) {

System.out.println("Enter the Name : ");

contactData.setName(scan.next());

System.out.println("Enter the Mobile No :");

contactData.setMobile(scan.next());

System.out.println("Enter the Gender : ");

contactData.setGender(scan.next());

System.out.println("do u want to store email???");

System.out.println("yes or no...");

String status = scan.next();

if(status.equals("yes")) {

System.out.println("Enter the email : ");

contactData.setEmail(scan.next());

}

if(validateMobile(contactData.getMobile())){

if(validateGender(contactData.getGender())) {

contacts[cIndex] = contactData;

cIndex++;

System.out.println("Successfully contact added.");

} else {

System.err.println("Contact is not saved.");

PhoneBook.start();

}

} else {

System.err.println("Contact is not saved.");

PhoneBook.start();

}

} else {

System.err.println("Phonebook can't store more than 5 concats.");

PhoneBook.start();

}

System.out.println("Do you want to add contact in any of the group..");

System.out.println("YES or NO");

if(scan.next().equalsIgnoreCase("Yes")) {

addToGroup(contactData);

}

askUser();

}

/*validateGender() is used to validate gender as a Male or Female only.*/

private static boolean validateGender(String iGender) {

if(iGender.equalsIgnoreCase("male") || iGender.equalsIgnoreCase("female")) {

return true;

} else {

System.err.println("Please enter the gender either male or female...");

return false;

}

}

/*validateMobile() is used to validate mobile numbers that contains only numerics or not, fixed length of 10 characters or not, whether it's already exist or not*/

private static boolean validateMobile(String iMobile) {

String reference = "0123456789";

if(iMobile.length()==10) {

for(int i=0;i<=9;i++) {

 if(!reference.contains(iMobile.charAt(i)+"")) {

System.err.println("Mobile number must have valid numeric values from 0 to 9");

return false;

}

}

for(int i=0;i<=4;i++) {

if(contacts[i]!=null) {

if(contacts[i].getName().equals(iMobile)) {

       System.err.println("Sorry! Entered mobile number already exists.");

       return false;

}

}

}

return true;

}

else {

System.err.println("Mobile number must have 10 numeric values");

return false;

}

}

/*viewContact() is used to view the all the contacts in alphabetical order*/

@Override

public void viewContact() {

/*cIndex is next Index to store the contact, if cIndex value is equal to Zero means there are no contacts to display*/

if(cIndex!=0) {

ContactData[] reference = Arrays.copyOf(contacts, cIndex);

Arrays.sort(reference);

for(int i=0;i<reference.length;i++) {

display(reference[i]);

}

} else {

System.err.println("No contacts are there.");

}

askUser();

}

/*display() is used to get the data in encapsulation form and display it on the console*/

private static void display(ContactData data) {

String one = "| Name :    "+data.getName()+" | Gender :    "+data.getGender()+" | ";

String eemail = data.getEmail()==null ? "Not Available" : data.getEmail();

String two = "| E-Mail : "+data.getEmail()+" | Mobile No : "+data.getMobile()+" | ";

int length = one.length()>=two.length() ? one.length() : two.length();

int count = length;

System.out.println();

while(count!=0) {

System.out.print("-");

count--;

}

System.out.println();

System.out.println(one);

count = length;

while(count!=0) {

System.out.print("-");

count--;

}

System.out.println();

System.out.println(two);

count = length;

while(count!=0) {

System.out.print("-");

count--;

}

System.out.println();

}

/*searchContact() is used to search the contacts by full name or first three characters of the name*/

@Override

public void searchContact() {

System.out.println("Enter the contact name or first three characters to search...");

String input = scan.next();

/*index variable contains the index of matching contacts*/

int index = -1;

/*for loop is used to compare the given name with all the contacts*/

   for(int i=0;i<=4;i++) {

       if(contacts[i]!=null) {

String data=contacts[i].getName().length()>3 ? contacts[i].getName().substring(0,3) :                              contacts[i].getName();

if(contacts[i].getName().equalsIgnoreCase(input)||data.equalsIgnoreCase(input)) {

 index=i;

}

}

}

if(index!=-1) {

display(contacts[index]);

} else {

System.err.println("No contacts are present with the name "+input);

}

askUser();

}

/*addToGroup() is used to add the contacts in group but its not available yet*/

@Override

public void addToGroup(ContactData contact) {

System.out.println("Do you want to add contact into Family or Friends group ?");

System.out.println("Family or Friends");

String data = scan.next();

if(data.equalsIgnoreCase("Family")) {

family[fIndex]=contact;

fIndex++;

System.out.println("Successfully added to family group");

}

else if(data.equalsIgnoreCase("Friends")) {

friend[frIndex]=contact;

frIndex++;

System.out.println("Successfully added to friends group");

}

else {

System.out.println("Please enter Family or Friends");

addToGroup(contact);

}

}

/*askUser() confirms whether user wants to proceeds to next operation or not*/

private void askUser() {

System.out.println("Do you want to continue to next operation..(Add/View/Search)");

System.out.println("Please enter YES or NO");

if(scan.next().equalsIgnoreCase("YES")) {

PhoneBook.start();

}

else {

System.out.println("you have successfully terminated the process..");

System.exit(0);

}

}

/*viewGroupContacts() is used to display family and friend group contacts individually*/

public void viewGroupContacts() {

if(family[0]==null && friend[0]==null) {

System.err.println("no contacts in groups");

System.out.println();

askUser();

return;

}

for(int i=0;i<=4;i++) {

if(family[i]!=null) {

if(i==0) {

System.out.println("Family :");

}

display(family[i]);

}

}

for(int j=0;j<=4;j++) {

if(friend[j]!=null) {

if(j==0) {

System.out.println("Friends :");

}

display(friend[j]);

}

}

askUser();

}

}

Filename: ContactData.java

package chaitu.info.blogs;

/*ContactData class is used to set and get contact information by using setters and getters methods*/
public class ContactData implements Comparable<ContactData> {
private String name;
private String mobile;
private String gender;
private String email="Not Available";

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}

@Override
public int compareTo(ContactData o) {
return this.getName().compareTo(o.getName());
}
}

Filename: Phone.java

package chaitu.info.blogs;

/*Phone interface*/
  public interface Phone {

/*addToGroup() is used to add the contact in family or friends group*/
void addToGroup(ContactData contact);

/*addContact() is used to get the information from the user and to store*/
void addContact();

/*viewContact() is used to view the all the contacts in alphabetical order*/
void viewContact();

/*searchContact() is used to search the contacts by full name or first three characters of the name*/
void searchContact();
}

also, visit:

Filename: PhoneBook.java

package chaitu.info.blogs;

import java.util.Scanner;

/*PhoneBook class which contains the main method for the execution.*/
public class PhoneBook {
static Scanner scan = new Scanner(System.in);
/*calling getContact() helper method to get the instance of Contact class since Contact class is a singleton class*/
static Contact contact = Contact.getContact();

/*main() of PhoneBook class.*/
public static void main(String[] args) {
start();
}

/*start() of PhoneBook class to receive the user input for mainOptions.*/
public static void start() {
System.out.println();
System.out.println("Please select the given option to proceed...");
System.out.println("1.Add contact\t2.View contact\n3.Search\t4.View group contacts");
int mainOption = 0;
try {
mainOption = scan.nextInt();
}
catch(Exception e) {
System.err.println("Please select valid option...");
return;
}
switch(mainOption) {
case 1:
contact.addContact();
break;
case 2:
contact.viewContact();
break;
case 3:
contact.searchContact();
break;
case 4:
contact.viewGroupContacts();
break;
default:
System.err.println("Please choose only any of above options..");
start();
}
}
}

Result:

java_program_output_chaitu_informative_blogs

If you have any doubts or any suggestions related to this post please drop your comments in below comment section.