Java Assignment
Java Assignment
AND
DEVELOPMENT
TOOLS LAB
BOOK
1
1/
2
Table of Contents
5
CORE JAVA 8 AND
DEVELOPMENT
TOOLS LAB BOOK
<<TO DO>>
.............................................................
442
Lab 13: Multithreading
.............................................................
453
Lab 14 : Lambda Expressions and
Stream………………………………………44
Appendices
.............................................................
486
Appendix A: Naming Conventions........46
Appendix B: Table of Figures
.............................................................
497
6
7
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.
9
10
CORE JAVA 8
AND
DEVELOPMENT
TOOLS LAB
BOOK
12
CORE JAVA 8
AND
DEVELOPMENT
TOOLS LAB
BOOK
13
Figure 1: Java program
Step 2: Set PATH environment variable:
Set PATH=%PATH%;%JAVA_HOME
%\bin;
Step 3: Set your current working directory
and set classpath.
Set CLASSPATH=.
Note: Classpath searches for the
classes required to execute the
command. Hence it must be set to the
directory containing the class files or the
names of the jars delimited by ;
For example:
C:\Test\myproject\Class;ant.jar
14
CORE JAVA 8
AND
DEVELOPMENT
TOOLS LAB
BOOK
Alternate approach:
Step 1: Right click My
Computers, and select
Properties Environment
Variables.
15
16
CORE JAVA 8
AND
DEVELOPMENT
TOOLS LAB
BOOK
17
Figure 4: Edit System
Variable
Step 4: Click PATH System Variable and
set it as %PATH%;%JAVA_HOME%\bin.
18
CORE JAVA 8
AND
DEVELOPMENT
TOOLS LAB
BOOK
19
Step 2: Select FileNewProject Java
project.
CORE JAVA 8
AND
DEVELOPMENT
TOOLS LAB
BOOK
20
Figure 7: Select Wizard
Step 3:Click Next and provide name for the
project.
21
CORE JAVA 8
AND
DEVELOPMENT
TOOLS LAB
BOOK
22
23
CORE JAVA 8
AND
DEVELOPMENT
TOOLS LAB
BOOK
24
Figure 10: Select Resource
25
CORE JAVA 8
AND
DEVELOPMENT
TOOLS LAB
BOOK
27
CORE JAVA 8
AND
DEVELOPMENT
TOOLS LAB
BOOK
30
If you want to open the Java
documentation for specified
resource as html page, right click in
the Javadoc view Open Attached
Javadoc.
31
CORE JAVA 8
AND
DEVELOPMENT
TOOLS LAB
BOOK
Person Details:
____________
First Name: Divya
Last Name: Bharathi
32
Gender: F
Age: 20
Weight: 85.55
33
CORE JAVA 8
AND
DEVELOPMENT
TOOLS LAB
BOOK
35
Lab 3: Exploring Basic Java Class
Libraries
38
CORE JAVA 8
AND
DEVELOPMENT
TOOLS LAB
BOOK
39
Figure 14: Association of person with
account class
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.
40
CORE JAVA 8
AND
DEVELOPMENT
TOOLS LAB
BOOK
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
41
a. Add a variable called overdraft
Limit
b. Overridemethod called
withdraw (checks whether
overdraft limit is reached and
returns a boolean value
accordingly)
42
CORE JAVA 8
AND
DEVELOPMENT
TOOLS LAB
BOOK
a) com.mp.eis.bean
In this package, create
“Employee” class with different
43
attributes such as id, name, salary,
designation, insuranceScheme.
b) com.mp.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.mp.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.
45
CORE JAVA 8
AND
DEVELOPMENT
TOOLS LAB
BOOK
47
CORE JAVA 8
AND
DEVELOPMENT
TOOLS LAB
BOOK
48
available in an arrayList and display the
names using for-each loop.
50
CORE JAVA 8
AND
DEVELOPMENT
TOOLS LAB
BOOK
Lab 8: Files IO
51
delimited by comma. Write a program to
read data from numbers.txt using Scanner
class API and display only even numbers in
the console.
52
CORE JAVA 8
AND
DEVELOPMENT
TOOLS LAB
BOOK
53
Figure 155: Creating Java Project in Eclipse
54
CORE JAVA 8
AND
DEVELOPMENT
TOOLS LAB
BOOK
55
public Person(String
fname,Stringlname)
{
if(fname == null
&&lname==null){
throw new IllegalArgumentException("Both
Names
Cannot be NULL");
}
this.firstName=fname;
this.lastName = lname;
}
public String getFullName()
{
String
first=(this.firstName !=
null)? this.firstName:"?";
String
last=(this.lastName !=
null)? this.lastName:"?";
return first + " " + last;
56
CORE JAVA 8
AND
DEVELOPMENT
TOOLS LAB
BOOK
}
public String getFirstName(){
return this.firstName;
}
public String getLastName(){
return this.lastName;
}
public static void main(String args[])
{
Person p=new Person("a","b");
System.out.println(p.getFirstName
());
}
}
Example 1: Person.java
Step 4: Write the JUnit test class.
Create a JUnit test case in Eclipse.
57
58
CORE JAVA 8
AND
DEVELOPMENT
TOOLS LAB
BOOK
59
Figure 18: Specifying information for the
test case
Write the code as follows:
importorg.junit.*;
import org.junit.Test;
import static org.junit.Assert.*;
public class TestPerson2
{
@Test
public void testGetFullName()
60
CORE JAVA 8
AND
DEVELOPMENT
TOOLS LAB
BOOK
{
System.out.println("from
TestPerson2");
Person per = new
Person("Robert","King");
assertEquals("Robert
King",per.getFullName());
}
@Test
(expected=IllegalArgumentExcepti
on.class)
public void testNullsInName()
{
System.out.println("from
TestPerson2 testing
exceptions"); Person per1
= new Person(null,null); }
}
Example 2: TestPerson2.java
61
Step 5:Run the test case.
Right click thetest case class, and
select RunAs JUnit Test.
The output will be displayed as shown
below:
62
CORE JAVA 8
AND
DEVELOPMENT
TOOLS LAB
BOOK
class Date
{
intintDay, intMonth, intYear;
// Constructor
Date(int intDay, int intMonth, int intYear)
{
this.intDay = intDay;
this.intMonth = intMonth;
this.intYear = intYear;
}
63
/ setter and
getter
methods
voidsetDay(i
nt 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( )
64
{
65
CORE JAVA 8
AND
DEVELOPMENT
TOOLS LAB
BOOK
return this.intYear;
}
public String toString() //converts date
obj to string.
{
return “Date is
“+intDay+”/”+intMonth+”/”+intYear;
}
} // Date class
Example 3: Date.java
67
CORE JAVA 8
AND
DEVELOPMENT
TOOLS LAB
BOOK
68
a) Read data from properties file,
load the data into Properties object
and display the data in the console.
b) Read data from properties
file(using getProperties method)
and print data in the console.
10.2: Extend the assignment 7.3 by
persisting data into database instead of
hashmap and display/delete data from
database. Use DriverManager for
connecting to the database.
69
CORE JAVA 8
AND
DEVELOPMENT
TOOLS LAB
BOOK
72
CORE JAVA 8
AND
DEVELOPMENT
TOOLS 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.
73
CREATE TABLE mobiles (mobileid
NUMBER PRIMARY KEY, name
VARCHAR2 (20), price
NUMBER(10,2),quantity
VARCHAR2(20));
CREATE TABLE
purchasedetails(purchaseid NUMBER,
74
cname vARCHAR2(20), mailid
VARCHAR2(30),phoneno
VARCHAR2(20), purchasedate DATE,
mobileid references mobiles(mobileid));
75
CORE JAVA 8
AND
DEVELOPMENT
TOOLS LAB
BOOK
78
CORE JAVA 8
AND
DEVELOPMENT
TOOLS LAB
BOOK
log4j.rootLogger=ALL, stdout
or
log4j.rootLogger=DEBUG, stdout
80
log4j.rootLogger=FATAL, stdout
81
CORE JAVA 8
AND
DEVELOPMENT
TOOLS LAB
BOOK
83
CORE JAVA 8
AND
DEVELOPMENT
TOOLS LAB
BOOK
log4j.rootLogger=DEBUG, stdout
# Global Threshold - overridden by
any Categories below.
log4j.appender.stdout.Threshold=WA
RN
84
# Categories
log4j.category.com.sample=FATAL
#log4j.category.com.sample.bean=INF
O
log4j.appender.stdout=org.ap
ache.log4j.ConsoleAppender
log4j.appender.stdout.layout=
org.apache.log4j.PatternLayo
ut
log4j.appender.stdout.layout.
ConversionPattern=%5p
[%c{1}] %M - %m%n
86
CORE JAVA 8
AND
DEVELOPMENT
TOOLS LAB
BOOK
87
Step 9: Comment out the following lines
in the log4j.properties file:
#log4j.category.com.sample=FATAL
#log4j.category.com.sample.bean=INF
O
Step 10: Run your application
Log4jDemo3.
The following log messages will be
displayed:
WARN [Message] setMessage - This is
my warn message.
ERROR [Message] setMessage - This is
my error message.
FATAL [Message] setMessage - This is
my fatal message.
WARN [Message] getMessage - This is
my warn message.
ERROR [Message] getMessage - This
is my error message.
FATAL [Message] getMessage - This is
my fatal message.
Hello World
FATAL [Log4jDemo3] main - This is my
fatal message.
88
All log messages should be displayed
due to line "log4j.rootLogger=DEBUG,
stdout". However because of line
"log4j.appender.stdout.Threshold=WAR
N" only messages with priority WARN
or higher are logged.
Step 11: Comment out the following lines
in the log4j.properties file:
#log4j.appender.stdout.Threshold=WA
RN
#log4j.category.com.sample=FATAL
#log4j.category.com.sample.bean=INF
O
Step 12: Run your application
Log4jDemo3.
The following log messages will be
displayed:
DEBUG [Message] setMessage - This is
my debug message.
INFO [Message] setMessage - This is
my info message.
WARN [Message] setMessage - This is
my warn message.
ERROR [Message] setMessage - This is
my error message.
89
FATAL [Message] setMessage - This is
my fatal message.
DEBUG [Message] getMessage - This
is my debug message.
INFO [Message] getMessage - This is
my info message.
90
CORE JAVA 8
AND
DEVELOPMENT
TOOLS LAB
BOOK
91
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;
public class Log4jDemo2 {
//create a logger for Log4jDemo2 class
public static void main(String args[]) {
for(int i=1 ; i<50000; i++) {
System.out.println("Counter = " + i);
log.debug("This is my debug message.
Counter = " + i);
/ write log message
statements for
remaining priority levels
//in the same way
}
}
}
Example 9: Sample code
Step 3: Compile the java code for
Log4jDemo2.java
92
Step 4: Create file
c:\demo\log4j.properties and define
several appenders:
log4j.rootLogger=ERROR, A2
########## Appender A1
log4j.appender.A1=org.apache.log4j.Con
soleAppender
log4j.appender.A1.layout=org.apache.log
4j.PatternLayout
log4j.appender.A1.layout.ConversionPatt
ern=[%5p] %d{mm:ss}
(%F:%M:%L)%n%m%n%n
########## Appender A2
log4j.appender.A2=org.apache.log4j.File
Appender
log4j.appender.A2.File=c:/demo/app_a2.l
og
93
CORE JAVA 8
AND
DEVELOPMENT
TOOLS LAB
BOOK
97
CORE JAVA 8
AND
DEVELOPMENT
TOOLS LAB
BOOK
Step 8: Demonstrate
DailyRollingFileAppender,
change the following line in
c:\demo\log4j.properties:
98
log4j.rootLogger=ERROR, A4
Step 9: Run your application.
By using appender A4, the log file
app_a4.log will be rolled over
depending on the date format (= Java
SimpleDateFormat ) used.
<<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.
100
CORE JAVA 8
AND
DEVELOPMENT
TOOLS LAB
BOOK
101
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
102
CORE JAVA 8
AND
DEVELOPMENT
TOOLS LAB
BOOK
103
user.(Keep delay of 5 seconds after
every 10 characters read.)
Create another class
“FileProgram.java” which will create
above thread. Pass required File
Stream classes to CopyDataThread
constructor and implement the
above functionality.
13.2: Write a thread program to display
timer where timer will get refresh after every
10seconds.( Use Runnable
implementation )
.
104
CORE JAVA 8
AND
DEVELOPMENT
TOOLS LAB
BOOK
107
CORE JAVA 8
AND
DEVELOPMENT
TOOLS LAB
BOOK
109
14.18: Create a method to accept first name
and last name of manager to print name of
all his/her subordinates.
14.19: Sort employees by their
Employee id
Department id
First name
110
CORE JAVA 8
AND
DEVELOPMENT
TOOLS LAB
BOOK
Appendices
Appendix A: Naming Conventions
Package names are written in all lower
case to avoid conflict with the names of
classes or interfaces.Companies use their
reversed Internet domain name to begin
their package names— for example,
com.cg.mypackage for a package named
mypackage created by a programmer at
cg.com.
Packages in the Java language itself begin
with java. Or javax.
111
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
112
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
113
CORE JAVA 8 AND
DEVELOPMENT
TOOLS LAB BOOK
114
115