SlideShare ist ein Scribd-Unternehmen logo
1 von 75
Downloaden Sie, um offline zu lesen
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
JAVA PROGRAMMING
MANUAL
Prepared by
Mr. NAVEEN SAGAYASELVARAJ
Lecturer
CSC Computer Education
Krishnagiri
Ms. MANGAIYARKKARASI V
Lecturer
CSC Computer Education
Gopichettipalayam
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
I
S.NO. CONTENT PAGE NO.
1 INTRODUCTION 1
2 PROGRAMMING CONSTRUCTS &
CASTING AND TYPE CONVERSION
4
3 ARRAYS 11
4 STRING CLASS 15
5 COSTRUCTOR 20
6 INHERITANCE AND INTERFACE 23
7 I/O STREAM CLASSES 27
8 APPLETS AND SWINGS 39
9 EVENT-HANDLING 49
10 MULTITHREADING 54
11 NETWORKING-I 59
12 NETWORKING-II 68
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
1
1 INTRODUCTION
OBJECTIVE:
Basic Programming using class and objects.
OVERVIEW:
Classes and Objects:
The fundamental programming unit of the Java programming language is the class. Classes provide
the structure for objects and the mechanisms to manufacture objects from a class definition. Classes define
methods: collections of executable code that are the focus of computation and that manipulate the data stored
in objects. Methods provide the behavior of the objects of a class.
Syntax:
For Class definition:
class class_name
{
Datatype variable_name; //Data_Memebers
Returntype method_name(parameters) //Member_Function
{
-------------;
}
Pubic static void main(String arg[ ])
{
//Main Method block
}
}
For Object creation:
class_name object_name = new class_name( );
objectname.variable_name;
objectname.methodname( );
To access data_members and
member_function of the class
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
2
Sample coding:
/**
*
* @author NaveenSagayaelvaRaj
*/
public class First_Program
{
private int first_num = 5;
private int second_num = 6;
public void add()
{
int answer;
answer = first_num+second_num;
System.out.println("Answer: "+answer);
}
public static void main(String arg[])
{
First_Program obj=new First_Program();
obj.add();
}
}
Output:
run:
Answer: 11
BUILD SUCCESSFUL (total time: 1 second)
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
3
PRE LAB EXERCISE
Define a class sample with the following specification
Public member function of class sample
Display() Function to Display “Hello!! World”
IN LAB EXERCISE
Define a class student with the following specification
Private members of class student
Roll_no int
Phy,che& mathsdouble
Total double
Average int
Cal_Total() a function to calculate Total with double return type
Cal_Avg() a function to calculate Average with int return type
Public member function of class student
Takedata() Function to accept values for Roll_no, Phy,che, maths,
invoke Cal_total() to calculate total and invoke Cal_Avg() to calculate average.
Showdata() Function to display all the data members.
POST LAB EXERCISE
Define a class BOOK with the following specifications :
Private members of the class BOOK are
BOOK NO integer type
PRICE double (price per copy)
TOTAL_COST() A function to calculate the total cost for N number of
copies where N is passed to the function as argument.
Public members of the class BOOK are
INPUT() function to read BOOK_NO., PRICE
PURCHASE() function to ask the user to input the number of copies to be
purchased. It invokes TOTAL_COST() and prints the total
cost to be paid by the user.
Result:
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
4
2 PROGRAMMING CONSTRUCTS & CASTING
AND TYPE CONVERSION
OBJECTIVE:
Programming using constructs, looping, casing and type conversions.
OVERVIEW:
SELECTION CONTROL STRUCTURE:
A selection control structure, allows a program to select between two or more alternative paths of
execution.
 if Statement:
if statement is the most basic selection control structure.
Syntax:
if(boolean expression)
{
Statement;
}
 if else Statement:
Syntax:
if(boolean expression)
{
Statement;
}
else
{
Statement;
}
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
5
 else if Statement:
Syntax:
if(boolean expression)
{
Statement;
}
else if(boolean expression)
{
Statement;
}
else
{
Statement;
}
 Nested if:
Syntax:
if(boolean expression)
{
Statement;
if(boolean expression)
{
Statement;
}
}
else
{
Statement;
}
 Switch Statement:
It’s a multiway branching statement. It is based on value on expression.
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
6
Syntax:
switch(ch)
{
case 1:
Statement;
break;
case 2:
Statement;
break;
.
.
.
.
case n:
Statement;
break;
default:
Statement;
break;
}
LOPPING STATEMENTS:
Looping statement causes a section of statements in the program to be executed a certain number of
times. The repetition remains until the condition is true. If the condition false loop ends, and the control
structure passes to the next statement.
 for Loop:
Syntax:
for(Initialization ; boolean expression ; Iteration)
{
Statement:
}
 Enhanced For Loop:
This type of for loop allows iterating through an array without creating an iterator. And do not
need to maintain index of each element.
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
7
Syntax:
for(declaration:expression)
{
Statement:
}
 while Loop
Syntax:
while(boolean expression)
{
Statement:
}
 do while Loop:
