Core Java 8 and Development Tools - Labbook-V1
Core Java 8 and Development Tools - Labbook-V1
Table of Contents
Capgemini Internal
CORE JAVA 8 AND DEVELOPMENT
TOOLS LAB BOOK
Capgemini Internal
CORE JAVA 8 AND DEVELOPMENT
TOOLS LAB BOOK
Getting Started
Overview
This lab book is a guided tour for learning Core Java version 8 and development tools. It
comprises of assignments to be done. Refer the demos and work out the assignments
given by referring the case studies which will expose you to work with Java applications.
Here is what is expected on your machine in order to work with lab assignment.
Minimum System Requirements
Intel Pentium 90 or higher (P166 recommended)
Microsoft Windows 7 or higher.
Memory: (1GB or more recommended)
Internet Explorer 9.0 or higher or Google Chrome 43 or higher
Connectivity to Oracle database
Instructions
For all Naming conventions, refer Appendix A. All lab assignments should adhere
to naming conventions.
Create a directory by your name in drive <drive>. In this directory, create a
subdirectory java_assignments. For each lab exercise create a directory as lab
<lab number>.
https://docs.oracle.com/javase/8/docs/
Java, The Complete Reference; by Herbert Schildt
Thinking in Java; by Bruce Eckel
Beginning Java 8 Fundamentals by KishoriSharan
Capgemini Internal
CORE JAVA 8 AND DEVELOPMENT
TOOLS LAB BOOK
Capgemini Internal
CORE JAVA 8 LAB BOOK
Time 45 minutes
Capgemini Internal
CORE JAVA 8 LAB BOOK
Alternatively follow the following steps for setting the environment variables
Alternate approach:
Step 1: Right click My Computers, and select PropertiesEnvironment
Variables.
Capgemini Internal
CORE JAVA 8 LAB BOOK
Capgemini Internal
CORE JAVA 8 LAB BOOK
Step 5: Set CLASSPATH to your working directory in the User Variables tab.
Capgemini Internal
CORE JAVA 8 LAB BOOK
Capgemini Internal
CORE JAVA 8 LAB BOOK
Capgemini Internal
CORE JAVA 8 LAB BOOK
Capgemini Internal
CORE JAVA 8 LAB BOOK
Capgemini Internal
CORE JAVA 8 LAB BOOK
Step 7: Providename and other details for the class, and click Finish.
This will open MyClass.java in the editor, with ready skeleton for the class, default
constructor, main() method, and necessary javadoc comments.
To run this class, select Run from toolbar, or select Run As Java application.
Alternatively, you can select Run..and you will be guided through a wizard, for the
selection of class containing main() method.
Console window will show the output.
Capgemini Internal
CORE JAVA 8 LAB BOOK
Capgemini Internal
CORE JAVA 8 LAB BOOK
Step 7: Open the Javadoc view from Window Show View Javadoc.
Note: Henceforth whenever you select any class or method in Editor Window, it Javadoc
view will display the reference documentation.
Capgemini Internal
CORE JAVA 8 LAB BOOK
If you want to open the Java documentation for specified resource as html page, right
click in the Javadoc view Open Attached Javadoc.
Capgemini Internal
CORE JAVA 8 LAB BOOK
2.1 Write a java program to print person details in the format as shown below:
Person Details:
____________
2.2: Write a program to accept a number from user as a command line argument and check
whether the given number is positive or negative number.
2.3: Refer the class diagram given below and createa personclass.
Capgemini Internal
CORE JAVA 8 LAB BOOK
Also Create “PersonMain.java” program and write code for following operations:
a) Create an object of Person class and specify person details through constructor.
b) Display the details in the format given in Lab assignment 2.1
2.4: Modify Lab assignment 2.3 to accept phone number of a person. Create a newmethod to
implement the same and also define method for displaying persondetails.
2.5: Modify the above program, to accept only ‘M’ or ‘F’ as gender field values. Use Enumeration
for implementing the same.
Capgemini Internal
CORE JAVA 8 LAB BOOK
3.1: Create a method which can perform a particular String operation based on the user’s choice.
The method should accept the String object and the user’s choice and return the output of the
operation.
Options are
Add the String to itself
Replace odd positions with #
Remove duplicate characters in the String
Change odd characters to upper case
3.2: Create a method that accepts a String and checks if it is a positive string. A string is
considered a positive string, if on moving from left to right each character in the String comes
after the previous characters in the Alphabetical order.For Example: ANT is a positive String
(Since T comes after N and N comes after A). The method should return true if the entered string
is positive.
3.3: Create a method to accept date and print the duration in days, months and years with
regards to current system date.
3.4: Revise exercise 3.3 to accept two LocalDates and print the duration between dates in days,
months and years.
3.5: Create a method to accept product purchase date and warrantee period (in terms of months
and years). Print the date on which warrantee of product expires.
3.6: Create a method which accept zone id and print the current date and time with respect to
given zone. (Hint: Few zones to test your code. America/New_York, Europe/London, Asia/Tokyo,
US/Pacific, Africa/Cairo, Australia/Sydney etc.)
Capgemini Internal
CORE JAVA 8 LAB BOOK
Capgemini Internal
CORE JAVA 8 LAB BOOK
4.1: Refer the case study 1in Page No: 5 and create Account Class as shown below in class
diagram. Ensure minimum balance of INR 500 in a bank account is available.
a) Create Account for smith with initial balance as INR 2000 and for Kathy with initial
balance as 3000.(accNum should be auto generated).
b) Deposit 2000 INR to smith account.
c) Withdraw 2000 INR from Kathy account.
d) Display updated balances in both the account.
e) Generate toString() method.
Capgemini Internal
CORE JAVA 8 LAB BOOK
Inherit two classes Savings Account and Current Account from account class. Implement
the following in the respective classes.
a) Savings Account
a. Add a variable called minimum Balance and assign final modifier.
b. Override method called withdraw (This method should check for minimum
balance and allow withdraw to happen)
b) Current Account
a. Add a variable called overdraft Limit
b. Overridemethod called withdraw (checks whether overdraft limit is reached
and returns a boolean value accordingly)
Capgemini Internal
CORE JAVA 8 LAB BOOK
Goals At the end of this lab session, you will be able to:
Use of abstract classes and interfaces
Time 90 minutes
5.1: Refer the case study 2 in page no: 5 and create an application for that requirement by
creating packages and classes as given below:
a) com.cg.eis.bean
In this package, create “Employee” class with different attributes such as id,
name, salary, designation, insuranceScheme.
b) com.cg.eis.service
This package will contain code for services offered in Employee Insurance
System. The service class will have one EmployeeService Interface and its
corresponding implementation class.
c) com.cg.eis.pl
This package will contain code for getting input from user, produce expected
output to the user and invoke services offered by the system.
5.2: Use overrides annotation for the overridden methods available in a derived class of an
interface of all the assignments.
Capgemini Internal
CORE JAVA 8 LAB BOOK
5.3: Refer the problem statement 4.1. Modify account class as abstract class and declare
withdraw method.
Capgemini Internal
CORE JAVA 8 LAB BOOK
Goals At the end of this lab session, you will be able to:
Create and use application specific exceptions
Time 120 minutes
6.1: Modify the Lab assignment 2.3 to validate the full name of an employee. Create and throw a
user defined exception if firstName and lastName is blank.
6.2: Validate the age of a person in Lab assignment 4.2 and display proper message by using
user defined exception. Age of a person should be above 15.
6.3: Modify the Lab assignment 5.1 to handle exceptions. Create an Exception class named as
“EmployeeException”(User defined Exception) in a package named as “com.cg.eis.exception”
and throw an exception if salary of an employee is below than 3000. Use Exception Handling
mechanism to handle exception properly.
Capgemini Internal
CORE JAVA 8 LAB BOOK
7.1: Write a program to store product names in a string array and sort strings available in an
array.
7.2: Modify the above program to store product names in anArrayList, sort strings available in an
arrayList and display the names using for-each loop.
7.3: Modify the lab assignment 5.1 to accept multiple employee details and store all employee
objects in a HashMap. The functionalities need to be implemented are:
Capgemini Internal
CORE JAVA 8 LAB BOOK
Capgemini Internal
CORE JAVA 8 LAB BOOK
Lab 8: Files IO
8.1: Write a program to read content from file, reverse the content and write the reversed content
to the file. (Use Reader and Writer APIs).
8.2: Create a file named as “numbers.txt” which should contain numbers from 0 to 10 delimited by
comma. Write a program to read data from numbers.txt using Scanner class API and display only
even numbers in the console.
8.3: Enhance the lab assignment 6.3 by adding functionality in service class to write employee
objects into a File. Also read employee details from file and display the same in console. Analyze
the output of the program.
Capgemini Internal
CORE JAVA 8 LAB BOOK
Capgemini Internal
CORE JAVA 8 LAB BOOK
Capgemini Internal
CORE JAVA 8 LAB BOOK
Capgemini Internal
CORE JAVA 8 LAB BOOK
A dialog box opens, where you need to specify the following details:
o The Junit version that is used
o The package name and the class name
o The class under test
o You can also specify the method stubs that you would like to create
Capgemini Internal
CORE JAVA 8 LAB BOOK
importorg.junit.*;
import org.junit.Test;
import static org.junit.Assert.*;
@Test (expected=IllegalArgumentException.class)
public void testNullsInName()
Capgemini Internal
CORE JAVA 8 LAB BOOK
{
System.out.println("from TestPerson2 testing exceptions");
Person per1 = new Person(null,null);
}
}
Example 2: TestPerson2.java
Capgemini Internal
CORE JAVA 8 LAB BOOK
Consider the following Java program. Write tests for testing various methods in the class
Solution:
Step 1: Write the following Java Program Date.java.
class Date
{
intintDay, intMonth, intYear;
// Constructor
Date(int intDay, int intMonth, int intYear) {
this.intDay = intDay;
this.intMonth = intMonth;
this.intYear = intYear;
}
// setter and getter methods
voidsetDay(int intDay)
{
this.intDay = intDay;
}
intgetDay( )
{
return this.intDay;
}
voidsetMonth(int intMonth)
{
this.intMonth = intMonth;
}
intgetMonth( )
{
return this.intMonth;
}
voidsetYear(int intYear)
{
this.intYear=intYear;
}
intgetYear( )
{
return this.intYear;
Capgemini Internal
CORE JAVA 8 LAB BOOK
}
public String toString() //converts date obj to string.
{
return “Date is “+intDay+”/”+intMonth+”/”+intYear;
}
} // Date class
Example 3: Date.java
Step 2: Write test class for testing all the methods of the above program and run it using
the eclipse IDE.
9.2.1: Consider the Person class created in lab assignment 2.3. This class has some
members and corresponding setter and getter methods. Write test case to check the
functionality of getter methods and displaydetails method.
9.2.2: Consider the lab assignment 6.3 from Exception Handling Lab. Create a new class
ExceptionCheck.javawhich handles an exception. Write a test case to verify if the
exception is being handled correctly.
Capgemini Internal
CORE JAVA 8 LAB BOOK
Capgemini Internal
CORE JAVA 8 LAB BOOK
Capgemini Internal
CORE JAVA 8 LAB BOOK
Goals At the end of this lab session, you will be able to:
Develop an complete Java application in layered architecture
Time 300 minutes
11.1: Develop a Mobile Purchase system for a Mobile Sales shop. This application is a part of the
system. Consider customer is doing full payment by cash, so payment details are not in the scope
of our system.Assume mobile details are available in the table (TableName: mobiles). Each
mobile detail have unique id and many quantity is available for each mobile. In this
system,administratorshould be able to do the following process:
a) Insert the customer and purchase details into database
Before inserting into database, do check that the quantity of the mobile should
be greater than 0, else display error message.
b) Update the mobile quantity in mobiles table, once mobile is purchased by a customer.
c) View details of all mobiles available in the shop.
d) Delete a mobile details based on mobile id.
e) Search mobiles based on price range.
f) Write a test case for insert and search mobile service functionalities.
When a customer purchased a mobile, the customer and purchase details have to be inserted to
the database through system. Perform the following validations while accepting customer details:
Customer name: Valid value should contain maximum 20 alphabets. Out of 20
Characters, first character should be in UPPERCASE.
MailId: should be valid mail id.
Phone number: Valid value should contain 10 digits exactly.
MobileId: Valid value should contain only 4 digits and it should be one of the mobileid
available in mobiles table.
PurchaseId: Generate automatically using sequence.
Purchasedate: Should be the current system date.
Capgemini Internal
CORE JAVA 8 LAB BOOK
Note:
1. Use layered architecture while implementing application
2. Handle all exceptions as a user defined exception.
3. Use Datasource for connecting to the database.
4. Read database details from properties file.
5. Use RegEx for performing validations.
6. Adhere to the coding standards and follow best practices.
7. Application should provide the menu options for the above requirements.
CREATE TABLE mobiles (mobileid NUMBER PRIMARY KEY, name VARCHAR2 (20), price
NUMBER(10,2),quantity VARCHAR2(20));
Capgemini Internal
CORE JAVA 8 LAB BOOK
Capgemini Internal
CORE JAVA 8 LAB BOOK
Solution:
Step 1:Create a directory structure as follows: c:\demo\com\sample
Step 2:Create the file c:\demo\com\sample\Log4jDemo.java.
packagecom.sample;
import org.apache.log4j.Logger;
log4j.rootLogger=ERROR, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=[%5p] %d{mm:ss}
(%F:%M:%L)%n%m%n%n
Example 5: Sample code
Capgemini Internal
CORE JAVA 8 LAB BOOK
log4j.rootLogger=ALL, stdout
or
log4j.rootLogger=DEBUG, stdout
Capgemini Internal
CORE JAVA 8 LAB BOOK
log4j.rootLogger=FATAL, stdout
Solution:
Step 1: Create one more directory bean under sample
c:\demo\com\sample\bean.
Step 2: Create the file c:\demo\com\sample\bean\Message.java.
packagecom.sample.bean;
import org.apache.log4j.Logger;
packagecom.sample;
importcom.sample.bean.Message;
import org.apache.log4j.Logger;
Capgemini Internal
CORE JAVA 8 LAB BOOK
log4j.rootLogger=DEBUG, stdout
# Categories
log4j.category.com.sample=FATAL
#log4j.category.com.sample.bean=INFO
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%c{1}] %M - %m%n
Capgemini Internal
CORE JAVA 8 LAB BOOK
log4j.category.com.sample.bean=INFO
INFO messages in category com.sample.bean are NOT logged. This is because of line
"log4j.appender.stdout.Threshold=WARN"
This appender will not log any messages with priority lower than WARN even if the
category's priority is set lower (INFO).
#log4j.category.com.sample=FATAL
#log4j.category.com.sample.bean=INFO
Step 11: Comment out the following lines in the log4j.properties file:
#log4j.appender.stdout.Threshold=WARN
Capgemini Internal
CORE JAVA 8 LAB BOOK
#log4j.category.com.sample=FATAL
#log4j.category.com.sample.bean=INFO
Solution:
Step 1: Create a directory structure as follows: c:\demo\com\sample
Step 2: Create the file c:\demo\com\sample\Log4jDemo2.java.
packagecom.sample;
import org.apache.log4j.Logger;
Capgemini Internal
CORE JAVA 8 LAB BOOK
log4j.rootLogger=ERROR, A2
########## Appender A1
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=[%5p] %d{mm:ss}
(%F:%M:%L)%n%m%n%n
########## Appender A2
log4j.appender.A2=org.apache.log4j.FileAppender
log4j.appender.A2.File=c:/demo/app_a2.log
log4j.appender.A2.Append=false
log4j.appender.A2.layout=org.apache.log4j.PatternLayout
log4j.appender.A2.layout.ConversionPattern=[%5p] %d{mm:ss}
(%F:%M:%L)%n%m%n%n
########## Appender A3
log4j.appender.A3=org.apache.log4j.RollingFileAppender
log4j.appender.A3.File=c:/demo/app_a3.log
# Set the maximum log file size (use KB, MB or GB)
log4j.appender.A3.MaxFileSize=3000KB
# Set the number of log files (0 means no backup files at all)
log4j.appender.A3.MaxBackupIndex=5
# Append to the end of the file or overwrites the file at start.
log4j.appender.A3.Append=false
log4j.appender.A3.layout=org.apache.log4j.PatternLayout
log4j.appender.A3.layout.ConversionPattern=[%5p] %d{mm:ss}
(%F:%M:%L)%n%m%n%n
########## Appender A4
log4j.appender.A4=org.apache.log4j.DailyRollingFileAppender
log4j.appender.A4.File=c:/demo/app_a4.log
# Roll the log file at a certain time
log4j.appender.A4.DatePattern='.'yyyy-MM-dd-HH-mm
# Append to the end of the file or overwrites the file at start.
log4j.appender.A4.Append=false
log4j.appender.A4.layout=org.apache.log4j.PatternLayout
log4j.appender.A4.layout.ConversionPattern=[%5p] %d{mm:ss}
(%F:%M:%L)%n%m%n%n
Capgemini Internal
CORE JAVA 8 LAB BOOK
The maximum number of backup log files is set to MaxBackupIndex=5, which means
app_a3.log.5 is the last file created.
log4j.rootLogger=ERROR, A4
<<TO DO>>
12.3.1: Assign a layout to an appender in the log4j.properties configuration file and see
the results.
12.3.2:Define the appenders in log4j.properties and use it to get the desired result.
Solution:
Capgemini Internal
CORE JAVA 8 LAB BOOK
If you rename log4j.properties file to something else (for example: test.properties), you
must add the following line to your Java runtime command:
-Dlog4j.configuration=test.properties
<<TO DO>>
12.5 Refer the Mobile Purchase layered application from lab 12.1. Configure the logger for
following functionalities:
12.5.1: Log details of customer and mobile when mobile is purchased successfully.
12.5.2: Log message when the mobile deleted.
12.5.3: Log search criteria details upon each search request from user.
12.5.3: Log all error messages/exceptions
Capgemini Internal
CORE JAVA 8 LAB BOOK
Goals At the end of this lab session, you will be able to:
To process Multithreading program with Thread Priority.
Time 60 minutes
13.2: Write a thread program to display timer where timer will get refresh after every 10seconds.(
Use Runnable implementation )
Capgemini Internal
CORE JAVA 8 LAB BOOK
Capgemini Internal
CORE JAVA 8 LAB BOOK
Goals At the end of this lab session, you will be able to:
Work with lambda expressions and stream API
Time 180 minutes
14.1: Write a lambda expression which accepts x and y numbers and return x y.
14.2: Write a method that uses lambda expression to format a given string, where a space is
inserted between each character of string. For ex., if input is “CG”, then expected output is “C G”.
14.3: Write a method that uses lambda expression to accept username and password and return
true or false. (Hint: Use any custom values for username and password for authentication)
14.4: Write a class with main method to demonstrate instance creation using method reference.
(Hint: Create any simple class with attributes and getters and setters)
14.5: Write a method to calculate factorial of a number. Test this method using method reference
feature.
Refer the classes given below to represent employees and their departments .
Also refer an EmployeeRepository class which is used to create and populate employee’s
collection with sample data.
Capgemini Internal
CORE JAVA 8 LAB BOOK
14.7: List out department names and count of employees in each department.
14.9: List employee name and duration of their service in months and days.
14.13: List employee name, hire date and day of week on which employee has started.
14.14: Revise exercise 10.13 to list employee name, hire date and day of week for employee
started on Friday. (Hint: Accept the day name for e.g. FRIDAY and list all employees joined on
Friday)
14.15: List employee’s names and name of manager to whom he/she reports. Create a report in
format “employee name reports to manager name”.
14.17: Find employees who didn’t report to anyone (Hint: Employees without manager)
14.18: Create a method to accept first name and last name of manager to print name of all his/her
subordinates.
Employee id
Department id
First name
Capgemini Internal
CORE JAVA 8 LAB BOOK
Capgemini Internal
CORE JAVA 8 LAB BOOK
Appendices
Classes and interfaces The first letter should be capitalized, and if several words are linked
together to form the name, the first letter of the inner words should be uppercase (a format that's
sometimes called "camelCase").
For classes, the names should typically be nouns. For example:
Dog
Account
PrintWriter
For interfaces, the names should typically be adjectives like
Runnable
Serializable
Methods The first letter should be lowercase, and then normal camelCase rules should be used.
In addition, the names should typically be verb-noun pairs. For example:
getBalance
doCalculation
setCustomerName
Variables Like methods, the camelCase format should be used, starting with a lowercase letter.
Sun recommends short, meaningful names, which sounds good to us. Some examples:
buttonWidth
accountBalance
myString
Constants Java constants are created by marking variables static and final. They should be
named using uppercase letters with underscore characters as separators:
MIN_HEIGHT
Capgemini Internal
CORE JAVA 8 LAB BOOK
Capgemini Internal