Syntax:
do
{
Statement:
} while(boolean expression);
CASTING AND CONVERSION:
Casting allow converting a variable of one datatype to another.
Types of conversion:
1. Implicit conversion- Automatic conversion take place of one datatype to another.
Example int to long automatic conversion.
2. Explicit conversion- We force to convert one datatype to another
Syntax
(type) value;
Example:
char ch = ’A’;
int Asci=(int)ch; //Explicit conversion take place
Example:
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
8
int Asci = 65;
char ch=(char)ch; //Explicit conversion take place
Sample coding:
/**
*
* @author NaveenSagayaselvaRaj
*/
public class Second_Program {
public static void main(String arg[])
{
System.out.println("**Find whether the given element is Alphabet or a
Numberic**n");
char ch='H';
int Asci=(int)ch;
if((Asci>=65 && Asci<=90) || (Asci>=97 && Asci<=122))
{
System.out.println(ch+" is a Alphabet ");
}
else if((Asci>=48 && Asci<=57))
{
System.out.println(ch+" is a Numeric ");
}
}
Output:
run:
**Find whether the given element is Alphabet or a Numeric**
H is a Alphabet
BUILD SUCCESSFUL (total time: 1 second)
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
9
Sample coding:
/**
*
* @author NaveenSagayaselvaRaj
*/
import java.util.Scanner;
public class Third_Program {
public static void main(String args[])
{
int n, num = 1, c, d;
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of rows of floyd's triangle you want");
n = in.nextInt();
System.out.println("**Floyd's triangle**");
for ( c = 1 ; c <= n ; c++ )
{
for ( d = 1 ; d <= c ; d++ )
{
System.out.print(num+" ");
num++;
}
System.out.println();
}
}
}
Output:
run:
Enter the number of rows of floyd's triangle you want
8
**Floyd's triangle**
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31 32 33 34 35 36
BUILD SUCCESSFUL (total time: 5 seconds)
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
10
PRE LAB EXERCISE
a. Write a Java program to find Asci value of given char
b. Write a Java program to print output as follows,
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
IN LAB EXERCISE
a. Write a Java program to change Upper case alphabet to Lower case alphabet
b. Write a Java program to print Pyramid
POST LAB EXERCISE
a. Write Java program to convert the following,
I/P Enter a character: 3
O/P Converted into int: 3
b. Write a Java program to print Diamond
Result:
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
11
3 ARRAYS
OBJECTIVE:
Programming using arrays.
OVERVIEW:
Arrays:
An Array is a contiguous block of memory location referred by a common name. The length of the
array is fixed at the time of creation.
Steps to create an Array:
1. Declare an Array
2. New operator to allocate memory to an Array
Types of Arrays:
 One Dimensional Array
 Multi-Dimensional Array
Syntax:
For One Dimensional Array:
1. Declare an Array
Datatype Array_Name [ ];
2. New operator to allocate memory to an Array
Array_Name[ ] = new Datatype[boundary condition ];
For Multi-Dimensional Array:
1. Declare an Array
Datatype Array_Name [ ] [ ];
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
12
2. New operator to allocate memory to an Array
Array_Name[ ] = new Datatype[boundary condition ] [boundary condition
];
Sample coding:
/**
*
* @author NaveenSagayaselvaRaj
*/
public class Fourth_Program {
public static void main(String arg[])
{
int array[]=new int[10];
int sum=0;
Scanner in=new Scanner(System.in);
System.out.println("Enter 10 elements: ");
for(int i=0;i<10;i++)
{
array[i]=in.nextInt();
}
for(int i=0;i<10;i++)
{
sum+=array[i];
}
System.out.print("Sum of the elements of an Array: "+sum);
}
}
Output:
run:
Enter 10 elements:
1 2 3 4 5 6 7 8 9 0
Sum of the elements of an Array: 45
BUILD SUCCESSFUL (total time: 11 seconds)
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
13
Sample coding:
/**
*
* @author NaveenSagayaselvaRaj
*/
public class Fifth_Program {
public static void main(String arg[])
{
int org_arr[][]=new int[2][2];
int tra_arr[][]=new int[2][2];
System.out.println("***********Transpose of Matrix********");
Scanner in=new Scanner(System.in);
System.out.println("Enter the elements for 2X2 matrix:");
for(int i=0;i<2;i++)
{
for(int j=0;j<2;j++)
{
org_arr[i][j]=in.nextInt();
}
System.out.println();
}
for(int i=0;i<2;i++)
{
for(int j=0;j<2;j++)
{
tra_arr[i][j]=org_arr[j][i];
}
}
for(int i=0;i<2;i++)
{
for(int j=0;j<2;j++)
{
System.out.print(tra_arr[i][j]);
}
System.out.println();
}
}
}
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
14
Output:
run:
***********Transpose of Matrix********
Enter the elements for 2X2 matrix:
1 2
3 4
1 3
2 4
BUILD SUCCESSFUL (total time: 7 seconds)
PRE LAB EXERCISE
a. Write a Java program to find product of n elements in an array
b. Write a Java program to find addition of two matrices
IN LAB EXERCISE
a. Write Java program to find whether the given element in the array are positive real number or
negative real number or zero
b. Write a Java program to find a given matrix is diagonal matrix or not
POST LAB EXERCISE
a. Write a Java program for TIC TAC TOE game
Result:
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
15
4 STRING CLASS
OBJECTIVE:
Detailed study on string class and its methods
OVERVIEW:
String class:
String is the most commonly used class in Java. String is a instance of the class string. They are real
object.
Methods in String class:
S.NO Method Description
1 char charAt(int index) Returns the character at the specified index
2 int compareTo(Object o) Compares this String to another Object.
3
int compareTo(String anotherString)
Compares two strings lexicographically.
4 int compareToIgnoreCase(String str) Compares two strings lexicographically,
ignoring case differences.
5 String concat(String str) Concatenates the specified string to the end of
this string
6 boolean contentEquals(StringBuffer sb) Returns true if and only if this String
represents the same sequence of characters as
the specified StringBuffer.
7 static String copyValueOf(char[] data) Returns a String that represents the character
sequence in the array specified
8 static String copyValueOf(char[] data, int
offset, int count)
Returns a String that represents the character
sequence in the array specified
9 boolean endsWith(String suffix) Tests if this string ends with the specified
suffix
10 boolean equals(Object anObject) Compares this string to the specified object.
11 boolean equalsIgnoreCase(String
anotherString)
Compares this String to another String,
ignoring case considerations.
12 byte getBytes() Encodes this String into a sequence of bytes
using the platform's default charset, storing
the result into a new byte array.
13 byte[] getBytes(String charsetName) Encodes this String into a sequence of bytes
using the named charset, storing the result
into a new byte array.
14 void getChars(int srcBegin, int srcEnd,
char[] dst, int dstBegin)
Copies characters from this string into the
destination character array.
15 int hashCode() Returns a hash code for this string.
16 int indexOf(int ch) Returns the index within this string of the first
occurrence of the specified character.
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
16
17 int indexOf(int ch, int fromIndex) Returns the index within this string of the first
occurrence of the specified character, starting
the search at the specified index.
18 int indexOf(String str) Returns the index within this string of the first
occurrence of the specified substring.
19 int indexOf(String str, int fromIndex) Returns the index within this string of the first
occurrence of the specified substring, starting
at the specified index
20 String intern() Returns a canonical representation for the
string object.
21 int lastIndexOf(int ch) Returns the index within this string of the last
occurrence of the specified character
22 int lastIndexOf(int ch, int fromIndex) Returns the index within this string of the last
occurrence of the specified character,
searching backward starting at the specified
index.
23 int lastIndexOf(String str) Returns the index within this string of the
rightmost occurrence of the specified
substring.
24 int lastIndexOf(String str, int fromIndex) Returns the index within this string of the last
occurrence of the specified substring,
searching backward starting at the specified
index.
25 int length() Returns the length of this string.
26 boolean matches(String regex) Tells whether or not this string matches the
given regular expression.
27 boolean regionMatches(boolean
ignoreCase, int toffset, String other, int
ooffset, int len)
Tests if two string regions are equal.
28 boolean regionMatches(int toffset, String
other, int ooffset, int len)
Tests if two string regions are equal
29 String replace(char oldChar, char
newChar)
Returns a new string resulting from replacing
all occurrences of oldChar in this string with
newChar.
30 String replaceAll(String regex, String
replacement )
Replaces each substring of this string that
matches the given regular expression with the
given replacement.
31 String replaceFirst(String regex, String
replacement)
Replaces the first substring of this string that
matches the given regular expression with the
given replacement.
32 String[] split(String regex) Splits this string around matches of the given
regular expression.
33 String[] split(String regex, int limit) Splits this string around matches of the given
regular expression.
34 boolean startsWith(String prefix) Tests if this string starts with the specified
prefix.
35 boolean startsWith(String prefix, int
toffset)
Tests if this string starts with the specified
prefix beginning a specified index
36 CharSequence subSequence(int
beginIndex, int endIndex)
Returns a new character sequence that is a
subsequence of this sequence
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
17
37 String substring(int beginIndex) Returns a new string that is a substring of this
string.
38 String substring(int beginIndex, int
endIndex)
Returns a new string that is a substring of this
string
39 char[] toCharArray() Converts this string to a new character array.
40 String toLowerCase() Converts all of the characters in this String to
lower case using the rules of the default
locale.
41 String toLowerCase(Locale locale) Converts all of the characters in this String to
lower case using the rules of the given Locale.
42 String toString() This object (which is already a string!) is
itself returned.
43 String toUpperCase() Converts all of the characters in this String to
upper case using the rules of the default
locale.
44 String toUpperCase(Locale locale) Converts all of the characters in this String to
upper case using the rules of the given Locale
45 String trim() Returns a copy of the string, with leading and
trailing whitespace omitted.
46 static String valueOf(primitive data type
x)
Returns the string representation of the passed
data type argument
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
18
Sample coding:
/**
*
* @author NaveenSagayaselvaRaj
*/
public class Sixth_Program {
//Find whether the string is plaindrome or not
public static void main(String arg[])
{
String str;
Scanner in=new Scanner(System.in);
System.out.println("Enter the string: ");
str=in.next();
//Reverse the String
String rev = "";
int length=str.length();
for(int i=0;i<length;i++)
{
rev+=str.charAt(length-i-1);
}
if(str.compareTo(rev)==0)
{
System.out.println("Its a Palindrome");
}
else
{
System.out.println("Its a not Palindrome");
}
}
}
Output:
run:
Enter the string:
malayalam
Its a Palindrome
BUILD SUCCESSFUL (total time: 7 seconds)
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
19
PRE LAB EXERCISE
a. Write a program to find length of the given string without using the string class’s method
b. Write a Java program to find number of lower case and number of upper case letters in a string
IN LAB EXERCISE
a. Write a Java program to find whether the given string is palindrome or not without using string
class’s methods
b. Write a Java program to change upper case character to lower case character in a string, vice
versa,.
POST LAB EXERCISE
a. Write Java program to find whether the given string is palindrome or not if the characters of the
strings is interchanged
Eg:
I/P Enter the string: tests
O/P It will became palindrome
Result:
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
20
5 COSTRUCTOR
OBJECTIVE:
Programming using a special type of member function
OVERVIEW:
Constructor:
Constructor method is a special kind of method which are used to initialize objects.
Characteristic of Constructor:
b. Constructor name same as the class name
c. It should be declared as public
d. It should not have any return type
e. It invoked when an object of class is created, it can't be called explicitly
f. It can be overloaded
Types of Constructor:
1. Default constructor – Constructor without arguments
2. Parameterized constructor – Constructor with arguments
Sample coding:
Default constructor:
/**
*
* @author NaveenSagayaselvaRaj
*/
public class Seventh_Program {
Seventh_Program() {
System.out.println("Constructor method called.");
}
public static void main(String[] args) {
Seventh_Program obj = new Seventh_Program();
}
}
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
21
Output:
run:
Constructor method called.
BUILD SUCCESSFUL (total time: 0 seconds)
Parameterized constructor:
/**
*
* @author NaveenSagayaselvaRaj
*/
public class Eigth_Program {
Eigth_Program(int num) {
System.out.println("Number: "+num);
}
public static void main(String[] args) {
Eigth_Program obj = new Eigth_Program(50);
}
}
Output:
run:
50
BUILD SUCCESSFUL (total time: 0 seconds)
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
22
PRE LAB EXERCISE
*******************************NILL************************************
IN LAB EXERCISE
a. Define a class called fruit with the following attributes :
1. Name of the fruit
2. Single fruit or bunch fruit
3. Price
Define a suitable constructor and display_Fruit() method that displays values of all the attributes.
Write a program that creates 2 objects of fruit class and display their attributes.
POST LAB EXERCISE
*******************************NILL************************************
Result:
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
23
6 INHERITANCE AND INTERFACE
OBJECTIVE:
Programming using various types of inheritance concept
OVERVIEW:
Inheritance:
Inheritance enable you to reuse the functionality and capabilities of the existing class by extending
a new class from existing class and adding new future to it. In inheritance the class that inherits the data
member and methods from another class is known as subclass. The class from which the subclass inherits is
known as the super class.
Types of Inheritance:
1. Single Level Inheritance
2. Multilevel Inheritance
Single Level Inheritance:
Multilevel Inheritance:
super_class_name
sub_class_name1 sub_class_name2
super_class_name
sub_class_name1
sub_class_name2
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
24
Syntax:
Single Level Inheritance
class super_class_name
{
//body of the class super_class
}
class sub_class_name1 extends super_class_name
{
//body of the sub_class
}
class sub_class_name2 extends super_class_name
{
//body of the sub_class
}
Multilevel Inheritance
class super_class_name
{
//body of the class super_class
}
class sub_class_name1 extends super_class_name
{
//body of the sub_class
}
class sub_class_name2 extends sub_class_name1
{
//body of the sub_class
}
Interface:
There may be cases where we need to inherit the features of more than one class. But Java does
not support multiple inheritance. However, we can simulate multiple inheritance in java by using interface.
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
25
Syntax:
interface interface_name
{
//interface body
static final data members;
return type public methods(parameters);
}
class sub_class_name extends super_class_name implements interface_name
{
//Defining the method declare in the interface
return type public methods(parameters)
{
//Body of the method
}
}
Sample coding:
public class Nine_Program {
void display()
{
System.out.println("Super_Class");
}
}
public class Tenth_Program extends Nine_Program{
public static void main(String arg[])
{
Tenth_Program obj=new Tenth_Program();
obj.display();
}
}
run:
Super_Class
BUILD SUCCESSFUL (total time: 0 seconds)
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
26
PRE LAB EXERCISE
*******************************NILL************************************
IN LAB EXERCISE
a. Create a class student and declare variable rollno.
Create function getnumber() and display().
Create another class test which inherit student.
Create function display().
Create another interface sports with variable sport and function putsp().
Create variable total and function putsp(),display().
Create another class result which extends the test and sport.
Create main class main_class and which has the student as object of class result.
POST LAB EXERCISE
*******************************NILL************************************
Result:
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
27
7 I/O STREAM CLASSES
OBJECTIVE:
Implementation of various file classes supported by Java for reading and writing to the file
OVERVIEW:
Introduction:
All programs accept input from user, process the input and produce output. Therefore, all
programming languages support the reading of input and display of output. Java handles all input and output
in form of streams. A stream is a sequence of bytes traveling from a source to destination over a
communication path. When a stream of data is being sent, it is said to be written, and when a stream of data
is being received, it is said to be read.
Implementing the File class:
File are the primary source and destination for storing the data contain in the programs. Java
provide the java.io package for performing I/O operation. This include File class.
File class Constructors:
Constructor Description
File(File parent, String child) This constructor is used to create a new File object with the
parent path name and child pathname.
Syntax : public File(File parent, String child)
File(String pathname) This constructor is used to create a new File object with
specified file pathname.
Syntax : public File(String pathname)
File(String parent, String
child)
This constructor is used to create a new File object with the
specified parent pathname and child pathname.
Syntax : public File(String parent, String child)
File(URI uri) This constructor is used to create a new File object by
converting a specified URI into pathname.
Syntax : public File(URI uri)
Methods in File class:
Method Descrption
public boolean canExecute() This method is used for testing that whether the file can
be executed by the application or not.
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
28
public boolean canRead() : This method is used for testing that whether the file can
be read by the application or not.
public boolean canWrite() This method is used for testing that whether the file can
be write by the application or not.
public int compareTo(File
pathname)
This method is used to compare two file pathname.
public boolean
createNewFile() throws
IOException
This method is used for creating a new empty file with
the specified name.
public static File
createTempFile(String
prefix,String suffix) throws
IOException
This method is used for creating an empty file in the
default temporary file directory. prefix and suffix are
used for specifying the name of file.
public static File
createTempFile(String
prefix, String suffix, File
directory) throws
IOException
This method is used for creating an empty file in the
given directory. prefix and suffix are used for specifying
the name of file.
public boolean delete() This method is used for deleting the specified file or
directory.
public void deleteOnExit() This method is used for deleting the specified file or
directory on the termination of JVM.
public boolean equals(Object
obj)
This method is used to test whether the specified Object
is equal to the pathname or not.
public boolean exists() This method is used to test whether the specified
pathname is existed or not.
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
29
public File getAbsoluteFile() This method is used to get the absolute form of
pathname.
public String
getAbsolutePath()
This method is used to get the absolute pathname. This
pathname is retrieved as string.
public long getFreeSpace() This method is used to find out the unallocated bytes in
the partition (portion of storage for a file system.)
public String getName() This method is used to find out the name of file or
directory of the specified pathname.
public String getParent() This method is used to find out the parent of the specified
pathname.
public File getParentFile() This method is used to find out the parent of the specified
pathname.
public String getPath() This method is used to find out the path of the file or
directory as string.
public long getTotalSpace() This method is used to find out the size of the partition.
public long getUsableSpace() This method is used to find out the number of bytes made
available to the VM when the partition named by the
pathname.
public int hashCode() This method is used for computing a hash code for
pathname.
public boolean isAbsolute() This method is used for testing that whether the
pathname is absolute or not.
public boolean isDirectory() This method is used for testing that whether the specified
pathname is directory or not.
public boolean isFile() This method specifies whether the specified file name is
a normal file or not.
public boolean isHidden() This method specifies, whether the file is a hidden file or
not.
public long lastModified() This method is used to get the time in which the file was
last modified.
public long length() This method is used to get the length of the file.
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
30
public String[] list() This method is used to get the list of files and directories
(as an array of strings) in the specified directory
public String[]
list(FilenameFilter filter)
This method is used to get the list of files and directories
(as an array of strings) in the specified directory which
specifies a specified filter.
public File[] listFiles() This method is used to get the (an array) pathnames
which represents files in the directory.
public File[]
listFiles(FileFilter filter)
This method is used to get the (an array) pathnames
which represents files and directories in the specified
directory which specifies a specified filter.
public File[]
listFiles(FilenameFilter
filter)
This method is used to get the (an array) pathnames
which represents files and directories in the specified
directory which specifies a specified filter.
public static File[] listRoots() This method is used to list the file system roots (if
available).
public boolean mkdir() This method is used to create a directory with the
specified pathname.
public boolean mkdirs() This method is used to create a directory with the
specified pathname.
public boolean
renameTo(File dest)
This method is used to rename the file specified by the
pathname.
public boolean
setExecutable(boolean
executable)
This method is used to set the permission of execution of
files.
public boolean
setExecutable(boolean
executable, boolean
ownerOnly)
: This method is used to set the permission of execution
of files.
public boolean
setLastModified(long time)
This method is used to set the file's or directory's last
modified time.
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
31
public boolean
setReadable(boolean
readable)
This method is used to set the permission of file to read.
public boolean
setReadable(boolean
readable, boolean
ownerOnly)
This method is used to set the permission of file to read.
public boolean
setReadOnly()
This method is used to set the file's or directory's to
allowed only for read operation.
public boolean
setWritable(boolean
writable)
This method is used to set the file's or directory's to
allowed only for write operation
public boolean
setWritable(boolean
writable, boolean
ownerOnly)
This method is used to set the file's or directory's to
allowed only for write operation.
public String toString() : This method is used to get the pathname of the specified
abstract pathname as string.
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
32
Sample coding:
/**
*
* @author NaveenSagayaselvaRaj
*/
import java.io.*;
public class Eleventh_Program {
public static void main(String[] args) throws IOException
{
File f;
f=new File("D:/myfile.txt");
if(!f.exists())
{
f.createNewFile();
System.out.println(“New file "myfile.txt" has been created to the
given directory);
}
else
{
System.out.println("The specified file is already exist");
}
}
}
Output:
run:
New file "myfile.txt" has been created to the given directory
BUILD SUCCESSFUL (total time: 3 seconds)
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
33
Screenshot:
Using Streams in Java:
Accessing File using the InputStream Class:
InputStream are the byte streams that read data in the form of byte. Java providing classes are
shown below,
InputStream
SequenceInputStream ObjectInputStream PipedInputStream ByteArrayInputStream FilterInputStream FileInputStream
PushbackInputStream BufferedInputStreamDataInputStream
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
34
Using Streams in Java:
Accessing File using the OutputStream Class:
OutputStream are the byte streams that write data in the form of byte. Java providing classes
are shown below,
Implementing Character Stream Classes:
Using the Reader Class:
The Reader class is used to read characters from the character streams. The Reader class
cannot be instantiated since it is an abstract class. Therefore, the object of its subclasses are used for
reading Unicode character data.
OutputStream
ObjectOutputStream PipedOutputStream ByteArrayOutputStream FilterOutputStream FileOutputStream
BufferedOutputStreamDataOutputStream
Reader
BufferedReader LineNumberReader
StringReader
InputStreamReader FileReader
PipedReader
FilterReader PushbackReader
CharArrayReader
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
35
Using the Writer class:
The Writer class is used to write characters from the character streams. The Writer class
cannot be instantiated since it is an abstract class. Therefore, the object of its subclasses are used for
writing character data to a character stream.
Sample coding:
/**
*
* @author NaveenSagayaselvaRaj
*/
public class Twelfth_Program {
public static void main(String arg[]) throws FileNotFoundException, IOException
{
char ch;
File f=new File("D:/test.txt");
FileReader fr=new FileReader(f);
//Reading a content from file
while(fr.ready())
{
ch=(char)fr.read();
System.out.print(ch);
}
System.out.println();
fr.close();
} }
Writer BufferedWriter
StringWriter
OutputStreamWriter FileWriter
PipedWriter
FilterWriter
CharArrayWriter
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
36
Output:
run:
Hello!!! world
BUILD SUCCESSFUL (total time: 0 seconds)
Snapshot:
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
37
Sample coding:
/**
*
* @author NaveenSagayaselvaRaj
*/
public class Twelfth_Program {
public static void main(String arg[]) throws FileNotFoundException, IOException
{
String str="Writer working";
File f=new File("D:/test.txt");
FileWriter fw=new FileWriter(f);
fw.write(str);
fw.close();
}
}
Output:
run:
BUILD SUCCESSFUL (total time: 0 seconds)
Snapshot:
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
38
PRE LAB EXERCISE
a. Write a Java Program to print size of a file
b. Write a Java program to copy the text file using InputStream and OutputStream
IN LAB EXERCISE
a. Write a Java program to get absolute path of the file
b. Write a Java program to read the entire text file, eliminate all special characters in it and write the
content in the same text file
I/O test.txt
Hai!! How Are You?
O/P test.txt
HaiHowAreYou
POST LAB EXERCISE
a. Write a Java program to delete a file
b. Write a Java program to prove the following mathematics notations,
1. n(n + l)(2n + 1) is always divisible by 6.
2. 32n
leaves remainder = 1 when divided by 8
3. n3
+ (n + 1 )3
+ (n + 2 )3
is always divisible by 9
4. 102n + 1
+ 1 is always divisible by 11
5. n(n2
– 1) is always divisible by 6
6. n2
+ n is always even
7. 23n
-1 is always divisible by 7
8. 152n-1
+l is always divisible by 16
9. n3
+ 2n is always divisible by 3
10. 34n
– 4 3n
is always divisible by 17
*(Note get the value of n from the text file)
Result:
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
39
8 APPLETS AND SWINGS
OBJECTIVE:
Creating GUI using Java programming.
OVERVIEW:
Applet:
Applet are Java program that executes inside a Web page. Therefore, unlike applications, applet
require a Java enabled browsers like Internet Explorer or Netscape etc. An applet loaded and executed when
a user load a Web page through Wed browser.
Applet Life Cycle:
Various Graphics Methods:
S.No Method Purpose
1
public void init() Called once by the applet container when an applet is loaded for
execution. This method initializes an applet. Typical actions
performed here are initializing fields, creating GUI components,
loading sounds to play, loading images to display
2
public void start() Called by the applet container after method init completes execution.
In addition, if the user browses to another website and later returns to
the applet’s HTML page, method start is called again. The method
performs any tasks that must be completed when the applet is loaded
for the first time and that must be performed every time the applet’s
HTML page is revisited. Actions performed here might include
starting an animation
3
public void paint(
Graphics g )
Called by the applet container after methods init and start. Method
paint is also called when the applet needs to be repainted. For example,
if the user covers the applet with another open window on the screen
and later uncovers the applet, the paint method is called. Typical
actions performed here involve drawing with the Graphics object g that
is passed to the paint method by the applet container
4
public void stop() This method is called by the applet container when the user leaves the
applet’s web page by browsing to another web page. Since it is
possible that the user might return to the web page containing the
applet, method stop performs tasks that might be required to suspend
the applet’s execution, so that the applet does not use computer
processing time when it is not displayed on the screen. Typical actions
performed here would stop the execution of animations
5
public void destroy() This method is called by the applet container when the applet is being
removed from memory. This occurs when the user exits the browsing
session by closing all the browser windows
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
40
Method Description
abstract void clearRect(int x, int y, int width,
int height)
Clears the specified rectangle by filling it
with the background color of the current
drawing surface.
abstract void clipRect(int x, int y, int width, int height) Intersects the current clip with the
specified rectangle.
abstract void copyArea(int x, int y, int width,
int height, int dx, int dy)
Copies an area of the component by a
distance specified by dx and dy.
abstract Graphics create()
Creates a new Graphics object that is a
copy of this Graphics object.
Graphics create(int x, int y, int width, int height) Creates a new Graphics object based on
this Graphics object, but with a new
translation and clip area.
abstract void dispose() Disposes of this graphics context and
releases any system resources that it is
using.
void draw3DRect(int x, int y, int width, int height,
boolean raised)
Draws a 3-D highlighted outline of the
specified rectangle.
abstract void drawArc(int x, int y, int width,
int height, int startAngle, int arcAngle) Draws the outline of a circular or elliptical
arc covering the specified rectangle.
void drawBytes(byte[] data, int offset, int length, int x,
int y)
Draws the text given by the specified byte
array, using this graphics context's current
font and color.
void drawChars(char[] data, int offset, int length,
int x, int y)
Draws the text given by the specified
character array, using this graphics
context's current font and color.
abstract boolean drawImage(Image img, int x, int y,
Color bgcolor, ImageObserver observer)
Draws as much of the specified image as is
currently available.
abstract boolean drawImage(Image img, int x, int y,
ImageObserver observer)
draws as much of the specified image as is
currently available.
abstract boolean drawImage(Image img, int x, int y,
int width, int height, Color bgcolor,
ImageObserver observer)
Draws as much of the specified image as
has already been scaled to fit inside the
specified rectangle.
abstract boolean drawImage(Image img, int x, int y,
int width, int height, ImageObserver observer)
Draws as much of the specified image as
has already been scaled to fit inside the
specified rectangle.
abstract booleandrawImage(Image img, int dx1,
int dy1, int dx2, int dy2, int sx1, int sy1, int sx2,
int sy2, Color bgcolor, ImageObserver observer)
Draws as much of the specified area of the
specified image as is currently available,
scaling it on the fly to fit inside the
specified area of the destination drawable
surface.
abstract boolean drawImage(Image img, int dx1,
int dy1, int dx2, int dy2, int sx1, int sy1, int sx2,
int sy2, ImageObserver observer)
Draws as much of the specified area of the
specified image as is currently available,
scaling it on the fly to fit inside the
specified area of the destination drawable
surface.
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
41
abstract void drawLine(int x1, int y1, int x2, int y2) Draws a line, using the current color,
between the points (x1, y1) and (x2, y2) in
this graphics context's coordinate system.
abstract void drawOval(int x, int y, int width,
int height)
Draws the outline of an oval.
abstract void drawPolygon(int[] xPoints, int[] yPoints,
int nPoints)
Draws a closed polygon defined by arrays
of x and y coordinates.
void drawPolygon(Polygon p) Draws the outline of a polygon defined by
the specified Polygon object.
abstract void drawPolyline(int[] xPoints, int[] yPoints,
int nPoints)
Draws a sequence of connected lines
defined by arrays of x and y coordinates.
void drawRect(int x, int y, int width, int height) Draws the outline of the specified
rectangle.
abstract void drawRoundRect(int x, int y, int width,
int height, int arcWidth, int arcHeight) Draws an outlined round-cornered
rectangle using this graphics context's
current color.
abstract void
drawString(AttributedCharacterIterator iterator,
int x, int y)
Renders the text of the specified iterator
applying its attributes in accordance with
the specification of the TextAttribute class.
abstract void drawString(String str, int x, int y)
Draws the text given by the specified
string, using this graphics context's current
font and color.
void fill3DRect(int x, int y, int width, int height,
boolean raised) Paints a 3-D highlighted rectangle filled
with the current color.
abstract void fillArc(int x, int y, int width, int height,
int startAngle, int arcAngle)
Fills a circular or elliptical arc covering the
specified rectangle.
abstract void fillOval(int x, int y, int width, int height) Fills an oval bounded by the specified
rectangle with the current color.
abstract void fillPolygon(int[] xPoints, int[] yPoints,
int nPoints)
Fills a closed polygon defined by arrays of
x and y coordinates.
void fillPolygon(Polygon p)
Fills the polygon defined by the specified
Polygon object with the graphics context's
current color.
abstract void fillRect(int x, int y, int width, int height)
Fills the specified rectangle.
abstract void fillRoundRect(int x, int y, int width,
int height, int arcWidth, int arcHeight)
Fills the specified rounded corner rectangle
with the current color.
void finalize() Disposes of this graphics context once it is
no longer referenced.
abstract Shape getClip() Gets the current clipping area.
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
42
Sample coding:
/**
*
* @author NaveenSagayaselvaRaj
*/
import java.applet.Applet;
import java.awt.Graphics;
abstract Rectangle getClipBounds() Returns the bounding rectangle of the
current clipping area.
Rectangle getClipBounds(Rectangle r)
Returns the bounding rectangle of the
current clipping area.
Rectangle getClipRect()
Deprecated.
As of JDK version 1.1, replaced by
getClipBounds().
abstract Color getColor() Gets this graphics context's current color.
abstract Font getFont() Gets the current font.
FontMetrics getFontMetrics() Gets the font metrics of the current font.
abstract FontMetrics getFontMetrics(Font f)
Gets the font metrics for the specified font.
boolean hitClip(int x, int y, int width, int height)
Returns true if the specified rectangular
area might intersect the current clipping
area.
abstract void setClip(int x, int y, int width, int height) Sets the current clip to the rectangle
specified by the given coordinates.
abstract void setClip(Shape clip) Sets the current clipping area to an
arbitrary clip shape.
abstract void setColor(Color c) Sets this graphics context's current color to
the specified color.
abstract void setFont(Font font) Sets this graphics context's font to the
specified font.
abstract void setPaintMode() Sets the paint mode of this graphics
context to overwrite the destination with
this graphics context's current color.
abstract void setXORMode(Color c1) Sets the paint mode of this graphics
context to alternate between this graphics
context's current color and the new
specified color.
String toString() Returns a String object representing this
Graphics object's value.
abstract void translate(int x, int y) Translates the origin of the graphics
context to the point (x, y) in the current
coordinate system.
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
43
import javax.swing.JOptionPane;
public class Fourteenth extends Applet {
private double sum;
/**
* Initialization method that will be called after the applet is loaded into
* the browser.
*/
public void init() {
String firstNumber;
String secondNumber;
double number1;
double number2;
firstNumber = JOptionPane.showInputDialog( "Enter first floating-point
value" );
secondNumber = JOptionPane.showInputDialog( "Enter second floating-point
value" );
number1 = Double.parseDouble( firstNumber );
number2 = Double.parseDouble( secondNumber );
sum = number1 + number2;
}
public void paint( Graphics g )
{
super.paint( g );
g.drawRect( 15, 10, 270, 20 );
g.drawString( "The sum is " + sum, 25, 25 );
}
// TODO overwrite start(), stop() and destroy() methods
}
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
44
Screenshot:
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
45
Working with AWT Control Components:
Java provides the AWT control components, which contain classes that enables us to create standard
components such as buttons, labels and text field in Java.
Various AWT Components:
Some of the AWT component classes are,
 TextField
 TextArea
 Button
 List
 CheckBox
 Choice
 Label
Working with Swing Components:
Swing components also provide GUI environment to Java in addition to applet. Swing components
are the collection of lightweight visual component that provide a replacement for heavy weight AWT
components.
Identifying the Swing Component Class Hierarchy:
The JComponents class is the root of the Swing hierarchy. The class hierarchy of the Swing
components is categorized into:
1. Top-level swing containers: It act as a container for placing the intermediate-level and atomic
components, such as panels, buttons, checkbox.
a. JFrame
b. JApplet
c. JDialog
2. Intermediate-level swing container: It placed on top-level container and contains atomic
components, such as buttons, checkbox and labels.
a. JPanel
b. JtabbedPane
c. JScrollPane
d. JToolBar
3. Atomic components: It placed on the intermediate-level swing container. Atomic components are
used to accept input from a user.
a. JTextField
b. JButton
c. JCheckBox
d. JLabel
e. JTable
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
46
Steps to create and work with JFrame using NetBean IDE:
1. File->New Project
2. New Project dialog box will appear
3. In Categories click Java, in Projects click Java Application and click Next
4. Give Project Name, uncheck the Create Main Class and click Finish
5. Project created. Right Click in the project in the Project Explorer tab
6. New->JFrame Form
7. New JFrame Form will appear
8. Give Class Name and click Finish
9. An empty JFrame is created
10. We can find Palette Explorer in Right side of the NetBean IDE. If not go to
Window ->Palette or Ctrl+Shift+8
11. Drag and Drop needed components to the Frame
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
47
12. To change the JLabel name or to resize the component. We can find Properties
Explorer in Right side of the NetBean IDE. If not go to Window ->Properties or
Ctrl+Shift+7
13. To view the Frame actual visible. Click Preview Design
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
48
PRE LAB EXERCISE
a. Draw any one smiley you known in JApplet
b. Create a Register form GUI for School Administration purpose using JFrame
IN LAB EXERCISE
a. An analysis of examination result at a school gave the following distribution of grades for all
subject taken in the year:
Grade Percentage
A 10
B 25
C 45
D 60
E 85
Write a Java program to represent the distribution of each grade in bar char
b. Create a Calculator GUI using JFrame
POST LAB EXERCISE
a. Draw a 3D rectangle without using Graphics method in JApplet
b. Create a Notepad GUI using JFrame
Result:
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
49
9 EVENT-HANDLING
OBJECTIVE:
Detailed study on Event classes in java
OVERVIEW:
Event:
An object that describes a state of change in a source component is called an event. In Java, events
are supported by the classes and interfaces defined in the java.awt.event package.
Event Classes:
Event Handling Classes and Methods
ActionListener actionPerformed(ActionEvent) addActionListener()
AdjustmentListener adjustmentValueChanged(Adjustment
Event)
addAdjustmentListener(
)
ComponentListener componentHidden(ComponentEvent)
componentMoved(ComponentEvent)
componentResized(ComponentEvent)
componentShown(ComponentEvent)
addComponentListener(
)
ContainerListener componentAdded(ContainerEvent)
componetRemoved(ContainerEvent)
addContainerListener()
Java.util.EventObject
Java.util.AWTEvent
ItemEvent
Adjustment
Event
FocusEvent
Component
Event
ContainerEv
ent
FocusEvent InputEvent
MouseEvent KeyEvent
PaintEvent
WindowEve
nt
ActionEvent TextEvent
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
50
FocusListener focusGained(FocusEvent)
focusLost(FocusEvent)
addFocusListener()
ItemListener itemStateChanged(ItemEvent) addItemListener()
KeyListener keyPressed(KeyEvent)
keyReleased(KeyEvent)
keyTyped(KeyEvent)
addKeyListener()
MouseListener mouseClicked(MouseEvent)
mouseEntered(MouseEvent)
mouseExited(MouseEvent)
mousePressed(MouseEvent)
mouseReleased(MouseEvent)
addMouseListener()
MouseMotionListene
r
mouseDragged(MouseEvent)
mouseMoved(MouseEvent)
addMouseMotionListen
er()
TextListener textValueChanged(TextEvent) addTextListener()
WindowListener windowActivated(WindowEvent)
windowClosed(WindowEvent)
windowClosing(WindowEvent)
windowDeactivated(WindowEvent)
windowDeiconified(WindowEvent)
windowIconified(WindowEvent)
windowOpened(WindowEvent)
addWindowListener()
Steps to work with Event handling in NetBean IDE:
 Open a NewJFrame, class name is Fifteenth and drag necessary components
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
51
 For above example, We going to perform ActionEvent on jButton1 (Login)
 Right click on the button, click Event->Action->actionPerformed[jButton1ActionPerformed]
 private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) method created in the
Fiveteenth.java file. We can view that method by clicking source tab.
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
52
 Write the following code in the private void
jButton1ActionPerformed(java.awt.event.ActionEvent evt) method,
 Run the program
When we give the Username and
Password field matches to the if
condition in program
When we give the Username and
Password field mismatch to the if
condition in program
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
53
PRE LAB EXERCISE
a. Create a Register form for School Administration purpose using JFrame and If the details were
entered click Register button. If the Register button is clicked, display the given options in next
Frame
IN LAB EXERCISE
a. Create a Scientific Calculator using JFrame (Use standard Math methods for calculation)
b. Rotate a compass needle on the screen about a fixed point in response to the mouse being moved
around the screen.
POST LAB EXERCISE
a. Create a JFrame (as shown below) to access the FileChooser to select file. After selecting the file
the content of the file displayed in the JTextArea.
Result:
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
54
10 MULTITHREADING
OBJECTIVE:
Creating Thread and demonstrate Multithreading concept
OVERVIEW:
Thread:
A thread can be defined as the single sequential flow of control within the program. It is a
sequence of instruction that is executed to define a unique flow of control. For example: A CPU performs
various process simultaneously, such as writing and printing a document, installing a software, and
displaying the date and time on status bar.
The process that is made of one thread is known as single-threaded process. A process that
creates two or more threads is called a multi-thread process. For example: Any Web browser, such as
Microsoft Edge, is a multi-threaded application.
Every Java program uses threads:
Every Java program has at least one thread i.e. main thread. When a Java program starts, the
JVM creates the main thread and call the program main() method within that thread. The JVM also creates
other threads that are mostly invisible to us. For example: Threads associate with garbage collection,
object finalization, and other JVM housekeeping tasks. Other facilities create threads too, such as the
AWT or Awing UI toolkits, servlet containers, application servers and RMI(Remote Method Invocation).
Benefits of Multithreading:
 Improved performance
 Minimized system resource usage
 Simultaneous access to multiple application
 Program structure simplification
Pitfalls of Multithreading:
 Race Condition
 Deadlock Condition
 Lock Starvation
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
55
Life Cycle of a Thread:
The various states in the life cycle of the thread are:
 New
 Runnable
 Not Runnable
 Terminate or Dead
The following figure shows the life cycle of a thread.
Creating Thread:
We create thread by instantiating an object of the Thread class. We can create a thread in the
following ways,
1. Implementing the Runnable interface
2. Extending the Thread class
Creating Thread by implementing the Runnable Interface:
If Applet extends the Applet class. Since Java does not support multiple inheritance, we cannot
inherit both Applet and Thread. So, Java provide us Runnable Interface.
Terminate
New Thread
Created
Suspended
RunnableSleeping
resume( ) run( ) suspend( )
sleep( )
timeout( )
stop( )
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
56
Sample coding:
/**
*
* @author NaveenSagayaselvaRaj
*/
import java.util.logging.Level;
import java.util.logging.Logger;
class Sixteenth1 implements Runnable{
Sixteenth1()
{
Thread t = new Thread(this,"mythread");
t.start();
}
@Override
public void run() {
System.out.println("Child class");
}
}
class Sixteenth2{
public static void main(String arg[])
{
new Sixteenth1();
System.out.println("Main class");
try {
Thread.sleep(20);
} catch (InterruptedException ex) {
Logger.getLogger(Sixteenth2.class.getName()).log(Level.SEVERE, null,
ex);
}
}
}
Output:
run:
Main class
Child class
BUILD SUCCESSFUL (total time: 2 seconds)
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
57
Sample coding:
/**
*
* @author NaveenSagayaselvaRaj
*/
import java.util.logging.Level;
import java.util.logging.Logger;
class Seventeenth1 extends Thread{
Seventeenth1()
{
Thread t = new Thread(this,"mythread");
t.start();
}
@Override
public void run() {
System.out.println("Child class");
}
}
class Seventeenth1{
public static void main(String arg[])
{
new Seventeenth1();
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
Logger.getLogger(Sixteenth2.class.getName()).log(Level.SEVERE, null,
ex);
}
System.out.println("Main class");
}
}
Output:
run:
Child class
Main class
BUILD SUCCESSFUL (total time: 2 seconds)
PRE LAB EXERCISE
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
58
*******************************NILL************************************
IN LAB EXERCISE
a. Illustrate Multi-Thread concept with suitable example
POST LAB EXERCISE
*******************************NILL************************************
Result:
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
59
11 NETWORKING-I
OBJECTIVE:
Java Programming on basic networking protocols
OVERVIEW:
Introduction:
One of the important features of java are networking support. Java provides fundamental
networking capabilities through java.net package.
OSI layers:
Communication between computers in network
Layer 7: Application Layer
 Defines interface to user processes for communication and data transfer in network
 Provides standardized services such as virtual terminal, file and job transfer and operations
Layer 6: Presentation Layer
 Masks the differences of data formats between dissimilar systems
 Specifies architecture-independent data transfer format
 Encodes and decodes data; encrypts and decrypts data; compresses and decompresses data
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
60
Layer 5: Session Layer
 Manages user sessions and dialogues
 Controls establishment and termination of logic links between users
 Reports upper layer errors
Layer 4: Transport Layer
 Manages end-to-end message delivery in network
 Provides reliable and sequential packet delivery through error recovery and flow control
mechanisms
 Provides connectionless oriented packet delivery
Layer 3: Network Layer
 Determines how data are transferred between network devices
 Routes packets according to unique network device addresses
 Provides flow and congestion control to prevent network resource depletion
Layer 2: Data Link Layer
 Defines procedures for operating the communication links
 Frames packets
 Detects and corrects packets transmit errors
Layer 1: Physical Layer
 Defines physical means of sending data over network devices
 Interfaces between network medium and devices
 Defines optical, electrical and mechanical characteristics
Protocol:
A protocol is a set of rules and standard for communication. A network protocol specifies the
format of data being sent over the network, along with necessary details. The important protocols used in
the Internet are:
1. IP(Internet Protocol):
Internet Protocol is a network layer protocol that breaks the data into packets and sent
them using IP address.
2. TCP(Transmission Control Protocol):
It is a used for connection oriented communication between two applications on two
different machines.
3. UDP(User Datagram Protocol):
It is a used for connectionless oriented communication between two applications on two
different machines.
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
61
Internet Address:
An Internet address uniquely identifies a node on the Internet. Internet address may also refer to
the name or IP of a Web site (URL). The term Internet address can also represent someone's e-mail
address
InetAddress class in Java:
It is a class in Java which represents an Internet Protocol (IP) address. An instance of an InetAddress
consists of an IP address and possibly corresponding hostname.
The Class represents an Internet address as Two fields:
1. Host name (The String)=Contain the name of the Host.
2. Address(an int)= The 32 bit IP address.
These fields are not public, so we can’t Access them directly. There is not public constructor in InetAddress
class, but it has 3 static methods that returns suitably initialized InetAddress. Objects namely Public String
getHostName() , public byte[] getAddress() and public String getHostAddress()
Methods Description
boolean equals(Object obj) Compares this object against the
specified object.
byte[] getAddress() Returns the raw IP address of this
InetAddress object.
static InetAddress[]getAllByName(String host) Given the name of a host, returns an
array of its IP addresses, based on the
configured name service on the system.
static InetAddress getByAddress(byte[] addr) Returns an InetAddress object given the
raw IP address.
static InetAddress getByAddress(String host,
byte[] addr)
Creates an InetAddress based on the
provided host name and IP address.
static InetAddress getByName(String host) Determines the IP address of a host,
given the host's name.
String getCanonicalHostName() Gets the fully qualified domain name for
this IP address.
String getHostAddress() Returns the IP address string in textual
Presentation.
String getHostName() Gets the host name for this IP address.
static InetAddress getLocalHost() Returns the address of the local host.
static InetAddress getLoopbackAddress() Returns the loopback address.
Int hashCode() Returns a hashcode for this IP address.
boolean isAnyLocalAddress() Utility routine to check if the
InetAddress in a wildcard address.
boolean isLinkLocalAddress() Utility routine to check if the
InetAddress is an link local address.
boolean isLoopbackAddress() Utility routine to check if the
InetAddress is a loopback address.
boolean isMCGlobal() Utility routine to check if the multicast
address has global scope.
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
62
boolean isMCLinkLocal() Utility routine to check if the multicast
address has link scope.
boolean isMCNodeLocal() Utility routine to check if the multicast
address has node scope.
boolean isMCOrgLocal() Utility routine to check if the multicast
address has organization scope.
boolean isMCSiteLocal() Utility routine to check if the multicast
address has site scope.
boolean isMulticastAddress() Utility routine to check if the
InetAddress is an IP multicast address.
boolean isReachable(int timeout) Test whether that address is reachable.
boolean isReachable(NetworkInterface netif, int ttl,
int timeout)
Test whether that address is reachable.
boolean isSiteLocalAddress() Utility routine to check if the
InetAddress is a site local address.
String toString() Converts this IP address to a String.
Sample coding:
To print IP address of LocalHost:
/**
*
* @author NaveenSagayaselvaRaj
*/
public class Eighteenth_Program {
public static void main(String arg[])
{
try
{
InetAddress IPO=InetAddress.getLocalHost();
System.out.println("IP of this system= "+IPO.getHostAddress());
}
catch(Exception e)
{
System.err.println("Exception: "+e.getMessage());
}
}
}
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
63
Output:
run:
IP of this system= 127.0.0.1
BUILD SUCCESSFUL (total time: 0 seconds)
TCP (Transmission Control Protocol):
Creating TCP Servers:
To create a TCP server, do the following:
1. Create a ServerSocket attached to a port number.
ServerSocket server = new ServerSocket(port);
2. Wait for connections from clients requesting connections to that port.
// Block on accept()
Socket channel = server.accept();
We get a Socket object as a result of the connection.
3. Get input and output streams associated with the socket.
out = new PrintWriter (channel.getOutputStream());
reader = new InputStreamReader (channel.getInputStream());
in = new BufferedReader (reader);
Now you can read and write to the socket, thus, communicating with the client.
String data = in.readLine();
out.println("Welcome!!");
When a server invokes the accept() method of the ServerSocket instance, the main server thread
blocks until a client connects to the server; it is then prevented from accepting further client connections
until the server has processed the client's request. This is known as an iterative server, since the main
server method handles each client request in its entirety before moving on to the next request. Iterative
servers are good when the requests take a known, short period of time. For example, requesting the current
day and time from a time-of-day server.
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
64
Creating TCP Clients:
To create a TCP client, do the following:
1. Create a Socket object attached to a remote host, port.
Socket client = new Socket(host, port);
When the constructor returns, you have a connection.
2. Get input and output streams associated with the socket.
out = new PrintWriter (client.getOutputStream());
reader = new InputStreamReader (client.getInputStream());
in = new BufferedReader (reader);
Now you can read and write to the socket, thus, communicating with the server.
out.println("Hi!! This is me your client");
String data = in.readLine();
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
65
Sample coding:
Implementation of Client Server Communication Using TCP
CliTCP:
/**
*
* @author NaveenSagayaselvaRaj
*/
import java.lang.*;
import java.net.*;
import java.io.*;
class CliTCP
{
public static void main(String args[]) throws UnknownHostException
{
try {
Socket skt=new Socket("",1234);
BufferedReader in=new BufferedReader(new
InputStreamReader(skt.getInputStream()));
System.out.println("Received string:");
while(!in.ready()) {}
System.out.println(in.readLine());
System.out.println("n"); in.close();
}
catch(Exception e) {
System.out.println("Whoops! It didn't work! n");
}
}
}
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
66
SerTCP:
/**
*
* @author NaveenSagayaselvaRaj
*/
import java.lang.*; import java.net.*; import java.io.*;
class SerTCP
{
public static void main(String args[])
{
String data="Welcome";
try {
ServerSocket s=new ServerSocket(1234);
Socket skt=s.accept();
System.out.println("Server has connected! n");
PrintWriter out=new PrintWriter(skt.getOutputStream(),true);
System.out.println("Sending string: n "+data+"n");
out.print(data);
out.close();
skt.close();
s.close();
}
catch(Exception e)
{
System.out.println("Whoops! It didn't work! n");
}
}
}
Output:
Clientside:
run:
Received string:
Welcome
BUILD SUCCESSFUL (total time: 2 seconds)
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
67
Serverside:
run:
Server has connected!
Sending string:
Welcome
BUILD SUCCESSFUL (total time: 2 seconds)
PRE LAB EXERCISE
a. Write a Java Program to print MAC address of the local host
IN LAB EXERCISE
a. Create a Simple Chat Application using TCP
b. Create a Simple Game Application using TCP
POST LAB EXERCISE
a. Create a Simple Chat Application using TCP (Note: Create JFrames Application)
Result:
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
68
12 NETWORKING-II
OBJECTIVE:
Java Programming on basic networking protocols
OVERVIEW:
UDP (User Datagram Protocol):
Creating UDP Servers:
To create a server with UDP, do the following:
1. Create a DatagramSocket attached to a port.
int port = 1234;
DatagramSocket socket = new DatagramSocket(port);
2. Allocate space to hold the incoming packet, and create an instance of DatagramPacket to
hold the incoming data.
byte[] buffer = new byte[1024];
DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
3. Block until a packet is received, then extract the information you need from the packet.
// Block on receive()
socket.receive(packet);
// Find out where packet came from
// so we can reply to the same host/port
InetAddress remoteHost = packet.getAddress();
int remotePort = packet.getPort();
// Extract the packet data byte[] data = packet.getData();
The server can now process the data it has received from the client, and issue an appropriate
reply in response to the client's request.
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
69
Creating UDP Client:
Writing code for a UDP client is similar to what we did for a server. Again, we need a DatagramSocket and
a DatagramPacket. The only real difference is that we must specify the destination address with each
packet, so the form of the DatagramPacket constructor used here specifies the destination host and port
number. Then, of course, we initially send packets instead of receiving.
1. First allocate space to hold the data we are sending and create an instance of DatagramPacket to
hold the data.
byte[] buffer = new byte[1024];
int port = 1234;
InetAddress host = InetAddress.getByName("magelang.com");
DatagramPacket packet = new DatagramPacket(buffer, buffer.length, host, port);
2. Create a DatagramSocket and send the packet using this socket.
DatagramSocket socket = new DatagramSocket();
socket.send(packet);
The DatagramSocket constructor that takes no arguments will allocate a free local port to use.
You can find out what local port number has been allocated for your socket, along with other information
about your socket if needed.
// Find out where we are sending from InetAddress localHostname = socket.getLocalAddress();
int localPort = socket.getLocalPort();
The client then waits for a reply from the server. Many protocols require the server to reply to the
host and port number that the client used, so the client can now invoke socket.receive() to wait for
information from the server.
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
70
Sample coding:
Implementation of socket program for UDP Echo Client and Echo Server:
CliUDP:
/**
*
* @author NaveenSagayaselvaRaj
*/
import java.net.*;
import java.io.*;
import java.lang.*;
public class CliUDP {
public static void main(String args[])throws IOException {
byte[] buff=new byte[1024];
DatagramSocket soc=new DatagramSocket(9999);
String s="From client-Hello Server";
buff=s.getBytes();
InetAddress a=InetAddress.getLocalHost();
DatagramPacket pac=new DatagramPacket(buff,buff.length,a,8888);
soc.send(pac);
System.out.println("End of sending");
byte[] buff1=new byte[1024];
buff1=s.getBytes();
pac=new DatagramPacket(buff1,buff1.length);
soc.receive(pac);
String msg=new String(pac.getData());
System.out.println(msg);
System.out.println("End of programming");
}
}
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
71
SerUDP:
/**
*
* @author NaveenSagayaselvaRaj
*/
import java.net.*;
import java.io.*;
import java.lang.*;
public class ES {
public static void main(String args[])throws IOException {
byte[] buff=new byte[512];
DatagramSocket soc=new DatagramSocket(8888);
DatagramPacket pac=new DatagramPacket(buff,buff.length );
System.out.println("server started");
soc.receive(pac);
String msg=new String(pac.getData());
System.out.println(msg);
System.out.println("End of reception");
String s="From Server-Hello client";
byte[] buff1=new byte[512];
buff1=s.getBytes();
InetAddress a=pac.getAddress();
int port=pac.getPort();
pac=new DatagramPacket(buff,buff1.length,a,port);
soc.send(pac);
System.out.println("End of sending");
}
}
Output:
Clientside:
run:
End of sending
From client-Hello Server
End of programming
BUILD SUCCESSFUL (total time: 2 seconds)
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
72
ServerSide:
run:
server started
From client-Hello Server
End of reception
End of sending
BUILD SUCCESSFUL (total time: 2 seconds)
PRE LAB EXERCISE
a. Design UDP Client and Server application to reverse the given input sentence.
IN LAB EXERCISE
a. Design UDP Client Server to transfer a file
POST LAB EXERCISE
*******************************NILL************************************
Result:
naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ
1
Contact Person1:
Mr. Naveen Sagayaselvaraj
Email ID:
naveensagayaselvaraj@gmail.com
Website:
https://sites.google.com/site/naveensagayaselvaraj/
Contact Person2:
Ms. Mangaiyarkkarasi V
Email ID: v.mangai.2010@gmail.com

Weitere ähnliche Inhalte

Was ist angesagt?

Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical FileSoumya Behera
 
Advanced Java - Praticals
Advanced Java - PraticalsAdvanced Java - Praticals
Advanced Java - PraticalsFahad Shaikh
 
Java Simple Programs
Java Simple ProgramsJava Simple Programs
Java Simple ProgramsUpender Upr
 
Cs2312 OOPS LAB MANUAL
Cs2312 OOPS LAB MANUALCs2312 OOPS LAB MANUAL
Cs2312 OOPS LAB MANUALPrabhu D
 
Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.Nishan Barot
 
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMMario Fusco
 
Java Programs
Java ProgramsJava Programs
Java Programsvvpadhu
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondMario Fusco
 
Advanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesAdvanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesGanesh Samarthyam
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Mario Fusco
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modelingMario Fusco
 
OOP and FP - Become a Better Programmer
OOP and FP - Become a Better ProgrammerOOP and FP - Become a Better Programmer
OOP and FP - Become a Better ProgrammerMario Fusco
 
If You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongIf You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongMario Fusco
 

Was ist angesagt? (20)

Advanced Java Practical File
Advanced Java Practical FileAdvanced Java Practical File
Advanced Java Practical File
 
Advanced Java - Praticals
Advanced Java - PraticalsAdvanced Java - Praticals
Advanced Java - Praticals
 
Simple Java Programs
Simple Java ProgramsSimple Java Programs
Simple Java Programs
 
Java programming-examples
Java programming-examplesJava programming-examples
Java programming-examples
 
Java codes
Java codesJava codes
Java codes
 
Java Simple Programs
Java Simple ProgramsJava Simple Programs
Java Simple Programs
 
Cs2312 OOPS LAB MANUAL
Cs2312 OOPS LAB MANUALCs2312 OOPS LAB MANUAL
Cs2312 OOPS LAB MANUAL
 
Java Fundamentals
Java FundamentalsJava Fundamentals
Java Fundamentals
 
Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.
 
Class method
Class methodClass method
Class method
 
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STMConcurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
Concurrency, Scalability & Fault-tolerance 2.0 with Akka Actors & STM
 
Java Programs
Java ProgramsJava Programs
Java Programs
 
Kotlin
KotlinKotlin
Kotlin
 
Java programs
Java programsJava programs
Java programs
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
 
Advanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesAdvanced Debugging Using Java Bytecodes
Advanced Debugging Using Java Bytecodes
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
 
OOP and FP - Become a Better Programmer
OOP and FP - Become a Better ProgrammerOOP and FP - Become a Better Programmer
OOP and FP - Become a Better Programmer
 
If You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are WrongIf You Think You Can Stay Away from Functional Programming, You Are Wrong
If You Think You Can Stay Away from Functional Programming, You Are Wrong
 

Andere mochten auch

tL20 event handling
tL20 event handlingtL20 event handling
tL20 event handlingteach4uin
 
Webdesing lab part-b__java_script_
Webdesing lab part-b__java_script_Webdesing lab part-b__java_script_
Webdesing lab part-b__java_script_Shivanand Algundi
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in javaGoogle
 
Java J2EE Interview Questions Part-1
Java J2EE Interview Questions Part-1Java J2EE Interview Questions Part-1
Java J2EE Interview Questions Part-1javatrainingonline
 
TKP Java Notes for Teaching Kids Programming
TKP Java Notes for Teaching Kids ProgrammingTKP Java Notes for Teaching Kids Programming
TKP Java Notes for Teaching Kids ProgrammingLynn Langit
 
Fal-e-Hafez (Omens of Hafez) Cards in Persian using Java
Fal-e-Hafez (Omens of Hafez) Cards in Persian using JavaFal-e-Hafez (Omens of Hafez) Cards in Persian using Java
Fal-e-Hafez (Omens of Hafez) Cards in Persian using JavaOXUS 20
 
Conditional Statement
Conditional Statement Conditional Statement
Conditional Statement OXUS 20
 
Java Regular Expression PART II
Java Regular Expression PART IIJava Regular Expression PART II
Java Regular Expression PART IIOXUS 20
 
Java Regular Expression PART I
Java Regular Expression PART IJava Regular Expression PART I
Java Regular Expression PART IOXUS 20
 
Everything about Object Oriented Programming
Everything about Object Oriented ProgrammingEverything about Object Oriented Programming
Everything about Object Oriented ProgrammingAbdul Rahman Sherzad
 
PHP Basic and Fundamental Questions and Answers with Detail Explanation
PHP Basic and Fundamental Questions and Answers with Detail ExplanationPHP Basic and Fundamental Questions and Answers with Detail Explanation
PHP Basic and Fundamental Questions and Answers with Detail ExplanationOXUS 20
 
Java Applet and Graphics
Java Applet and GraphicsJava Applet and Graphics
Java Applet and GraphicsOXUS 20
 
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton ClassesJava Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton ClassesOXUS 20
 
Java Unicode with Cool GUI Examples
Java Unicode with Cool GUI ExamplesJava Unicode with Cool GUI Examples
Java Unicode with Cool GUI ExamplesOXUS 20
 
Object Oriented Concept Static vs. Non Static
Object Oriented Concept Static vs. Non StaticObject Oriented Concept Static vs. Non Static
Object Oriented Concept Static vs. Non StaticOXUS 20
 
Structure programming – Java Programming – Theory
Structure programming – Java Programming – TheoryStructure programming – Java Programming – Theory
Structure programming – Java Programming – TheoryOXUS 20
 

Andere mochten auch (16)

tL20 event handling
tL20 event handlingtL20 event handling
tL20 event handling
 
Webdesing lab part-b__java_script_
Webdesing lab part-b__java_script_Webdesing lab part-b__java_script_
Webdesing lab part-b__java_script_
 
Event Handling in java
Event Handling in javaEvent Handling in java
Event Handling in java
 
Java J2EE Interview Questions Part-1
Java J2EE Interview Questions Part-1Java J2EE Interview Questions Part-1
Java J2EE Interview Questions Part-1
 
TKP Java Notes for Teaching Kids Programming
TKP Java Notes for Teaching Kids ProgrammingTKP Java Notes for Teaching Kids Programming
TKP Java Notes for Teaching Kids Programming
 
Fal-e-Hafez (Omens of Hafez) Cards in Persian using Java
Fal-e-Hafez (Omens of Hafez) Cards in Persian using JavaFal-e-Hafez (Omens of Hafez) Cards in Persian using Java
Fal-e-Hafez (Omens of Hafez) Cards in Persian using Java
 
Conditional Statement
Conditional Statement Conditional Statement
Conditional Statement
 
Java Regular Expression PART II
Java Regular Expression PART IIJava Regular Expression PART II
Java Regular Expression PART II
 
Java Regular Expression PART I
Java Regular Expression PART IJava Regular Expression PART I
Java Regular Expression PART I
 
Everything about Object Oriented Programming
Everything about Object Oriented ProgrammingEverything about Object Oriented Programming
Everything about Object Oriented Programming
 
PHP Basic and Fundamental Questions and Answers with Detail Explanation
PHP Basic and Fundamental Questions and Answers with Detail ExplanationPHP Basic and Fundamental Questions and Answers with Detail Explanation
PHP Basic and Fundamental Questions and Answers with Detail Explanation
 
Java Applet and Graphics
Java Applet and GraphicsJava Applet and Graphics
Java Applet and Graphics
 
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton ClassesJava Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
Java Virtual Keyboard Using Robot, Toolkit and JToggleButton Classes
 
Java Unicode with Cool GUI Examples
Java Unicode with Cool GUI ExamplesJava Unicode with Cool GUI Examples
Java Unicode with Cool GUI Examples
 
Object Oriented Concept Static vs. Non Static
Object Oriented Concept Static vs. Non StaticObject Oriented Concept Static vs. Non Static
Object Oriented Concept Static vs. Non Static
 
Structure programming – Java Programming – Theory
Structure programming – Java Programming – TheoryStructure programming – Java Programming – Theory
Structure programming – Java Programming – Theory
 

Ähnlich wie Java Lab Manual

Object Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsObject Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsMuhammadTalha436
 
4CS4-25-Java-Lab-Manual.pdf
4CS4-25-Java-Lab-Manual.pdf4CS4-25-Java-Lab-Manual.pdf
4CS4-25-Java-Lab-Manual.pdfamitbhachne
 
Assignment Java Programming 2
Assignment Java Programming 2Assignment Java Programming 2
Assignment Java Programming 2Kaela Johnson
 
classes object fgfhdfgfdgfgfgfgfdoop.pptx
classes object  fgfhdfgfdgfgfgfgfdoop.pptxclasses object  fgfhdfgfdgfgfgfgfdoop.pptx
classes object fgfhdfgfdgfgfgfgfdoop.pptxarjun431527
 
Java practical(baca sem v)
Java practical(baca sem v)Java practical(baca sem v)
Java practical(baca sem v)mehul patel
 
Interface and abstraction
Interface and abstractionInterface and abstraction
Interface and abstractionRaghav Chhabra
 
JavaScript(Es5) Interview Questions & Answers
JavaScript(Es5)  Interview Questions & AnswersJavaScript(Es5)  Interview Questions & Answers
JavaScript(Es5) Interview Questions & AnswersRatnala Charan kumar
 
What’s new in .NET
What’s new in .NETWhat’s new in .NET
What’s new in .NETDoommaker
 
Objectives Assignment 09 Applications of Stacks COS.docx
Objectives Assignment 09 Applications of Stacks COS.docxObjectives Assignment 09 Applications of Stacks COS.docx
Objectives Assignment 09 Applications of Stacks COS.docxdunhamadell
 
Programming in Java: Why Object-Orientation?
Programming in Java: Why Object-Orientation?Programming in Java: Why Object-Orientation?
Programming in Java: Why Object-Orientation?Martin Chapman
 
CSE215_Module_02_Elementary_Programming.ppt
CSE215_Module_02_Elementary_Programming.pptCSE215_Module_02_Elementary_Programming.ppt
CSE215_Module_02_Elementary_Programming.pptRashedurRahman18
 
SystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummarySystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummaryAmal Khailtash
 
05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and ClassesIntro C# Book
 
c#(loops,arrays)
c#(loops,arrays)c#(loops,arrays)
c#(loops,arrays)sdrhr
 

Ähnlich wie Java Lab Manual (20)

JavaProgrammingManual
JavaProgrammingManualJavaProgrammingManual
JavaProgrammingManual
 
Object Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ ExamsObject Oriented Solved Practice Programs C++ Exams
Object Oriented Solved Practice Programs C++ Exams
 
4CS4-25-Java-Lab-Manual.pdf
4CS4-25-Java-Lab-Manual.pdf4CS4-25-Java-Lab-Manual.pdf
4CS4-25-Java-Lab-Manual.pdf
 
Assignment Java Programming 2
Assignment Java Programming 2Assignment Java Programming 2
Assignment Java Programming 2
 
Java final lab
Java final labJava final lab
Java final lab
 
classes object fgfhdfgfdgfgfgfgfdoop.pptx
classes object  fgfhdfgfdgfgfgfgfdoop.pptxclasses object  fgfhdfgfdgfgfgfgfdoop.pptx
classes object fgfhdfgfdgfgfgfgfdoop.pptx
 
00_Introduction to Java.ppt
00_Introduction to Java.ppt00_Introduction to Java.ppt
00_Introduction to Java.ppt
 
Java practical(baca sem v)
Java practical(baca sem v)Java practical(baca sem v)
Java practical(baca sem v)
 
JAVA CONCEPTS
JAVA CONCEPTS JAVA CONCEPTS
JAVA CONCEPTS
 
Interface and abstraction
Interface and abstractionInterface and abstraction
Interface and abstraction
 
JavaScript(Es5) Interview Questions & Answers
JavaScript(Es5)  Interview Questions & AnswersJavaScript(Es5)  Interview Questions & Answers
JavaScript(Es5) Interview Questions & Answers
 
C#2
C#2C#2
C#2
 
What’s new in .NET
What’s new in .NETWhat’s new in .NET
What’s new in .NET
 
Objectives Assignment 09 Applications of Stacks COS.docx
Objectives Assignment 09 Applications of Stacks COS.docxObjectives Assignment 09 Applications of Stacks COS.docx
Objectives Assignment 09 Applications of Stacks COS.docx
 
Programming in Java: Why Object-Orientation?
Programming in Java: Why Object-Orientation?Programming in Java: Why Object-Orientation?
Programming in Java: Why Object-Orientation?
 
CSE215_Module_02_Elementary_Programming.ppt
CSE215_Module_02_Elementary_Programming.pptCSE215_Module_02_Elementary_Programming.ppt
CSE215_Module_02_Elementary_Programming.ppt
 
SystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features SummarySystemVerilog OOP Ovm Features Summary
SystemVerilog OOP Ovm Features Summary
 
05. Java Loops Methods and Classes
05. Java Loops Methods and Classes05. Java Loops Methods and Classes
05. Java Loops Methods and Classes
 
c#(loops,arrays)
c#(loops,arrays)c#(loops,arrays)
c#(loops,arrays)
 
190030341 fcp lab 1
190030341  fcp lab 1190030341  fcp lab 1
190030341 fcp lab 1
 

Kürzlich hochgeladen

US Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of ActionUS Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of ActionMebane Rash
 
Input Output Management in Operating System
Input Output Management in Operating SystemInput Output Management in Operating System
Input Output Management in Operating SystemRashmi Bhat
 
home automation using Arduino by Aditya Prasad
home automation using Arduino by Aditya Prasadhome automation using Arduino by Aditya Prasad
home automation using Arduino by Aditya Prasadaditya806802
 
Virtual memory management in Operating System
Virtual memory management in Operating SystemVirtual memory management in Operating System
Virtual memory management in Operating SystemRashmi Bhat
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...asadnawaz62
 
Vishratwadi & Ghorpadi Bridge Tender documents
Vishratwadi & Ghorpadi Bridge Tender documentsVishratwadi & Ghorpadi Bridge Tender documents
Vishratwadi & Ghorpadi Bridge Tender documentsSachinPawar510423
 
National Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdfNational Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdfRajuKanojiya4
 
Earthing details of Electrical Substation
Earthing details of Electrical SubstationEarthing details of Electrical Substation
Earthing details of Electrical Substationstephanwindworld
 
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor CatchersTechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catcherssdickerson1
 
Energy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptxEnergy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptxsiddharthjain2303
 
The SRE Report 2024 - Great Findings for the teams
The SRE Report 2024 - Great Findings for the teamsThe SRE Report 2024 - Great Findings for the teams
The SRE Report 2024 - Great Findings for the teamsDILIPKUMARMONDAL6
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfROCENODodongVILLACER
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHC Sai Kiran
 
Work Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvWork Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvLewisJB
 
NO1 Certified Black Magic Specialist Expert Amil baba in Uae Dubai Abu Dhabi ...
NO1 Certified Black Magic Specialist Expert Amil baba in Uae Dubai Abu Dhabi ...NO1 Certified Black Magic Specialist Expert Amil baba in Uae Dubai Abu Dhabi ...
NO1 Certified Black Magic Specialist Expert Amil baba in Uae Dubai Abu Dhabi ...Amil Baba Dawood bangali
 
Industrial Safety Unit-I SAFETY TERMINOLOGIES
Industrial Safety Unit-I SAFETY TERMINOLOGIESIndustrial Safety Unit-I SAFETY TERMINOLOGIES
Industrial Safety Unit-I SAFETY TERMINOLOGIESNarmatha D
 
Transport layer issues and challenges - Guide
Transport layer issues and challenges - GuideTransport layer issues and challenges - Guide
Transport layer issues and challenges - GuideGOPINATHS437943
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxk795866
 

Kürzlich hochgeladen (20)

US Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of ActionUS Department of Education FAFSA Week of Action
US Department of Education FAFSA Week of Action
 
Input Output Management in Operating System
Input Output Management in Operating SystemInput Output Management in Operating System
Input Output Management in Operating System
 
home automation using Arduino by Aditya Prasad
home automation using Arduino by Aditya Prasadhome automation using Arduino by Aditya Prasad
home automation using Arduino by Aditya Prasad
 
Virtual memory management in Operating System
Virtual memory management in Operating SystemVirtual memory management in Operating System
Virtual memory management in Operating System
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...
 
Vishratwadi & Ghorpadi Bridge Tender documents
Vishratwadi & Ghorpadi Bridge Tender documentsVishratwadi & Ghorpadi Bridge Tender documents
Vishratwadi & Ghorpadi Bridge Tender documents
 
National Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdfNational Level Hackathon Participation Certificate.pdf
National Level Hackathon Participation Certificate.pdf
 
Earthing details of Electrical Substation
Earthing details of Electrical SubstationEarthing details of Electrical Substation
Earthing details of Electrical Substation
 
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor CatchersTechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
 
Energy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptxEnergy Awareness training ppt for manufacturing process.pptx
Energy Awareness training ppt for manufacturing process.pptx
 
The SRE Report 2024 - Great Findings for the teams
The SRE Report 2024 - Great Findings for the teamsThe SRE Report 2024 - Great Findings for the teams
The SRE Report 2024 - Great Findings for the teams
 
Risk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdfRisk Assessment For Installation of Drainage Pipes.pdf
Risk Assessment For Installation of Drainage Pipes.pdf
 
Introduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECHIntroduction to Machine Learning Unit-3 for II MECH
Introduction to Machine Learning Unit-3 for II MECH
 
Work Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvWork Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvv
 
NO1 Certified Black Magic Specialist Expert Amil baba in Uae Dubai Abu Dhabi ...
NO1 Certified Black Magic Specialist Expert Amil baba in Uae Dubai Abu Dhabi ...NO1 Certified Black Magic Specialist Expert Amil baba in Uae Dubai Abu Dhabi ...
NO1 Certified Black Magic Specialist Expert Amil baba in Uae Dubai Abu Dhabi ...
 
Industrial Safety Unit-I SAFETY TERMINOLOGIES
Industrial Safety Unit-I SAFETY TERMINOLOGIESIndustrial Safety Unit-I SAFETY TERMINOLOGIES
Industrial Safety Unit-I SAFETY TERMINOLOGIES
 
Transport layer issues and challenges - Guide
Transport layer issues and challenges - GuideTransport layer issues and challenges - Guide
Transport layer issues and challenges - Guide
 
young call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Serviceyoung call girls in Green Park🔝 9953056974 🔝 escort Service
young call girls in Green Park🔝 9953056974 🔝 escort Service
 
Introduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptxIntroduction-To-Agricultural-Surveillance-Rover.pptx
Introduction-To-Agricultural-Surveillance-Rover.pptx
 

Java Lab Manual

  • 1. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ JAVA PROGRAMMING MANUAL Prepared by Mr. NAVEEN SAGAYASELVARAJ Lecturer CSC Computer Education Krishnagiri Ms. MANGAIYARKKARASI V Lecturer CSC Computer Education Gopichettipalayam
  • 2. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ I S.NO. CONTENT PAGE NO. 1 INTRODUCTION 1 2 PROGRAMMING CONSTRUCTS & CASTING AND TYPE CONVERSION 4 3 ARRAYS 11 4 STRING CLASS 15 5 COSTRUCTOR 20 6 INHERITANCE AND INTERFACE 23 7 I/O STREAM CLASSES 27 8 APPLETS AND SWINGS 39 9 EVENT-HANDLING 49 10 MULTITHREADING 54 11 NETWORKING-I 59 12 NETWORKING-II 68
  • 3. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 1 1 INTRODUCTION OBJECTIVE: Basic Programming using class and objects. OVERVIEW: Classes and Objects: The fundamental programming unit of the Java programming language is the class. Classes provide the structure for objects and the mechanisms to manufacture objects from a class definition. Classes define methods: collections of executable code that are the focus of computation and that manipulate the data stored in objects. Methods provide the behavior of the objects of a class. Syntax: For Class definition: class class_name { Datatype variable_name; //Data_Memebers Returntype method_name(parameters) //Member_Function { -------------; } Pubic static void main(String arg[ ]) { //Main Method block } } For Object creation: class_name object_name = new class_name( ); objectname.variable_name; objectname.methodname( ); To access data_members and member_function of the class
  • 4. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 2 Sample coding: /** * * @author NaveenSagayaelvaRaj */ public class First_Program { private int first_num = 5; private int second_num = 6; public void add() { int answer; answer = first_num+second_num; System.out.println("Answer: "+answer); } public static void main(String arg[]) { First_Program obj=new First_Program(); obj.add(); } } Output: run: Answer: 11 BUILD SUCCESSFUL (total time: 1 second)
  • 5. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 3 PRE LAB EXERCISE Define a class sample with the following specification Public member function of class sample Display() Function to Display “Hello!! World” IN LAB EXERCISE Define a class student with the following specification Private members of class student Roll_no int Phy,che& mathsdouble Total double Average int Cal_Total() a function to calculate Total with double return type Cal_Avg() a function to calculate Average with int return type Public member function of class student Takedata() Function to accept values for Roll_no, Phy,che, maths, invoke Cal_total() to calculate total and invoke Cal_Avg() to calculate average. Showdata() Function to display all the data members. POST LAB EXERCISE Define a class BOOK with the following specifications : Private members of the class BOOK are BOOK NO integer type PRICE double (price per copy) TOTAL_COST() A function to calculate the total cost for N number of copies where N is passed to the function as argument. Public members of the class BOOK are INPUT() function to read BOOK_NO., PRICE PURCHASE() function to ask the user to input the number of copies to be purchased. It invokes TOTAL_COST() and prints the total cost to be paid by the user. Result:
  • 6. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 4 2 PROGRAMMING CONSTRUCTS & CASTING AND TYPE CONVERSION OBJECTIVE: Programming using constructs, looping, casing and type conversions. OVERVIEW: SELECTION CONTROL STRUCTURE: A selection control structure, allows a program to select between two or more alternative paths of execution.  if Statement: if statement is the most basic selection control structure. Syntax: if(boolean expression) { Statement; }  if else Statement: Syntax: if(boolean expression) { Statement; } else { Statement; }
  • 7. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 5  else if Statement: Syntax: if(boolean expression) { Statement; } else if(boolean expression) { Statement; } else { Statement; }  Nested if: Syntax: if(boolean expression) { Statement; if(boolean expression) { Statement; } } else { Statement; }  Switch Statement: It’s a multiway branching statement. It is based on value on expression.
  • 8. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 6 Syntax: switch(ch) { case 1: Statement; break; case 2: Statement; break; . . . . case n: Statement; break; default: Statement; break; } LOPPING STATEMENTS: Looping statement causes a section of statements in the program to be executed a certain number of times. The repetition remains until the condition is true. If the condition false loop ends, and the control structure passes to the next statement.  for Loop: Syntax: for(Initialization ; boolean expression ; Iteration) { Statement: }  Enhanced For Loop: This type of for loop allows iterating through an array without creating an iterator. And do not need to maintain index of each element.
  • 9. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 7 Syntax: for(declaration:expression) { Statement: }  while Loop Syntax: while(boolean expression) { Statement: }  do while Loop: Syntax: do { Statement: } while(boolean expression); CASTING AND CONVERSION: Casting allow converting a variable of one datatype to another. Types of conversion: 1. Implicit conversion- Automatic conversion take place of one datatype to another. Example int to long automatic conversion. 2. Explicit conversion- We force to convert one datatype to another Syntax (type) value; Example: char ch = ’A’; int Asci=(int)ch; //Explicit conversion take place Example:
  • 10. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 8 int Asci = 65; char ch=(char)ch; //Explicit conversion take place Sample coding: /** * * @author NaveenSagayaselvaRaj */ public class Second_Program { public static void main(String arg[]) { System.out.println("**Find whether the given element is Alphabet or a Numberic**n"); char ch='H'; int Asci=(int)ch; if((Asci>=65 && Asci<=90) || (Asci>=97 && Asci<=122)) { System.out.println(ch+" is a Alphabet "); } else if((Asci>=48 && Asci<=57)) { System.out.println(ch+" is a Numeric "); } } Output: run: **Find whether the given element is Alphabet or a Numeric** H is a Alphabet BUILD SUCCESSFUL (total time: 1 second)
  • 11. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 9 Sample coding: /** * * @author NaveenSagayaselvaRaj */ import java.util.Scanner; public class Third_Program { public static void main(String args[]) { int n, num = 1, c, d; Scanner in = new Scanner(System.in); System.out.println("Enter the number of rows of floyd's triangle you want"); n = in.nextInt(); System.out.println("**Floyd's triangle**"); for ( c = 1 ; c <= n ; c++ ) { for ( d = 1 ; d <= c ; d++ ) { System.out.print(num+" "); num++; } System.out.println(); } } } Output: run: Enter the number of rows of floyd's triangle you want 8 **Floyd's triangle** 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 BUILD SUCCESSFUL (total time: 5 seconds)
  • 12. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 10 PRE LAB EXERCISE a. Write a Java program to find Asci value of given char b. Write a Java program to print output as follows, 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 IN LAB EXERCISE a. Write a Java program to change Upper case alphabet to Lower case alphabet b. Write a Java program to print Pyramid POST LAB EXERCISE a. Write Java program to convert the following, I/P Enter a character: 3 O/P Converted into int: 3 b. Write a Java program to print Diamond Result:
  • 13. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 11 3 ARRAYS OBJECTIVE: Programming using arrays. OVERVIEW: Arrays: An Array is a contiguous block of memory location referred by a common name. The length of the array is fixed at the time of creation. Steps to create an Array: 1. Declare an Array 2. New operator to allocate memory to an Array Types of Arrays:  One Dimensional Array  Multi-Dimensional Array Syntax: For One Dimensional Array: 1. Declare an Array Datatype Array_Name [ ]; 2. New operator to allocate memory to an Array Array_Name[ ] = new Datatype[boundary condition ]; For Multi-Dimensional Array: 1. Declare an Array Datatype Array_Name [ ] [ ];
  • 14. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 12 2. New operator to allocate memory to an Array Array_Name[ ] = new Datatype[boundary condition ] [boundary condition ]; Sample coding: /** * * @author NaveenSagayaselvaRaj */ public class Fourth_Program { public static void main(String arg[]) { int array[]=new int[10]; int sum=0; Scanner in=new Scanner(System.in); System.out.println("Enter 10 elements: "); for(int i=0;i<10;i++) { array[i]=in.nextInt(); } for(int i=0;i<10;i++) { sum+=array[i]; } System.out.print("Sum of the elements of an Array: "+sum); } } Output: run: Enter 10 elements: 1 2 3 4 5 6 7 8 9 0 Sum of the elements of an Array: 45 BUILD SUCCESSFUL (total time: 11 seconds)
  • 15. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 13 Sample coding: /** * * @author NaveenSagayaselvaRaj */ public class Fifth_Program { public static void main(String arg[]) { int org_arr[][]=new int[2][2]; int tra_arr[][]=new int[2][2]; System.out.println("***********Transpose of Matrix********"); Scanner in=new Scanner(System.in); System.out.println("Enter the elements for 2X2 matrix:"); for(int i=0;i<2;i++) { for(int j=0;j<2;j++) { org_arr[i][j]=in.nextInt(); } System.out.println(); } for(int i=0;i<2;i++) { for(int j=0;j<2;j++) { tra_arr[i][j]=org_arr[j][i]; } } for(int i=0;i<2;i++) { for(int j=0;j<2;j++) { System.out.print(tra_arr[i][j]); } System.out.println(); } } }
  • 16. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 14 Output: run: ***********Transpose of Matrix******** Enter the elements for 2X2 matrix: 1 2 3 4 1 3 2 4 BUILD SUCCESSFUL (total time: 7 seconds) PRE LAB EXERCISE a. Write a Java program to find product of n elements in an array b. Write a Java program to find addition of two matrices IN LAB EXERCISE a. Write Java program to find whether the given element in the array are positive real number or negative real number or zero b. Write a Java program to find a given matrix is diagonal matrix or not POST LAB EXERCISE a. Write a Java program for TIC TAC TOE game Result:
  • 17. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 15 4 STRING CLASS OBJECTIVE: Detailed study on string class and its methods OVERVIEW: String class: String is the most commonly used class in Java. String is a instance of the class string. They are real object. Methods in String class: S.NO Method Description 1 char charAt(int index) Returns the character at the specified index 2 int compareTo(Object o) Compares this String to another Object. 3 int compareTo(String anotherString) Compares two strings lexicographically. 4 int compareToIgnoreCase(String str) Compares two strings lexicographically, ignoring case differences. 5 String concat(String str) Concatenates the specified string to the end of this string 6 boolean contentEquals(StringBuffer sb) Returns true if and only if this String represents the same sequence of characters as the specified StringBuffer. 7 static String copyValueOf(char[] data) Returns a String that represents the character sequence in the array specified 8 static String copyValueOf(char[] data, int offset, int count) Returns a String that represents the character sequence in the array specified 9 boolean endsWith(String suffix) Tests if this string ends with the specified suffix 10 boolean equals(Object anObject) Compares this string to the specified object. 11 boolean equalsIgnoreCase(String anotherString) Compares this String to another String, ignoring case considerations. 12 byte getBytes() Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new byte array. 13 byte[] getBytes(String charsetName) Encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array. 14 void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin) Copies characters from this string into the destination character array. 15 int hashCode() Returns a hash code for this string. 16 int indexOf(int ch) Returns the index within this string of the first occurrence of the specified character.
  • 18. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 16 17 int indexOf(int ch, int fromIndex) Returns the index within this string of the first occurrence of the specified character, starting the search at the specified index. 18 int indexOf(String str) Returns the index within this string of the first occurrence of the specified substring. 19 int indexOf(String str, int fromIndex) Returns the index within this string of the first occurrence of the specified substring, starting at the specified index 20 String intern() Returns a canonical representation for the string object. 21 int lastIndexOf(int ch) Returns the index within this string of the last occurrence of the specified character 22 int lastIndexOf(int ch, int fromIndex) Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index. 23 int lastIndexOf(String str) Returns the index within this string of the rightmost occurrence of the specified substring. 24 int lastIndexOf(String str, int fromIndex) Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index. 25 int length() Returns the length of this string. 26 boolean matches(String regex) Tells whether or not this string matches the given regular expression. 27 boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len) Tests if two string regions are equal. 28 boolean regionMatches(int toffset, String other, int ooffset, int len) Tests if two string regions are equal 29 String replace(char oldChar, char newChar) Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar. 30 String replaceAll(String regex, String replacement ) Replaces each substring of this string that matches the given regular expression with the given replacement. 31 String replaceFirst(String regex, String replacement) Replaces the first substring of this string that matches the given regular expression with the given replacement. 32 String[] split(String regex) Splits this string around matches of the given regular expression. 33 String[] split(String regex, int limit) Splits this string around matches of the given regular expression. 34 boolean startsWith(String prefix) Tests if this string starts with the specified prefix. 35 boolean startsWith(String prefix, int toffset) Tests if this string starts with the specified prefix beginning a specified index 36 CharSequence subSequence(int beginIndex, int endIndex) Returns a new character sequence that is a subsequence of this sequence
  • 19. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 17 37 String substring(int beginIndex) Returns a new string that is a substring of this string. 38 String substring(int beginIndex, int endIndex) Returns a new string that is a substring of this string 39 char[] toCharArray() Converts this string to a new character array. 40 String toLowerCase() Converts all of the characters in this String to lower case using the rules of the default locale. 41 String toLowerCase(Locale locale) Converts all of the characters in this String to lower case using the rules of the given Locale. 42 String toString() This object (which is already a string!) is itself returned. 43 String toUpperCase() Converts all of the characters in this String to upper case using the rules of the default locale. 44 String toUpperCase(Locale locale) Converts all of the characters in this String to upper case using the rules of the given Locale 45 String trim() Returns a copy of the string, with leading and trailing whitespace omitted. 46 static String valueOf(primitive data type x) Returns the string representation of the passed data type argument
  • 20. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 18 Sample coding: /** * * @author NaveenSagayaselvaRaj */ public class Sixth_Program { //Find whether the string is plaindrome or not public static void main(String arg[]) { String str; Scanner in=new Scanner(System.in); System.out.println("Enter the string: "); str=in.next(); //Reverse the String String rev = ""; int length=str.length(); for(int i=0;i<length;i++) { rev+=str.charAt(length-i-1); } if(str.compareTo(rev)==0) { System.out.println("Its a Palindrome"); } else { System.out.println("Its a not Palindrome"); } } } Output: run: Enter the string: malayalam Its a Palindrome BUILD SUCCESSFUL (total time: 7 seconds)
  • 21. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 19 PRE LAB EXERCISE a. Write a program to find length of the given string without using the string class’s method b. Write a Java program to find number of lower case and number of upper case letters in a string IN LAB EXERCISE a. Write a Java program to find whether the given string is palindrome or not without using string class’s methods b. Write a Java program to change upper case character to lower case character in a string, vice versa,. POST LAB EXERCISE a. Write Java program to find whether the given string is palindrome or not if the characters of the strings is interchanged Eg: I/P Enter the string: tests O/P It will became palindrome Result:
  • 22. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 20 5 COSTRUCTOR OBJECTIVE: Programming using a special type of member function OVERVIEW: Constructor: Constructor method is a special kind of method which are used to initialize objects. Characteristic of Constructor: b. Constructor name same as the class name c. It should be declared as public d. It should not have any return type e. It invoked when an object of class is created, it can't be called explicitly f. It can be overloaded Types of Constructor: 1. Default constructor – Constructor without arguments 2. Parameterized constructor – Constructor with arguments Sample coding: Default constructor: /** * * @author NaveenSagayaselvaRaj */ public class Seventh_Program { Seventh_Program() { System.out.println("Constructor method called."); } public static void main(String[] args) { Seventh_Program obj = new Seventh_Program(); } }
  • 23. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 21 Output: run: Constructor method called. BUILD SUCCESSFUL (total time: 0 seconds) Parameterized constructor: /** * * @author NaveenSagayaselvaRaj */ public class Eigth_Program { Eigth_Program(int num) { System.out.println("Number: "+num); } public static void main(String[] args) { Eigth_Program obj = new Eigth_Program(50); } } Output: run: 50 BUILD SUCCESSFUL (total time: 0 seconds)
  • 24. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 22 PRE LAB EXERCISE *******************************NILL************************************ IN LAB EXERCISE a. Define a class called fruit with the following attributes : 1. Name of the fruit 2. Single fruit or bunch fruit 3. Price Define a suitable constructor and display_Fruit() method that displays values of all the attributes. Write a program that creates 2 objects of fruit class and display their attributes. POST LAB EXERCISE *******************************NILL************************************ Result:
  • 25. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 23 6 INHERITANCE AND INTERFACE OBJECTIVE: Programming using various types of inheritance concept OVERVIEW: Inheritance: Inheritance enable you to reuse the functionality and capabilities of the existing class by extending a new class from existing class and adding new future to it. In inheritance the class that inherits the data member and methods from another class is known as subclass. The class from which the subclass inherits is known as the super class. Types of Inheritance: 1. Single Level Inheritance 2. Multilevel Inheritance Single Level Inheritance: Multilevel Inheritance: super_class_name sub_class_name1 sub_class_name2 super_class_name sub_class_name1 sub_class_name2
  • 26. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 24 Syntax: Single Level Inheritance class super_class_name { //body of the class super_class } class sub_class_name1 extends super_class_name { //body of the sub_class } class sub_class_name2 extends super_class_name { //body of the sub_class } Multilevel Inheritance class super_class_name { //body of the class super_class } class sub_class_name1 extends super_class_name { //body of the sub_class } class sub_class_name2 extends sub_class_name1 { //body of the sub_class } Interface: There may be cases where we need to inherit the features of more than one class. But Java does not support multiple inheritance. However, we can simulate multiple inheritance in java by using interface.
  • 27. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 25 Syntax: interface interface_name { //interface body static final data members; return type public methods(parameters); } class sub_class_name extends super_class_name implements interface_name { //Defining the method declare in the interface return type public methods(parameters) { //Body of the method } } Sample coding: public class Nine_Program { void display() { System.out.println("Super_Class"); } } public class Tenth_Program extends Nine_Program{ public static void main(String arg[]) { Tenth_Program obj=new Tenth_Program(); obj.display(); } } run: Super_Class BUILD SUCCESSFUL (total time: 0 seconds)
  • 28. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 26 PRE LAB EXERCISE *******************************NILL************************************ IN LAB EXERCISE a. Create a class student and declare variable rollno. Create function getnumber() and display(). Create another class test which inherit student. Create function display(). Create another interface sports with variable sport and function putsp(). Create variable total and function putsp(),display(). Create another class result which extends the test and sport. Create main class main_class and which has the student as object of class result. POST LAB EXERCISE *******************************NILL************************************ Result:
  • 29. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 27 7 I/O STREAM CLASSES OBJECTIVE: Implementation of various file classes supported by Java for reading and writing to the file OVERVIEW: Introduction: All programs accept input from user, process the input and produce output. Therefore, all programming languages support the reading of input and display of output. Java handles all input and output in form of streams. A stream is a sequence of bytes traveling from a source to destination over a communication path. When a stream of data is being sent, it is said to be written, and when a stream of data is being received, it is said to be read. Implementing the File class: File are the primary source and destination for storing the data contain in the programs. Java provide the java.io package for performing I/O operation. This include File class. File class Constructors: Constructor Description File(File parent, String child) This constructor is used to create a new File object with the parent path name and child pathname. Syntax : public File(File parent, String child) File(String pathname) This constructor is used to create a new File object with specified file pathname. Syntax : public File(String pathname) File(String parent, String child) This constructor is used to create a new File object with the specified parent pathname and child pathname. Syntax : public File(String parent, String child) File(URI uri) This constructor is used to create a new File object by converting a specified URI into pathname. Syntax : public File(URI uri) Methods in File class: Method Descrption public boolean canExecute() This method is used for testing that whether the file can be executed by the application or not.
  • 30. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 28 public boolean canRead() : This method is used for testing that whether the file can be read by the application or not. public boolean canWrite() This method is used for testing that whether the file can be write by the application or not. public int compareTo(File pathname) This method is used to compare two file pathname. public boolean createNewFile() throws IOException This method is used for creating a new empty file with the specified name. public static File createTempFile(String prefix,String suffix) throws IOException This method is used for creating an empty file in the default temporary file directory. prefix and suffix are used for specifying the name of file. public static File createTempFile(String prefix, String suffix, File directory) throws IOException This method is used for creating an empty file in the given directory. prefix and suffix are used for specifying the name of file. public boolean delete() This method is used for deleting the specified file or directory. public void deleteOnExit() This method is used for deleting the specified file or directory on the termination of JVM. public boolean equals(Object obj) This method is used to test whether the specified Object is equal to the pathname or not. public boolean exists() This method is used to test whether the specified pathname is existed or not.
  • 31. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 29 public File getAbsoluteFile() This method is used to get the absolute form of pathname. public String getAbsolutePath() This method is used to get the absolute pathname. This pathname is retrieved as string. public long getFreeSpace() This method is used to find out the unallocated bytes in the partition (portion of storage for a file system.) public String getName() This method is used to find out the name of file or directory of the specified pathname. public String getParent() This method is used to find out the parent of the specified pathname. public File getParentFile() This method is used to find out the parent of the specified pathname. public String getPath() This method is used to find out the path of the file or directory as string. public long getTotalSpace() This method is used to find out the size of the partition. public long getUsableSpace() This method is used to find out the number of bytes made available to the VM when the partition named by the pathname. public int hashCode() This method is used for computing a hash code for pathname. public boolean isAbsolute() This method is used for testing that whether the pathname is absolute or not. public boolean isDirectory() This method is used for testing that whether the specified pathname is directory or not. public boolean isFile() This method specifies whether the specified file name is a normal file or not. public boolean isHidden() This method specifies, whether the file is a hidden file or not. public long lastModified() This method is used to get the time in which the file was last modified. public long length() This method is used to get the length of the file.
  • 32. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 30 public String[] list() This method is used to get the list of files and directories (as an array of strings) in the specified directory public String[] list(FilenameFilter filter) This method is used to get the list of files and directories (as an array of strings) in the specified directory which specifies a specified filter. public File[] listFiles() This method is used to get the (an array) pathnames which represents files in the directory. public File[] listFiles(FileFilter filter) This method is used to get the (an array) pathnames which represents files and directories in the specified directory which specifies a specified filter. public File[] listFiles(FilenameFilter filter) This method is used to get the (an array) pathnames which represents files and directories in the specified directory which specifies a specified filter. public static File[] listRoots() This method is used to list the file system roots (if available). public boolean mkdir() This method is used to create a directory with the specified pathname. public boolean mkdirs() This method is used to create a directory with the specified pathname. public boolean renameTo(File dest) This method is used to rename the file specified by the pathname. public boolean setExecutable(boolean executable) This method is used to set the permission of execution of files. public boolean setExecutable(boolean executable, boolean ownerOnly) : This method is used to set the permission of execution of files. public boolean setLastModified(long time) This method is used to set the file's or directory's last modified time.
  • 33. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 31 public boolean setReadable(boolean readable) This method is used to set the permission of file to read. public boolean setReadable(boolean readable, boolean ownerOnly) This method is used to set the permission of file to read. public boolean setReadOnly() This method is used to set the file's or directory's to allowed only for read operation. public boolean setWritable(boolean writable) This method is used to set the file's or directory's to allowed only for write operation public boolean setWritable(boolean writable, boolean ownerOnly) This method is used to set the file's or directory's to allowed only for write operation. public String toString() : This method is used to get the pathname of the specified abstract pathname as string.
  • 34. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 32 Sample coding: /** * * @author NaveenSagayaselvaRaj */ import java.io.*; public class Eleventh_Program { public static void main(String[] args) throws IOException { File f; f=new File("D:/myfile.txt"); if(!f.exists()) { f.createNewFile(); System.out.println(“New file "myfile.txt" has been created to the given directory); } else { System.out.println("The specified file is already exist"); } } } Output: run: New file "myfile.txt" has been created to the given directory BUILD SUCCESSFUL (total time: 3 seconds)
  • 35. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 33 Screenshot: Using Streams in Java: Accessing File using the InputStream Class: InputStream are the byte streams that read data in the form of byte. Java providing classes are shown below, InputStream SequenceInputStream ObjectInputStream PipedInputStream ByteArrayInputStream FilterInputStream FileInputStream PushbackInputStream BufferedInputStreamDataInputStream
  • 36. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 34 Using Streams in Java: Accessing File using the OutputStream Class: OutputStream are the byte streams that write data in the form of byte. Java providing classes are shown below, Implementing Character Stream Classes: Using the Reader Class: The Reader class is used to read characters from the character streams. The Reader class cannot be instantiated since it is an abstract class. Therefore, the object of its subclasses are used for reading Unicode character data. OutputStream ObjectOutputStream PipedOutputStream ByteArrayOutputStream FilterOutputStream FileOutputStream BufferedOutputStreamDataOutputStream Reader BufferedReader LineNumberReader StringReader InputStreamReader FileReader PipedReader FilterReader PushbackReader CharArrayReader
  • 37. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 35 Using the Writer class: The Writer class is used to write characters from the character streams. The Writer class cannot be instantiated since it is an abstract class. Therefore, the object of its subclasses are used for writing character data to a character stream. Sample coding: /** * * @author NaveenSagayaselvaRaj */ public class Twelfth_Program { public static void main(String arg[]) throws FileNotFoundException, IOException { char ch; File f=new File("D:/test.txt"); FileReader fr=new FileReader(f); //Reading a content from file while(fr.ready()) { ch=(char)fr.read(); System.out.print(ch); } System.out.println(); fr.close(); } } Writer BufferedWriter StringWriter OutputStreamWriter FileWriter PipedWriter FilterWriter CharArrayWriter
  • 38. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 36 Output: run: Hello!!! world BUILD SUCCESSFUL (total time: 0 seconds) Snapshot:
  • 39. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 37 Sample coding: /** * * @author NaveenSagayaselvaRaj */ public class Twelfth_Program { public static void main(String arg[]) throws FileNotFoundException, IOException { String str="Writer working"; File f=new File("D:/test.txt"); FileWriter fw=new FileWriter(f); fw.write(str); fw.close(); } } Output: run: BUILD SUCCESSFUL (total time: 0 seconds) Snapshot:
  • 40. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 38 PRE LAB EXERCISE a. Write a Java Program to print size of a file b. Write a Java program to copy the text file using InputStream and OutputStream IN LAB EXERCISE a. Write a Java program to get absolute path of the file b. Write a Java program to read the entire text file, eliminate all special characters in it and write the content in the same text file I/O test.txt Hai!! How Are You? O/P test.txt HaiHowAreYou POST LAB EXERCISE a. Write a Java program to delete a file b. Write a Java program to prove the following mathematics notations, 1. n(n + l)(2n + 1) is always divisible by 6. 2. 32n leaves remainder = 1 when divided by 8 3. n3 + (n + 1 )3 + (n + 2 )3 is always divisible by 9 4. 102n + 1 + 1 is always divisible by 11 5. n(n2 – 1) is always divisible by 6 6. n2 + n is always even 7. 23n -1 is always divisible by 7 8. 152n-1 +l is always divisible by 16 9. n3 + 2n is always divisible by 3 10. 34n – 4 3n is always divisible by 17 *(Note get the value of n from the text file) Result:
  • 41. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 39 8 APPLETS AND SWINGS OBJECTIVE: Creating GUI using Java programming. OVERVIEW: Applet: Applet are Java program that executes inside a Web page. Therefore, unlike applications, applet require a Java enabled browsers like Internet Explorer or Netscape etc. An applet loaded and executed when a user load a Web page through Wed browser. Applet Life Cycle: Various Graphics Methods: S.No Method Purpose 1 public void init() Called once by the applet container when an applet is loaded for execution. This method initializes an applet. Typical actions performed here are initializing fields, creating GUI components, loading sounds to play, loading images to display 2 public void start() Called by the applet container after method init completes execution. In addition, if the user browses to another website and later returns to the applet’s HTML page, method start is called again. The method performs any tasks that must be completed when the applet is loaded for the first time and that must be performed every time the applet’s HTML page is revisited. Actions performed here might include starting an animation 3 public void paint( Graphics g ) Called by the applet container after methods init and start. Method paint is also called when the applet needs to be repainted. For example, if the user covers the applet with another open window on the screen and later uncovers the applet, the paint method is called. Typical actions performed here involve drawing with the Graphics object g that is passed to the paint method by the applet container 4 public void stop() This method is called by the applet container when the user leaves the applet’s web page by browsing to another web page. Since it is possible that the user might return to the web page containing the applet, method stop performs tasks that might be required to suspend the applet’s execution, so that the applet does not use computer processing time when it is not displayed on the screen. Typical actions performed here would stop the execution of animations 5 public void destroy() This method is called by the applet container when the applet is being removed from memory. This occurs when the user exits the browsing session by closing all the browser windows
  • 42. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 40 Method Description abstract void clearRect(int x, int y, int width, int height) Clears the specified rectangle by filling it with the background color of the current drawing surface. abstract void clipRect(int x, int y, int width, int height) Intersects the current clip with the specified rectangle. abstract void copyArea(int x, int y, int width, int height, int dx, int dy) Copies an area of the component by a distance specified by dx and dy. abstract Graphics create() Creates a new Graphics object that is a copy of this Graphics object. Graphics create(int x, int y, int width, int height) Creates a new Graphics object based on this Graphics object, but with a new translation and clip area. abstract void dispose() Disposes of this graphics context and releases any system resources that it is using. void draw3DRect(int x, int y, int width, int height, boolean raised) Draws a 3-D highlighted outline of the specified rectangle. abstract void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle) Draws the outline of a circular or elliptical arc covering the specified rectangle. void drawBytes(byte[] data, int offset, int length, int x, int y) Draws the text given by the specified byte array, using this graphics context's current font and color. void drawChars(char[] data, int offset, int length, int x, int y) Draws the text given by the specified character array, using this graphics context's current font and color. abstract boolean drawImage(Image img, int x, int y, Color bgcolor, ImageObserver observer) Draws as much of the specified image as is currently available. abstract boolean drawImage(Image img, int x, int y, ImageObserver observer) draws as much of the specified image as is currently available. abstract boolean drawImage(Image img, int x, int y, int width, int height, Color bgcolor, ImageObserver observer) Draws as much of the specified image as has already been scaled to fit inside the specified rectangle. abstract boolean drawImage(Image img, int x, int y, int width, int height, ImageObserver observer) Draws as much of the specified image as has already been scaled to fit inside the specified rectangle. abstract booleandrawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, Color bgcolor, ImageObserver observer) Draws as much of the specified area of the specified image as is currently available, scaling it on the fly to fit inside the specified area of the destination drawable surface. abstract boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1, int sx2, int sy2, ImageObserver observer) Draws as much of the specified area of the specified image as is currently available, scaling it on the fly to fit inside the specified area of the destination drawable surface.
  • 43. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 41 abstract void drawLine(int x1, int y1, int x2, int y2) Draws a line, using the current color, between the points (x1, y1) and (x2, y2) in this graphics context's coordinate system. abstract void drawOval(int x, int y, int width, int height) Draws the outline of an oval. abstract void drawPolygon(int[] xPoints, int[] yPoints, int nPoints) Draws a closed polygon defined by arrays of x and y coordinates. void drawPolygon(Polygon p) Draws the outline of a polygon defined by the specified Polygon object. abstract void drawPolyline(int[] xPoints, int[] yPoints, int nPoints) Draws a sequence of connected lines defined by arrays of x and y coordinates. void drawRect(int x, int y, int width, int height) Draws the outline of the specified rectangle. abstract void drawRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight) Draws an outlined round-cornered rectangle using this graphics context's current color. abstract void drawString(AttributedCharacterIterator iterator, int x, int y) Renders the text of the specified iterator applying its attributes in accordance with the specification of the TextAttribute class. abstract void drawString(String str, int x, int y) Draws the text given by the specified string, using this graphics context's current font and color. void fill3DRect(int x, int y, int width, int height, boolean raised) Paints a 3-D highlighted rectangle filled with the current color. abstract void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle) Fills a circular or elliptical arc covering the specified rectangle. abstract void fillOval(int x, int y, int width, int height) Fills an oval bounded by the specified rectangle with the current color. abstract void fillPolygon(int[] xPoints, int[] yPoints, int nPoints) Fills a closed polygon defined by arrays of x and y coordinates. void fillPolygon(Polygon p) Fills the polygon defined by the specified Polygon object with the graphics context's current color. abstract void fillRect(int x, int y, int width, int height) Fills the specified rectangle. abstract void fillRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight) Fills the specified rounded corner rectangle with the current color. void finalize() Disposes of this graphics context once it is no longer referenced. abstract Shape getClip() Gets the current clipping area.
  • 44. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 42 Sample coding: /** * * @author NaveenSagayaselvaRaj */ import java.applet.Applet; import java.awt.Graphics; abstract Rectangle getClipBounds() Returns the bounding rectangle of the current clipping area. Rectangle getClipBounds(Rectangle r) Returns the bounding rectangle of the current clipping area. Rectangle getClipRect() Deprecated. As of JDK version 1.1, replaced by getClipBounds(). abstract Color getColor() Gets this graphics context's current color. abstract Font getFont() Gets the current font. FontMetrics getFontMetrics() Gets the font metrics of the current font. abstract FontMetrics getFontMetrics(Font f) Gets the font metrics for the specified font. boolean hitClip(int x, int y, int width, int height) Returns true if the specified rectangular area might intersect the current clipping area. abstract void setClip(int x, int y, int width, int height) Sets the current clip to the rectangle specified by the given coordinates. abstract void setClip(Shape clip) Sets the current clipping area to an arbitrary clip shape. abstract void setColor(Color c) Sets this graphics context's current color to the specified color. abstract void setFont(Font font) Sets this graphics context's font to the specified font. abstract void setPaintMode() Sets the paint mode of this graphics context to overwrite the destination with this graphics context's current color. abstract void setXORMode(Color c1) Sets the paint mode of this graphics context to alternate between this graphics context's current color and the new specified color. String toString() Returns a String object representing this Graphics object's value. abstract void translate(int x, int y) Translates the origin of the graphics context to the point (x, y) in the current coordinate system.
  • 45. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 43 import javax.swing.JOptionPane; public class Fourteenth extends Applet { private double sum; /** * Initialization method that will be called after the applet is loaded into * the browser. */ public void init() { String firstNumber; String secondNumber; double number1; double number2; firstNumber = JOptionPane.showInputDialog( "Enter first floating-point value" ); secondNumber = JOptionPane.showInputDialog( "Enter second floating-point value" ); number1 = Double.parseDouble( firstNumber ); number2 = Double.parseDouble( secondNumber ); sum = number1 + number2; } public void paint( Graphics g ) { super.paint( g ); g.drawRect( 15, 10, 270, 20 ); g.drawString( "The sum is " + sum, 25, 25 ); } // TODO overwrite start(), stop() and destroy() methods }
  • 47. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 45 Working with AWT Control Components: Java provides the AWT control components, which contain classes that enables us to create standard components such as buttons, labels and text field in Java. Various AWT Components: Some of the AWT component classes are,  TextField  TextArea  Button  List  CheckBox  Choice  Label Working with Swing Components: Swing components also provide GUI environment to Java in addition to applet. Swing components are the collection of lightweight visual component that provide a replacement for heavy weight AWT components. Identifying the Swing Component Class Hierarchy: The JComponents class is the root of the Swing hierarchy. The class hierarchy of the Swing components is categorized into: 1. Top-level swing containers: It act as a container for placing the intermediate-level and atomic components, such as panels, buttons, checkbox. a. JFrame b. JApplet c. JDialog 2. Intermediate-level swing container: It placed on top-level container and contains atomic components, such as buttons, checkbox and labels. a. JPanel b. JtabbedPane c. JScrollPane d. JToolBar 3. Atomic components: It placed on the intermediate-level swing container. Atomic components are used to accept input from a user. a. JTextField b. JButton c. JCheckBox d. JLabel e. JTable
  • 48. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 46 Steps to create and work with JFrame using NetBean IDE: 1. File->New Project 2. New Project dialog box will appear 3. In Categories click Java, in Projects click Java Application and click Next 4. Give Project Name, uncheck the Create Main Class and click Finish 5. Project created. Right Click in the project in the Project Explorer tab 6. New->JFrame Form 7. New JFrame Form will appear 8. Give Class Name and click Finish 9. An empty JFrame is created 10. We can find Palette Explorer in Right side of the NetBean IDE. If not go to Window ->Palette or Ctrl+Shift+8 11. Drag and Drop needed components to the Frame
  • 49. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 47 12. To change the JLabel name or to resize the component. We can find Properties Explorer in Right side of the NetBean IDE. If not go to Window ->Properties or Ctrl+Shift+7 13. To view the Frame actual visible. Click Preview Design
  • 50. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 48 PRE LAB EXERCISE a. Draw any one smiley you known in JApplet b. Create a Register form GUI for School Administration purpose using JFrame IN LAB EXERCISE a. An analysis of examination result at a school gave the following distribution of grades for all subject taken in the year: Grade Percentage A 10 B 25 C 45 D 60 E 85 Write a Java program to represent the distribution of each grade in bar char b. Create a Calculator GUI using JFrame POST LAB EXERCISE a. Draw a 3D rectangle without using Graphics method in JApplet b. Create a Notepad GUI using JFrame Result:
  • 51. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 49 9 EVENT-HANDLING OBJECTIVE: Detailed study on Event classes in java OVERVIEW: Event: An object that describes a state of change in a source component is called an event. In Java, events are supported by the classes and interfaces defined in the java.awt.event package. Event Classes: Event Handling Classes and Methods ActionListener actionPerformed(ActionEvent) addActionListener() AdjustmentListener adjustmentValueChanged(Adjustment Event) addAdjustmentListener( ) ComponentListener componentHidden(ComponentEvent) componentMoved(ComponentEvent) componentResized(ComponentEvent) componentShown(ComponentEvent) addComponentListener( ) ContainerListener componentAdded(ContainerEvent) componetRemoved(ContainerEvent) addContainerListener() Java.util.EventObject Java.util.AWTEvent ItemEvent Adjustment Event FocusEvent Component Event ContainerEv ent FocusEvent InputEvent MouseEvent KeyEvent PaintEvent WindowEve nt ActionEvent TextEvent
  • 52. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 50 FocusListener focusGained(FocusEvent) focusLost(FocusEvent) addFocusListener() ItemListener itemStateChanged(ItemEvent) addItemListener() KeyListener keyPressed(KeyEvent) keyReleased(KeyEvent) keyTyped(KeyEvent) addKeyListener() MouseListener mouseClicked(MouseEvent) mouseEntered(MouseEvent) mouseExited(MouseEvent) mousePressed(MouseEvent) mouseReleased(MouseEvent) addMouseListener() MouseMotionListene r mouseDragged(MouseEvent) mouseMoved(MouseEvent) addMouseMotionListen er() TextListener textValueChanged(TextEvent) addTextListener() WindowListener windowActivated(WindowEvent) windowClosed(WindowEvent) windowClosing(WindowEvent) windowDeactivated(WindowEvent) windowDeiconified(WindowEvent) windowIconified(WindowEvent) windowOpened(WindowEvent) addWindowListener() Steps to work with Event handling in NetBean IDE:  Open a NewJFrame, class name is Fifteenth and drag necessary components
  • 53. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 51  For above example, We going to perform ActionEvent on jButton1 (Login)  Right click on the button, click Event->Action->actionPerformed[jButton1ActionPerformed]  private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) method created in the Fiveteenth.java file. We can view that method by clicking source tab.
  • 54. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 52  Write the following code in the private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) method,  Run the program When we give the Username and Password field matches to the if condition in program When we give the Username and Password field mismatch to the if condition in program
  • 55. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 53 PRE LAB EXERCISE a. Create a Register form for School Administration purpose using JFrame and If the details were entered click Register button. If the Register button is clicked, display the given options in next Frame IN LAB EXERCISE a. Create a Scientific Calculator using JFrame (Use standard Math methods for calculation) b. Rotate a compass needle on the screen about a fixed point in response to the mouse being moved around the screen. POST LAB EXERCISE a. Create a JFrame (as shown below) to access the FileChooser to select file. After selecting the file the content of the file displayed in the JTextArea. Result:
  • 56. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 54 10 MULTITHREADING OBJECTIVE: Creating Thread and demonstrate Multithreading concept OVERVIEW: Thread: A thread can be defined as the single sequential flow of control within the program. It is a sequence of instruction that is executed to define a unique flow of control. For example: A CPU performs various process simultaneously, such as writing and printing a document, installing a software, and displaying the date and time on status bar. The process that is made of one thread is known as single-threaded process. A process that creates two or more threads is called a multi-thread process. For example: Any Web browser, such as Microsoft Edge, is a multi-threaded application. Every Java program uses threads: Every Java program has at least one thread i.e. main thread. When a Java program starts, the JVM creates the main thread and call the program main() method within that thread. The JVM also creates other threads that are mostly invisible to us. For example: Threads associate with garbage collection, object finalization, and other JVM housekeeping tasks. Other facilities create threads too, such as the AWT or Awing UI toolkits, servlet containers, application servers and RMI(Remote Method Invocation). Benefits of Multithreading:  Improved performance  Minimized system resource usage  Simultaneous access to multiple application  Program structure simplification Pitfalls of Multithreading:  Race Condition  Deadlock Condition  Lock Starvation
  • 57. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 55 Life Cycle of a Thread: The various states in the life cycle of the thread are:  New  Runnable  Not Runnable  Terminate or Dead The following figure shows the life cycle of a thread. Creating Thread: We create thread by instantiating an object of the Thread class. We can create a thread in the following ways, 1. Implementing the Runnable interface 2. Extending the Thread class Creating Thread by implementing the Runnable Interface: If Applet extends the Applet class. Since Java does not support multiple inheritance, we cannot inherit both Applet and Thread. So, Java provide us Runnable Interface. Terminate New Thread Created Suspended RunnableSleeping resume( ) run( ) suspend( ) sleep( ) timeout( ) stop( )
  • 58. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 56 Sample coding: /** * * @author NaveenSagayaselvaRaj */ import java.util.logging.Level; import java.util.logging.Logger; class Sixteenth1 implements Runnable{ Sixteenth1() { Thread t = new Thread(this,"mythread"); t.start(); } @Override public void run() { System.out.println("Child class"); } } class Sixteenth2{ public static void main(String arg[]) { new Sixteenth1(); System.out.println("Main class"); try { Thread.sleep(20); } catch (InterruptedException ex) { Logger.getLogger(Sixteenth2.class.getName()).log(Level.SEVERE, null, ex); } } } Output: run: Main class Child class BUILD SUCCESSFUL (total time: 2 seconds)
  • 59. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 57 Sample coding: /** * * @author NaveenSagayaselvaRaj */ import java.util.logging.Level; import java.util.logging.Logger; class Seventeenth1 extends Thread{ Seventeenth1() { Thread t = new Thread(this,"mythread"); t.start(); } @Override public void run() { System.out.println("Child class"); } } class Seventeenth1{ public static void main(String arg[]) { new Seventeenth1(); try { Thread.sleep(2000); } catch (InterruptedException ex) { Logger.getLogger(Sixteenth2.class.getName()).log(Level.SEVERE, null, ex); } System.out.println("Main class"); } } Output: run: Child class Main class BUILD SUCCESSFUL (total time: 2 seconds) PRE LAB EXERCISE
  • 60. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 58 *******************************NILL************************************ IN LAB EXERCISE a. Illustrate Multi-Thread concept with suitable example POST LAB EXERCISE *******************************NILL************************************ Result:
  • 61. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 59 11 NETWORKING-I OBJECTIVE: Java Programming on basic networking protocols OVERVIEW: Introduction: One of the important features of java are networking support. Java provides fundamental networking capabilities through java.net package. OSI layers: Communication between computers in network Layer 7: Application Layer  Defines interface to user processes for communication and data transfer in network  Provides standardized services such as virtual terminal, file and job transfer and operations Layer 6: Presentation Layer  Masks the differences of data formats between dissimilar systems  Specifies architecture-independent data transfer format  Encodes and decodes data; encrypts and decrypts data; compresses and decompresses data
  • 62. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 60 Layer 5: Session Layer  Manages user sessions and dialogues  Controls establishment and termination of logic links between users  Reports upper layer errors Layer 4: Transport Layer  Manages end-to-end message delivery in network  Provides reliable and sequential packet delivery through error recovery and flow control mechanisms  Provides connectionless oriented packet delivery Layer 3: Network Layer  Determines how data are transferred between network devices  Routes packets according to unique network device addresses  Provides flow and congestion control to prevent network resource depletion Layer 2: Data Link Layer  Defines procedures for operating the communication links  Frames packets  Detects and corrects packets transmit errors Layer 1: Physical Layer  Defines physical means of sending data over network devices  Interfaces between network medium and devices  Defines optical, electrical and mechanical characteristics Protocol: A protocol is a set of rules and standard for communication. A network protocol specifies the format of data being sent over the network, along with necessary details. The important protocols used in the Internet are: 1. IP(Internet Protocol): Internet Protocol is a network layer protocol that breaks the data into packets and sent them using IP address. 2. TCP(Transmission Control Protocol): It is a used for connection oriented communication between two applications on two different machines. 3. UDP(User Datagram Protocol): It is a used for connectionless oriented communication between two applications on two different machines.
  • 63. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 61 Internet Address: An Internet address uniquely identifies a node on the Internet. Internet address may also refer to the name or IP of a Web site (URL). The term Internet address can also represent someone's e-mail address InetAddress class in Java: It is a class in Java which represents an Internet Protocol (IP) address. An instance of an InetAddress consists of an IP address and possibly corresponding hostname. The Class represents an Internet address as Two fields: 1. Host name (The String)=Contain the name of the Host. 2. Address(an int)= The 32 bit IP address. These fields are not public, so we can’t Access them directly. There is not public constructor in InetAddress class, but it has 3 static methods that returns suitably initialized InetAddress. Objects namely Public String getHostName() , public byte[] getAddress() and public String getHostAddress() Methods Description boolean equals(Object obj) Compares this object against the specified object. byte[] getAddress() Returns the raw IP address of this InetAddress object. static InetAddress[]getAllByName(String host) Given the name of a host, returns an array of its IP addresses, based on the configured name service on the system. static InetAddress getByAddress(byte[] addr) Returns an InetAddress object given the raw IP address. static InetAddress getByAddress(String host, byte[] addr) Creates an InetAddress based on the provided host name and IP address. static InetAddress getByName(String host) Determines the IP address of a host, given the host's name. String getCanonicalHostName() Gets the fully qualified domain name for this IP address. String getHostAddress() Returns the IP address string in textual Presentation. String getHostName() Gets the host name for this IP address. static InetAddress getLocalHost() Returns the address of the local host. static InetAddress getLoopbackAddress() Returns the loopback address. Int hashCode() Returns a hashcode for this IP address. boolean isAnyLocalAddress() Utility routine to check if the InetAddress in a wildcard address. boolean isLinkLocalAddress() Utility routine to check if the InetAddress is an link local address. boolean isLoopbackAddress() Utility routine to check if the InetAddress is a loopback address. boolean isMCGlobal() Utility routine to check if the multicast address has global scope.
  • 64. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 62 boolean isMCLinkLocal() Utility routine to check if the multicast address has link scope. boolean isMCNodeLocal() Utility routine to check if the multicast address has node scope. boolean isMCOrgLocal() Utility routine to check if the multicast address has organization scope. boolean isMCSiteLocal() Utility routine to check if the multicast address has site scope. boolean isMulticastAddress() Utility routine to check if the InetAddress is an IP multicast address. boolean isReachable(int timeout) Test whether that address is reachable. boolean isReachable(NetworkInterface netif, int ttl, int timeout) Test whether that address is reachable. boolean isSiteLocalAddress() Utility routine to check if the InetAddress is a site local address. String toString() Converts this IP address to a String. Sample coding: To print IP address of LocalHost: /** * * @author NaveenSagayaselvaRaj */ public class Eighteenth_Program { public static void main(String arg[]) { try { InetAddress IPO=InetAddress.getLocalHost(); System.out.println("IP of this system= "+IPO.getHostAddress()); } catch(Exception e) { System.err.println("Exception: "+e.getMessage()); } } }
  • 65. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 63 Output: run: IP of this system= 127.0.0.1 BUILD SUCCESSFUL (total time: 0 seconds) TCP (Transmission Control Protocol): Creating TCP Servers: To create a TCP server, do the following: 1. Create a ServerSocket attached to a port number. ServerSocket server = new ServerSocket(port); 2. Wait for connections from clients requesting connections to that port. // Block on accept() Socket channel = server.accept(); We get a Socket object as a result of the connection. 3. Get input and output streams associated with the socket. out = new PrintWriter (channel.getOutputStream()); reader = new InputStreamReader (channel.getInputStream()); in = new BufferedReader (reader); Now you can read and write to the socket, thus, communicating with the client. String data = in.readLine(); out.println("Welcome!!"); When a server invokes the accept() method of the ServerSocket instance, the main server thread blocks until a client connects to the server; it is then prevented from accepting further client connections until the server has processed the client's request. This is known as an iterative server, since the main server method handles each client request in its entirety before moving on to the next request. Iterative servers are good when the requests take a known, short period of time. For example, requesting the current day and time from a time-of-day server.
  • 66. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 64 Creating TCP Clients: To create a TCP client, do the following: 1. Create a Socket object attached to a remote host, port. Socket client = new Socket(host, port); When the constructor returns, you have a connection. 2. Get input and output streams associated with the socket. out = new PrintWriter (client.getOutputStream()); reader = new InputStreamReader (client.getInputStream()); in = new BufferedReader (reader); Now you can read and write to the socket, thus, communicating with the server. out.println("Hi!! This is me your client"); String data = in.readLine();
  • 67. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 65 Sample coding: Implementation of Client Server Communication Using TCP CliTCP: /** * * @author NaveenSagayaselvaRaj */ import java.lang.*; import java.net.*; import java.io.*; class CliTCP { public static void main(String args[]) throws UnknownHostException { try { Socket skt=new Socket("",1234); BufferedReader in=new BufferedReader(new InputStreamReader(skt.getInputStream())); System.out.println("Received string:"); while(!in.ready()) {} System.out.println(in.readLine()); System.out.println("n"); in.close(); } catch(Exception e) { System.out.println("Whoops! It didn't work! n"); } } }
  • 68. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 66 SerTCP: /** * * @author NaveenSagayaselvaRaj */ import java.lang.*; import java.net.*; import java.io.*; class SerTCP { public static void main(String args[]) { String data="Welcome"; try { ServerSocket s=new ServerSocket(1234); Socket skt=s.accept(); System.out.println("Server has connected! n"); PrintWriter out=new PrintWriter(skt.getOutputStream(),true); System.out.println("Sending string: n "+data+"n"); out.print(data); out.close(); skt.close(); s.close(); } catch(Exception e) { System.out.println("Whoops! It didn't work! n"); } } } Output: Clientside: run: Received string: Welcome BUILD SUCCESSFUL (total time: 2 seconds)
  • 69. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 67 Serverside: run: Server has connected! Sending string: Welcome BUILD SUCCESSFUL (total time: 2 seconds) PRE LAB EXERCISE a. Write a Java Program to print MAC address of the local host IN LAB EXERCISE a. Create a Simple Chat Application using TCP b. Create a Simple Game Application using TCP POST LAB EXERCISE a. Create a Simple Chat Application using TCP (Note: Create JFrames Application) Result:
  • 70. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 68 12 NETWORKING-II OBJECTIVE: Java Programming on basic networking protocols OVERVIEW: UDP (User Datagram Protocol): Creating UDP Servers: To create a server with UDP, do the following: 1. Create a DatagramSocket attached to a port. int port = 1234; DatagramSocket socket = new DatagramSocket(port); 2. Allocate space to hold the incoming packet, and create an instance of DatagramPacket to hold the incoming data. byte[] buffer = new byte[1024]; DatagramPacket packet = new DatagramPacket(buffer, buffer.length); 3. Block until a packet is received, then extract the information you need from the packet. // Block on receive() socket.receive(packet); // Find out where packet came from // so we can reply to the same host/port InetAddress remoteHost = packet.getAddress(); int remotePort = packet.getPort(); // Extract the packet data byte[] data = packet.getData(); The server can now process the data it has received from the client, and issue an appropriate reply in response to the client's request.
  • 71. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 69 Creating UDP Client: Writing code for a UDP client is similar to what we did for a server. Again, we need a DatagramSocket and a DatagramPacket. The only real difference is that we must specify the destination address with each packet, so the form of the DatagramPacket constructor used here specifies the destination host and port number. Then, of course, we initially send packets instead of receiving. 1. First allocate space to hold the data we are sending and create an instance of DatagramPacket to hold the data. byte[] buffer = new byte[1024]; int port = 1234; InetAddress host = InetAddress.getByName("magelang.com"); DatagramPacket packet = new DatagramPacket(buffer, buffer.length, host, port); 2. Create a DatagramSocket and send the packet using this socket. DatagramSocket socket = new DatagramSocket(); socket.send(packet); The DatagramSocket constructor that takes no arguments will allocate a free local port to use. You can find out what local port number has been allocated for your socket, along with other information about your socket if needed. // Find out where we are sending from InetAddress localHostname = socket.getLocalAddress(); int localPort = socket.getLocalPort(); The client then waits for a reply from the server. Many protocols require the server to reply to the host and port number that the client used, so the client can now invoke socket.receive() to wait for information from the server.
  • 72. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 70 Sample coding: Implementation of socket program for UDP Echo Client and Echo Server: CliUDP: /** * * @author NaveenSagayaselvaRaj */ import java.net.*; import java.io.*; import java.lang.*; public class CliUDP { public static void main(String args[])throws IOException { byte[] buff=new byte[1024]; DatagramSocket soc=new DatagramSocket(9999); String s="From client-Hello Server"; buff=s.getBytes(); InetAddress a=InetAddress.getLocalHost(); DatagramPacket pac=new DatagramPacket(buff,buff.length,a,8888); soc.send(pac); System.out.println("End of sending"); byte[] buff1=new byte[1024]; buff1=s.getBytes(); pac=new DatagramPacket(buff1,buff1.length); soc.receive(pac); String msg=new String(pac.getData()); System.out.println(msg); System.out.println("End of programming"); } }
  • 73. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 71 SerUDP: /** * * @author NaveenSagayaselvaRaj */ import java.net.*; import java.io.*; import java.lang.*; public class ES { public static void main(String args[])throws IOException { byte[] buff=new byte[512]; DatagramSocket soc=new DatagramSocket(8888); DatagramPacket pac=new DatagramPacket(buff,buff.length ); System.out.println("server started"); soc.receive(pac); String msg=new String(pac.getData()); System.out.println(msg); System.out.println("End of reception"); String s="From Server-Hello client"; byte[] buff1=new byte[512]; buff1=s.getBytes(); InetAddress a=pac.getAddress(); int port=pac.getPort(); pac=new DatagramPacket(buff,buff1.length,a,port); soc.send(pac); System.out.println("End of sending"); } } Output: Clientside: run: End of sending From client-Hello Server End of programming BUILD SUCCESSFUL (total time: 2 seconds)
  • 74. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 72 ServerSide: run: server started From client-Hello Server End of reception End of sending BUILD SUCCESSFUL (total time: 2 seconds) PRE LAB EXERCISE a. Design UDP Client and Server application to reverse the given input sentence. IN LAB EXERCISE a. Design UDP Client Server to transfer a file POST LAB EXERCISE *******************************NILL************************************ Result:
  • 75. naveensagayaselvaraj@gmail.com NAVEEN SAGAYASELVARAJ 1 Contact Person1: Mr. Naveen Sagayaselvaraj Email ID: naveensagayaselvaraj@gmail.com Website: https://sites.google.com/site/naveensagayaselvaraj/ Contact Person2: Ms. Mangaiyarkkarasi V Email ID: v.mangai.2010@gmail.com