102 Object oriented programming with JAVA
102 Object oriented programming with JAVA
ORIENTED
PROGRAMMING WITH JAVA
UNIT – I
Object Oriented Programming Fundamentals & Java: Java Features, Object Oriented
Programming Concepts –Abstraction, Encapsulation, Inheritance and Polymorphism.
Java Fundamentals: Data Types, variables, arrays, Inheritance to classes: class
fundamentals, Objects, References, Constructors, Overloading of methods, Access
control, Nested and Inner classes. Inheritance: Inheritance basics, Using Super,
multilevel hierarchy, method overriding, dynamic method dispatch, abstract classes,
final with inheritance.
UNIT-II
UNIT-III
Java Utilities: Type wrappers: Number, Double, Float, Byte, Short, Integer and
Long, Character, Boolean, Math class. Collections: Collection interfaces, collection
classes, legacy classes and interfaces: Enumeration interface, Vector, Stack,
Dictionary, Hash table. More utility classes: String Tokenizer, Bit set, Date, And
Calendar Input/output: File, Stream classes, Byte Streams, Character Streams.
UNIT-IV
UNIT - V
Text Book
Reference Books
WhatIsInheritance?
WhatIsanInterface?
interface Bicycle {
// wheel revolutions per
minute void
changeCadence(int
newValue); void
changeGear(int newValue);
void speedUp(int
increment);
void applyBrakes(int decrement); }
To implement this interface, the name of your class would change (to
a particular brand of bicycle, for example, such as ACMEBicycle), and
you'd use the implements keyword in the class declaration:
WhatIsaPackage?
1)Simple
Java is easy to learn and its syntax is quite simple, clean and
easy to understand.The confusing and ambiguous concepts of C++
are either left out in Java or they have been re-implemented in a
cleaner way.
Eg : Pointers and Operator Overloading are not there in java but
were an important part of C++.
2)Object Oriented
3)Robust
4)Platform Independent
6)Multi Threading
7)Architectural Neutral
8)Portable
Lets see how JVM works: Class Loader: The class loader
reads the .class file and save the byte code in the method area.
Method Area: There is only one method area in a JVM which is
shared among all the classes. This holds the class level information of
each .class file.
Heap: Heap is a part of JVM memory where objects are allocated.
JVM creates a Class object for each .class file.
Stack: Stack is a also a part of JVM memory but unlike Heap, it is
used for storing temporary variables.
PC Registers: This keeps the track of which instruction has been
executed and which one is going to be executed. Since instructions are
executed by threads, each thread has a separate PC register.
Native Method stack: A native method can access the runtime data
areas of the virtual machine.
Native Method interface: It enables java code to call or be called
by native applications. Native applications are programs that are specific
to the hardware and OS of a system.
Garbage collection: A class instance is explicitly created by the
java code and after use it is automatically destroyed by garbage
collection for memory management.
JRE: JRE is the environment within which the java virtual machine
runs. JRE contains Java virtual Machine(JVM), class libraries, and other
files excluding development tools such as compiler and
debugger. Which means you can run the code in JRE but you can’t
develop and compile the code in JRE.
JVM: As we discussed above, JVM runs the program by using class,
libraries and files provided by JRE.
JDK: JDK is a superset of JRE, it contains everything that JRE has
along with development tools such as compiler,
debugger etc. Data types in java:
Java Variables:
Variables are containers for storing data values. In Java, there are
different types of variables, for example:
To create a variable, you must specify the type and assign it a value:
Example Create a variable called myNum of type int and assign it the
value 15:
You can also declare a variable without assigning the value, and
assign the value later:
System.out.println(myNum);
Final Variables
However, you can add the final keyword if you don't want others (or
yourself) to overwrite existing values (this will declare the variable as
"final" or "constant", which means unchangeable and read-only):
Example
final int myNum = 15; myNum = 20; // will generate an error: cannot
assign a value to a final variable
Example
Display Variables
The println() method is often used to display variables.To
combine both text and a variable, use the + character:
Example
Example
Example
Java Operators
Operators are used to perform operations on variables and
values.In the example below, we use the + operator to add
together two values: Example int x = 100 + 50; Although the +
operator is often used to add together two values, like in the
example above, it can also be used to add together a variable and a
value, or a variable and another variable:
Example int sum1 = 100 + 50; int sum2 = sum1 + 250; int sum3 =
sum2 + sum2;
/
Division Divides one value by x / y
another
-- --x
Decrement Decreases the value of a
variable by 1
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
!= Not equal x != y
||
Logical Returns true if one of the x < 5 || x < 4
or statements is true
If/Else/Else If
int whileCounter = 1;
while (whileCounter <= 50) { methodToRepeat() whileCounter++;}
Both code blocks above will call methodToRepeat 50 times.
Break
We need to use break to exit early from a
loop. Let's see a quick example:
List<String> names =
getNameList();
String name = "John Doe";
int index = 0;
for ( ; index < names.length; index++)
{
if (names[index].equals(name)) { break; }}
Here, we are looking for a name in a list of names, and we want to
stop looking once we've found it.
Continue
Simply put,continuemeans to skip the rest of the loop we're in:
List<String> names = getNameList();
String name = "John Doe"; String
list = ""; for (int i = 0; i <
names.length; i++) { if
(names[i].equals(name)) {
continue;
}list += names[i];}
Here, we skip appending the duplicate names into the list.
Java Arrays
Arrays are used to store multiple values in a single variable, instead
of declaring separate variables for each value.
String[] cars;
We have now declared a variable that holds an array of strings. To
insert values to it, we can use an array literal - place the values in a
comma- separated list, inside curly braces:
Note: Array indexes start with 0: [0] is the first element. [1] is the
second element, etc.
Examplecars[0] = "Opel";
Array Length To find out how many elements an array has, use the
length property:
You can loop through the array elements with the for loop, and use
the length property to specify how many times the loop should run.
The following example outputs all elements in the cars array:
Syntax
for (type variable : arrayname) {}
The following example outputs all elements in the cars array, using a
"foreach" loop:
The example above can be read like this: for each String element
(called i - as in index) in cars, print out the value of i.
If you compare the for loop and for-each loop, you will see that the
for- each method is easier to write, it does not require a counter
(using the length property), and it is more readable.
Multidimensional Arrays
To create a two-dimensional array, add each array within its own set of
curly braces:Example int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
System.out.println(x); // Outputs 7
We can also use a for loop inside another for loop to get the
elements of a two-dimensional array (we still have to point to the
two indexes): Example is
<myNumbers[i].length; ++j) {
System.out.println(myNumbers[i][j]);}}}
Control Structures :
Control Statements in Javais one of the fundamentals required for
Java Programming. It allows the smooth flow of a program. Following
pointers will be covered in this article:Decision making statements
simple if statement ,if- else statement ,Nested if statement, Switch
statement, Looping statements, while,Do-while,For ,For-each
,Branching statements ,Break, Continue
Simple if statement
Output:
If statement!
Hello World!
If..else statement
> 20)
else
System.out.println("Hello World!");}}}
Output:
a is less than 10
Hello World!
Nested if statement
if (condition1) {
(condition2) {
Example:
else
System.out.println("Hello World!");}}
Switch statement
Example:
args){int instrument = 4;
String musicInstrument;
6:musicInstrument = "Violin";break;case
7:musicInstrument = "Trumpet";break;default:
musicInstrument = "Invalid";break;}
System.out.println(musicInstrument);}}
Output:
Flute
Looping Statements
Known as the most common loop, the while loop evaluates a certain
condition. If the condition is true, the code is executed. This process
is continued until the specified condition turns out to be
false. The condition to be specified in the while loop must be a
Boolean expression. An error will be generated if the type used is int
or a string.
Syntax:
while (condition){statementOne;}
Example:
{System.out.println(i);i = i+2;}}}
Output:
5 7 9 11 13 15
Do..while
The do-while loop is similar to the while loop, the only difference
being that the condition in the do-while loop is evaluated after the
execution of the loop body. This guarantees that the loop is executed
at least once.
Syntax:
do{//code to be executed}while(condition);
Example:
public class Main
4 { int i = 20; do
Output:
20
Syntax:
for (initialization; condition; increment/decrement)
{statement;}
Example:
Output:
5
6
7
8
9
10
For-Each
Example:
(int i : s)
{System.out.println(i);}}}
Output:
18
25
28
29
30
Branching Statements
Branching statements in java are used to jump from a statement to
another statement, thereby the transferring the flow of execution.
Break
Example:
}}}
Output:
5
6
7
Continue
Example:
Output:
6 8 10 12 14
Arrays
An array is a grouping of the same typed values in computer
memory. In Java, the data stored in an array can be a primitive or
an object. As a quick refresher, primitive data types in Java are byte,
short, int, long, float, double, or character. When storing primitives
in an array Java stores these in adjacent blocks of memory. An
element is an individual value in an array. The index is the location of
an element in the array.
Creating an array
In Java, there are two ways to create an array. The first way is
using the new keyword as shown below.int[] array = new
int[10];The other way to create an array is using a shortcut syntax.
The shortcut syntax allows us to instantiate the array with exactly
the values we need. Using this syntax, we skip having to do the
costly operation of looping through the array to insert an element at
each index.
System.out.println(myObj.x);}}
System.out.println(myObj1.x);System.out.println(myObj2.x);}}
Using Multiple Classes
Remember that the name of the java file should match the class
name. In this example, we have created two files in the same
directory/folder:
• Main.java
• Second.java
byte Byte
short Short
int Integer
long Long
float Float
double Double
Auto boxing
System.out.println(a+””+i+++);}} output:20 20 20
Unboxing :
Constructors
1.Typesofconstructors
1. DefaultConstructor
2. ParameterizedConstructor
2. ConstructorOverloading
3. Doesconstructorreturnanyvalue?
4. Copyingthevaluesofoneobjectintoanother
5. Doesconstructorperform othertasksinsteadoftheinitialization
In Java, a constructor is just like a method but without return type. It can also be overloaded
like Java methods.
Constructor overloading in Javais a technique of having more than one constructor with
different parameter lists. They are arranged in a way that each constructor performs a
different task. They are differentiated by the compiler by the number of parameters in the
list and their types
There is no copy constructor in Java. However, we can copy the values from one object to another like
copy constructor in C++.
There are many ways to copy the values of one object into another in Java. They are:
In this example, we are going to copy the values of one object into another using Java constructor.
The constructor name must be same as the The method name may or may
class name. not be same as the class name.
Overloading of methods
1. Differentwaystooverloadthe method
2. Bychangingtheno.ofarguments
3. Bychangingthedatatype
4. Whymethodoverloadingisnotpossiblebychangingthereturntype
5. Canweoverloadthemainmethod
6. methodoverloadingwithType Promotion
If we have to perform only one operation, having same name of the methods
increases the readability of theprogram.
Suppose you have to perform addition of the given numbers but there can be any
number of arguments, if you write the method such as a(int,int) for two
parameters, and b(int,int,int) for three parameters then it may be difficult for you
as well as other programmers to understand the behavior of the method because
its name differs.
In this example, we are creating static methodsso that we don't need to create instance for
calling methods.
class
Add
er{
static int add(int a,int b){return
a+b;} static int add(int a,int b,int
c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
Access Control
Access control specifies the accessibility of code. By using these you can
specify the scope of data, method, class etc.There are 3 types of access control
in :
1. Public or Default
2. Private
3. Internal
1. type AccessControl() =
2. member public x.a = 10
3. member public x.display() = printfn "This is public method"
4. let ac = new AccessControl() ac.display()
5. printfn "a = %d" ac.a Output:This is public methoda = 10
Nested class
Nested class is such class which is created inside another class. In Kotlin,
nested class is by default static, so its data member and member function can
be accessed without creating an object of class. Nested class cannot be able to
access the data member of outer class.
class outerClass{ //outer class
codeclass nestedClass{
//nested class code } }
Inner class
Inner class is a class which is created inside another class with keyword inner.
In other words, we can say that a nested class which is marked as "inner" is
called inner class.
The advantage of inner class over nested class is that, it is able to access
members of outer class even it is private. Inner class keeps a reference to an
object of outer class
Abstract class in Java
Abstraction in Java
These are important points :An abstract class must be declared with
an abstract keyword,It can have abstract and non-abstract
methods,It cannot be instantiated,It can have constructors and static
methods also,It can have final methods which wil force the subclass
not to change the body of the method.
Obj.run();}}
File: TestBank.java
2. TypesofInheritance
3. Whymultipleinheritanceisnot possibleinJavaincaseofclass?
Inheritance in Java is a mechanism in which one object acquires all
the properties and behaviors of a parent object. The idea behind
inheritance in Java is that you can create new classesthat are built
upon existing classes. . Inheritance represents the IS-A
relationship which is also known as a parent-child relationship.
Why use inheritance in
javaoForMethodOverriding(soruntimepolymorphismcan be
The extends keyword indicates that you are making a new class
that derives from an existing class. The meaning of "extends" is to
increase the functionality. In the terminology of Java, a class which
is inherited is called a parent or superclass, and the new class is
called child or subclass.
File: TestInheritance2.java
Method Overriding:
o Method overriding is used to provide the specific
implementation of a method which is already provided by its
superclass.
parent class.
1. class Vehicle{
2. void run(){System.out.println("Vehicle is running");}
3. class Bike2 extends Vehicle{
4. void run(){System.out.println("Bike is running safely");}
5. public static void main(String args[]){
6. Bike2 obj = new Bike2();//creating object
7. obj.run();//calling method } } Output:Bike is running safely
UNIT-iI
Java Math class
Java Math class provides several methods to work on math
calculations like min(), max(), avg(), sin(), cos(), tan(), round(),
ceil(), floor(), abs() etc.
Unlike some of the StrictMath class numeric methods, all implementations of the
equivalent function of Math class can't define to return the bit-for-bit same
results. If the size is int or long and the results overflow the range of value,
the methods addExact(), subtractExact(), multiplyExact(), and
toIntExact() throw an ArithmeticException.
publicclass JavaMathExample1
{ publicstaticvoid main(String[] args) { double x = 28; double y = 4;
LogarithmicMathMethods:
Math.log(),Math.log10(),Math.log1p(),Math.exp(),Math.expm1
()
Java Package
A java package is a group of similar types of classes, interfaces and
subpackages.Package in java can be categorized in two form, built-in
package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net,
io, util, sql etc.Here, we will have the detailed learning of creating and using
user-defined packages.
Subpackage in java
Let's take an example, Sun Microsystem has definded a package named java
that contains many classes like System, String, Reader, Writer, Socket etc.
These classes represent a particular group e.g. Reader and Writer classes
are for Input/Output operation, Socket and ServerSocket classes are for
networking etc and so on. So, Sun has subcategorized the java package into
subpackages such as lang, net, io etc. and put the Input/Output related
classes in io package, Server and ServerSocket classes in net packages and
so on
Interface in Java
An interface in Java is a blueprint of a class. It has static constants
and abstract methods.
In other words, you can say that interfaces can have abstract methods and
variables. It cannot have a method body. Java Interface also represents
the IS-A relationship.It cannot be instantiated just like the abstract class.
There are mainly three reasons to use interface. They are given
below.
oIt is used to achieve abstraction. By interface, we can support the
functionality of multiple inheritance. It can be used to achieve loose
coupling.
How to declare an interface? An interface is declared by using the interface
keyword. It provides total abstraction; means all the methods in an interface
are declared with the empty body, and all the fields are public, static and
final by default. A class that implements an interface must implement all the
methods declared in the interface.
Syntax:
1.interface<interface_name>{
In other words, Interface fields are public, static and final by default,
and the methods are public and abstract.
1. publicclass JavaExceptionExample{
2. publicstaticvoid main(String args[]){
3. try{ int data=100/0; }catch(ArithmeticException
e){System.out.println (e);}
4. System.out.println("rest of the code..."); } }
If you are inserting any value in the wrong index, it would result in
ArrayIndexOutOfBoundsException
ArithmeticException, ArrayIndexOutOfBoundExceptions,
ClassNotFoundExceptions etc. are come in the category of Built-in
Exception. Sometimes, the built-in exceptions are not sufficient to explain
or describe certain situations. For describing these situations, we have to
create our own exceptions by creating an exception class as a subclass of
the Exception class. These types of exceptions come in the category of
User-Defined Exception.
Un caught exceptions :
1. throw exception;
2. publicclass TestThrow1{
3. staticvoid validate(int age){
4. if(age<18)
5. thrownew ArithmeticException("not valid");
6. else
7. System.out.println("welcome to vote"); }
8. publicstaticvoid main(String args[]){
9. validate(13);
10. System.out.println("rest of the code..."); }}
D
iffere
No. throw throws nce
1) Java throw keyword is Java throws betwe
used to explicitly keyword is used en
throw an exception. to declare an throw
exception. and
2) Checked exception Checked throw
cannot be exception can s in
propagated using be propagated Java
throw only. with throws.
Jav
3) Throw is Throws is
a
followed by followed by thro
an class. w
instance. exa
4) Throw is Throws is used mple
used with the 1.voi
within the method d m()
method. signature. {
thro
5) You cannot You can declare multiple
w
throw exceptions e.g. public
new
multiple void method()throws
Ari
exceptions. IOException,SQLException.
thmet
icE xception(
"sorry"); }
Multithreading in Java
Multithreading :Javais a process of executing multiple threads
simultaneously.
Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use
multitasking to utilize the CPU. Multitasking can be achieved in two ways:
Thread in java
A thread is a lightweight subprocess, the smallest unit of processing. It is a
separate path of execution. Threads are independent. If there occurs
exception in one thread, it doesn't affect other threads. It uses a shared
memory area.
As shown in the above figure, a thread is executed inside the process. There
is context-switching between the threads. There can be multiple processes
inside theOS, and one process can have multiple threads.
A thread can be in one of the five states. According to sun, there is only 4
states in thread life cycle in java new, runnable, non-runnable and
terminated. There is no running state.
The life cycle of the thread in java is controlled by JVM. The java thread
states are as follows:
3) Running The thread is in running state if the thread scheduler has selected
it.
4) Non-Runnable (Blocked) This is the state when the thread is still alive, but
is currently not eligible to run.
Multithreading in Java
MULTITHREADING in Java is a process of executing two or more threads
simultaneously to maximum utilization of CPU. Multithreaded applications
execute two or more threads run concurrently. Hence, it is also known as
Concurrency in Java. Each thread runs parallel to each other. Mulitple threads
don't allocate separate memory area, hence they save memory. Also, context
switching between threads takes less time.
Advantages of multithread:
• The users are not blocked because threads are independent, and we
can perform multiple operations at times
• As such the threads are independent, the other threads won't get
affected if one thread meets an exception
Synchronization in Java
Synchronization in java is the capability to control the access of multiple
threads to any shared resource. Java Synchronization is better option where
we want to allow only one thread to access the shared resource.
Types of Synchronization
Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while
sharing data. This can be done by three ways in java: 1 by synchronized
method 2. by synchronized block 3 by static synchronization
class Table{
void printTable(int n){//method not synchronized
for(int i=1;i<=5;i++){
System.out.println(n*i); try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);} } } }
class MyThread1 extends Thread{ Table
t; MyThread1(Table t){
this.t=t; }
publicvoid run(){
t.printTable(5); } }
class MyThread2 extends Thread{ Table t;
MyThread2(Table t){ this.t=t; }
publicvoid run(){
t.printTable(100); } } class
TestSynchronization1{
publicstaticvoid main(String args[]){ Table
obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
. t1.start(); t2.start(); } }
Output: 5 100 10 200 15 300 20 400 25 500
Java synchronized method If you declare any method as synchronized, it is
known as synchronized method. Synchronized method is used to lock an object
for any shared resource.When a thread invokes a synchronized method, it
automatically acquires the lock for that object and releases it when the thread
completes its task.class Table{
synchronizedvoid printTable(int n){//synchronized
methodfor(int i=1;i<=5;i++){
System.out.println(n*i); try{ Thread.sleep(400);
}catch(Exception e){System.out.println(e);} } } } class
MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t; } publicvoid run(){ t.printTable(5); }
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){ this.t=t; }
publicvoid run(){ t.printTable(100); } }
publicclass TestSynchronization2{
publicstaticvoid main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start(); t2.start(); } } Synchronized
Block in Java
1) wait() method
Causes current thread to release the lock and wait until either another
thread invokes the notify() method or the notifyAll() method for this object,
or a specified amount of time has elapsed.
The current thread must own this object's monitor, so it must be called from
the synchronized method only otherwise it will throw exception. Public final
void wait() throws InterruptedException :waits until object is notified.
public final void wait(long timeout)throws InterruptedException :waits for
the specified amount of time.
2) notify() method
3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor. Syntax:
CharSequence Interface
How to create a string object? There are two ways to create String object: By
string literal ,By new keyword
1) String Literal Java String literal is created by using double quotes. For
Example: String s="welcome";
Each time you create a string literal, the JVM checks the "string constant
pool" first. If the string already exists in the pool, a reference to the pooled
instance is returned. If the string doesn't exist in the pool, a new string
instance is created and placed in the pool. For example:
2) By new keyword
String s=new String("Welcome");//creates two objects and one reference v
ariable
1. By equals() method
2. By = = operator
3. By compareTo() method
The String equals() method compares the original content of the string. It
compares values of string for equality. String class provides two methods:
The String equals() method compares the original content of the string. It
compares values of string for equality. String class provides two methods:
Java string concatenation operator (+) is used to add strings. For Example:
Substring in Java
You can get substring from the given string object by one of the two
methods:
The java string toUpperCase() method converts this string into uppercase
letter and string toLowerCase() method into lowercase letter.
String s="Sachin";
System.out.println(s.toUpperCase());//SACHIN
System.out.println(s.toLowerCase());//sachin System.out.println(s);
Java String charAt() method The string charAt() method returns a character at
specified index.
Java String charAt() method The string charAt() method returns a character at
specified index.
When the intern method is invoked, if the pool already contains a string
equal to this String object as determined by the equals(Object) method,
then the string from the pool is returned.
Java String valueOf() method The string valueOf() method coverts given
type such as int, long, float, double, boolean, char and char array into
string.
Java String replace() method The string replace() method replaces all
occurrence of first sequence of character with second sequence of character.
Java StringBuffer class Java StringBuffer class is used to create mutable
(modifiable) string. The StringBuffer class in java is same as String class
except it is mutable i.e. it can be changed.
3)StringBuffer replace() method The replace() method replaces the given string
from the specified beginIndex and endIndex.
The capacity() method of StringBuffer class returns the current capacity of the buffer. The
default capacity of the buffer is 16. If the number of character increases from its current
capacity, it increases the capacity by (oldcapacity *2)+2. For example if your current
capacity is 16, it will be (16*2)+2=34.
StringTokenizer(String creates
str) StringTokenizer with
specified string.
StringTokenizer(String creates
str, String delim) StringTokenizer with
specified string and
delimeter.
StringTokenizer(String creates StringTokenizer with
str, String delim, boolean specified string, delimeter and
returnValue) returnValue. If return value is
true, delimiter characters are
considered to be tokens. If it is
false, delimiter characters set.
Methods of StringTokenizer class The 6 useful methods of
StringTokenizer class
are as follows:
Public method Description
Short Questions
1.what is access protection?
2.what are the importing packages?
3.What are the exception types?
4.what is thread model?
Long Questions
5.explain about packages and interfaces?
6.Briefly explain about exception handling?
7.Explain about multithreading ?
8.Inter thread communication, string handling ?
UNIT-III
Since J2SE 5.0, autoboxing and unboxing feature convert primitives into
objects and objects into primitives automatically. The automatic conversion
of primitive into an object is known as autoboxing and vice-versa unboxing.
o Change the value in Method: Java supports only call by value. So, if
we pass a primitive value, it will not change the original value. But, if
we convert the primitive value in an object, it will change the original
value.
o Serialization: We need to convert the objects into streams to perform
the serialization. If we have a primitive value, we can convert it in
objects through the wrapper classes.
o Synchronization: Java synchronization works with objects in
Multithreading. ojava.util package: The java.util package provides the
utility classes to deal with objects.
o Collection Framework: Java collection framework works with objects
only. All classes of the collection framework (ArrayList, LinkedList,
Vector, HashSet, LinkedHashSet, TreeSet, PriorityQueue, ArrayDeque,
etc.) deal with objects only.
Number Class
Java Number class provides methods to convert the represented
numeric value to byte, double, float, int, long, and short type. The
various Java Number methods are as follows-
SN Modifier Method Description
& Type
1) Byte byteValue() It converts the given
number into a byte
type and returns the
value of the specified
number as a byte.
2) abstract doubleValue() It returns the value
double of the specified
number as a double
equivalent.
3) abstract floatValue() It returns the float
float equivalent value of
the specified Number
object.
4) abstract intValue() It returns
int the value
of the
specified
number as
an int.
5) abstract longValue() It returns the value
long of the specified
number object as
long equivalent.
6) short shortValue() It returns the value
of the specified
number as a short
type after a primitive
conversion.
Java Character class
The Character class generally wraps the value of all the primitive type char
into an object. Any object of the type Character may contain a single field
whose type is char. All the fields, methods, and constructors of the class
Character are specified by the Unicode Data file which is particularly a part of
Unicode Character Database and is maintained by the Unicode Consortium.
Methods:booleanValue(),compare(),compareTo(),equals(),getBoolean(),hashCode(),lo
gicalAnd(),logicalOr(),logicalXor(),parseBoolean(),toString(), valueOf()
More Utility Classes:
Java.utilpackage contains the collection's framework, legacy collection
classes, event model, date and time facilities,internationalization, and
miscellaneous utility classes (a string tokenizer, a random-number generator,
and a bit array). Here is the list of most commonly used top ten Java utility
classes:
1. Java Arrays Class Java.util package provides anArrays classthat
contains a static factory that allows arrays to be viewed as lists. The class
contains various methods for manipulating arrays like sorting and searching.
The methods in this class throw a NullPointerException, if the specified array
reference is null.
2. Java Vector Class Java.util. A vector is a sequence container
implementing array that can change in size. Unlike an array, the size of a
vector changes automatically when elements are appended or deleted. It is
similar to ArrayList, but with two differences:1 Vector package provides
avector classthat models and implements vector data structure is
synchronized. Vector contains many legacy methods that are not part of the
collections framework.
Class declaration
Class constructors
Sr.No. Constructor & Description
1 Vector()
This constructor is used to create an empty vector
so that its internal data array has size 10 and its
standard capacity increment is zero.
2 Vector(Collection<? extends E> c)
This constructor is used to create a vector containing the
elements of the specified collection, in the order they are
returned by the collection's iterator.
3 Vector(int initialCapacity)
This constructor is used to create an empty vector
with the specified initial capacity and with its
capacity increment equal to zero.
4 Vector(int initialCapacity, int
capacityIncrement)
This constructor is used to create an empty vector
with the specified initial capacity and capacity
increment.
Stack
The stack is a linear data structure that is used to store the collection of
objects. It is based on Last-In-First-Out (LIFO).Java collectionframework
provides many interfaces and classes to store the collection of objects. One
of them is the Stack class that provides different operations such as push,
pop, search, etc.
In Java, Stack is a class that falls under the Collection framework that
extends the Vector class. It also implements interfaces List, Collection,
Iterable, Cloneable, Serializable. It represents the LIFO stack of objects.
Before using the Stack class, we must import the java.util package. The stack
class arranged in the Collections framework hierarchy, as shown below.
Methods of the Stack Class We can perform push, pop, peek and
search operation on the stack. The Java Stack class provides
mainly five methods to. Along with this, it also provides all the
methods of theJava Vector class.
Method Modifier and perform these operations Method
Type Description
Hashtable class Parameters Let's see the Parameters for java.util.Hashtable class.
oK: It is the type of keys maintained by this map,V: It is the type of
mapped values.
StringTokenizer in Java
The java.util.StringTokenizer class allows you to break a string into
tokens. It is simple way to break string.
Character Streams
Java Byte streams are used to perform input and output of 8-bit bytes,
whereas Java Character streams are used to perform input and output for
16-bit unicode. Though there are many classes related to character streams
but the most frequently used classes are, FileReader and FileWriter.
Though internally FileReader uses FileInputStream and FileWriter uses
FileOutputStream but here the major difference is that FileReader reads two
bytes at a time and FileWriter writes two bytes at a time.
FileInputStream
This stream is used for reading data from the files. Objects can be created
using the keyword new and there are several types of constructors available.
FileOutputStream
FileOutputStream is used to create a file and write data into it. The stream
would create a file, if it doesn't already exist, before opening it for output.
Here are two constructors which can be used to create a FileOutputStream
object.
There are current three sets of Java APIs for graphics programming: AWT
(Abstract Windowing Toolkit), Swing and JavaFX.
1. AWT API was introduced in JDK 1.0. Most of the AWT components have
become obsolete and should be replaced by newer Swing components.
2. Swing API, a much more comprehensive set of graphics libraries that
enhances the AWT, was introduced as part of Java Foundation Classes
(JFC) after the release of JDK 1.1. JFC consists of Swing, Java2D,
Accessibility, Internationalization, and Pluggable Look-and-Feel Support
APIs. JFC has been integrated into core Java since JDK 1.2.
3. The latest JavaFX, which was integrated into JDK 8, is meant to replace
Swing.
Other than AWT/Swing/JavaFX graphics APIs provided in JDK, other
organizations/vendors have also provided graphics APIs that work with Java,
such as Eclipse's Standard Widget Toolkit (SWT) (used in Eclipse), Google
Web Toolkit (GWT) (used in Android), 3D Graphics API such as Java bindings
for OpenGL (JOGL) and Java3D.
In the above figure, there are three containers: a Frame and two Panels. A
Frame is the top-level container of an AWT program. A Frame has a title
bar (containing an icon, a title, and the minimize/maximize/close
buttons), an optional menu bar and the content display area. A Panel is a
rectangular area used to group related GUI components in a certain
layout. In the above figure, the top-level Frame contains two Panels.
There are five components: a Label (providing
description), a TextField (for users to enter text), and three Buttons
(for user to trigger certain programmed actions).
A Frame provides the "main window" for your GUI application. It has a title bar
(containing an icon, a title, the minimize, maximize/restore-down and close
buttons), an optional menu bar, and the content display area. To write a GUI
program, we typically start with a subclass extending from java.awt.Frame to
inherit the main window as follows:
• An AWT Dialog is a "pop-up window" used for interacting with the users.
A Dialog has a title-bar (containing an icon, a title and a close button) and
a content display area, as illustrated.
• An AWT Applet (in package java.applet) is the top-level container for an
applet, which is a Java program running inside a browser.
Secondary Containers: Panel and ScrollPane
Swing Introduction
Swing is part of the so-called "Java Foundation Classes (JFC)" (have you
heard of MFC?), which was introduced in 1997 after the release of JDK 1.1.
JFC was subsequently included as an integral part of JDK since JDK 1.2. JFC
consists of:
• Swing API: for advanced graphical programming.
• Accessibility API: provides assistive technology for the disabled.
• Java 2D API: for high quality 2D graphics and images.
• Pluggable look and feel supports.
• Drag-and-drop support between Java and native applications.
The goal of Java GUI programming is to allow the programmer to build GUI
that looks good on ALL platforms. JDK 1.0's AWT was awkward and
nonobject-oriented (using many event.getSource()). JDK 1.1's AWT
introduced event-delegation (event-driven) model, much clearer and object-
oriented. JDK 1.1 also introduced inner class and JavaBeans – a component
programming model for visual programming environment (similar to Visual
Basic).
Swing appeared after JDK 1.1. It was introduced into JDK 1.1 as part of an
add-on JFC (Java Foundation Classes). Swing is a rich set of easy-to-use,
easy-to-understand JavaBean GUI components that can be dragged and
dropped as "GUI builders" in visual programming environment. Swing is now
an integral part of Java since JDK 1.2.
Swing's Features
Swing is huge (consists of 18 packages of 737 classes as in JDK 1.8) and has
great depth. Swing provides a huge and comprehensive collection of
reusable GUI components. The main features of Swing are (extracted from
the Swing website):
1. Swing is written in pure Java (except a few classes) and therefore is
100% portable.
2. Swing components are lightweight. The AWT components are
heavyweight (in terms of system resource utilization). Each AWT
component has its own opaque native display, and always displays on
top of the lightweight components. AWT components rely heavily on
the underlying windowing subsystem of the native operating system.
For Swing components support pluggable look-and-feel. You can
choose between Java look-and-feel and the look-and-feel of the
underlying OS Similarly, a Swing button runs on the UNIX looks like a
UNIX's button and feels like a UNIX's button.
3. Swing supports mouse-less operation, i.e., it can operate entirely using
keyboard.
4. Swing components support "tool-tips".
5. Swing components are JavaBeans – a Component-based Model used in
Visual Programming (like Visual Basic). You can drag-and-drop a Swing
component into a "design form" using a "GUI builder" and double-click
to attach an event handler.
6. Swing application uses AWT event-handling classes (in package
java.awt.event). Swing added some new classes in package
javax.swing.event, but they are not frequently used.
7. Swing application uses AWT's layout manager (such as FlowLayout and
BorderLayout in package java.awt). It added new layout managers,
such as Springs, Struts, and BoxLayout (in package javax.swing).
8. Swing implements double-buffering and automatic repaint batching for
smoother screen repaint.
9. Swing introduces JLayeredPane and JInternalFrame for creating
Multiple Document Interface (MDI) applications.
10. Swing supports floating toolbars (in JToolBar), splitter control,
"undo".
Using Swing API
Swing's Components
Compared with the AWT component classes (in package java.awt), Swing
component classes (in package javax.swing) begin with a prefix "J", e.g.,
JButton, JTextField, JLabel, JPanel, JFrame, or JApplet.
Short Questions
1.what are the float and byte?
2.what are the two differences between byte and byte
stream?
3.what are the collection classes ?
4.what are the character streams?
Long Questions
5. Explain the Java utilities?
6. Briefly explain the type wrappers?
7. Explain the collections in Java?
8.what are the more utility classes? Explain?
UNIT-4
Java Applet
Applet is a special type of program that is embedded in the webpage to
generate the dynamic content. It runs inside the browser and works at
client side.
Advantage of Applet There are many advantages of applet. They are as follows:
to execute applet.
java.applet.Applet class
To execute the applet by html file, create an applet and compile it. After that
create an html file and place the applet code in html file. Now click the html
file.
1. //First.java
2. import java.applet.Applet; import java.awt.Graphics;
3. publicclass First extends Applet{
4. publicvoid paint(Graphics g){
5. g.drawString("welcome",150,150); } myapplet.html
1. <html><body>
2. <applet code="First.class" width="300" height="300"></applet></b
1. //First.java
2. import java.applet.Applet;
3. import java.awt.Graphics;
4. publicclass First extends Applet{
5. publicvoid paint(Graphics g){
6. g.drawString("welcome to applet",150,150); } }
7. /*<applet code="First.class" width="300" height="300"></applet>*/
To execute the applet by appletviewer tool, write in command prompt:
c:\>javac First.java c:\>appletviewer First.java
myapplet.html
1. <html><body>
2. <applet code="DisplayImage.class" width="300" height="300">
3. </applet></body></html>
Parameter in Applet
We can get any information from the HTML file as a parameter. For this
purpose, Applet class provides a method named getParameter(). Syntax:
public String getParameter(String parameterName) Example
of using parameter in Applet:
1. import java.applet.Applet; import java.awt.Graphics;
2. publicclass UseParam extends Applet{
3. publicvoid paint(Graphics g){
4. String str=getParameter("msg");
5. g.drawString(str,50, 50); } } myapplet.html
1. <html><body>
2. <applet code="UseParam.class" width="300" height="300">
3. <param name="msg" value="Welcome to applet">
4. </applet></body></html>
Animation in Applet
Applet is mostly used in games and animation. For this purpose image is required to be
moved.
Example of animation in applet:
myapplet.html
1. <html><body>
2. <applet code="DisplayImage.class" width="300" height="300">
3. </applet></body></html>
ActionEvent ActionListener
MouseListener and
MouseEvent MouseMotionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
Registration Methods
For registering the component with the Listener, many classes provide the
registration methods. For example:
o Button
oTextField
public void addActionListener(ActionListener a){}
oTextArea
o Checkbox
oChoice
oList
public void setBounds(int xaxis, int yaxis, int width, int height); have
been used in the above example that sets the position of the component it
may be button, textfield etc.
WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
HierarchyBoundsAdapter HierarchyBoundsListener
Adapter class Listener interface
DragSourceAdapter DragSourceListener
DragTargetAdapter DragTargetListener
Adapter class Listener interface
MouseInputAdapter MouseInputListener
InternalFrameAdapter InternalFrameListener
java.awt.event Adapter classes
What is JFC
The Java Foundation Classes (JFC) are a set of GUI components which
simplify the development of desktop applications.
File: FirstSwingExample.java
1. import javax.swing.*;
2. publicclass FirstSwingExample {
3. publicstaticvoid main(String[] args) {
4. JFrame f=new JFrame();//creating instance of JFrame
5. JButton b=new JButton("click");//creating instance of JButton
6. b.setBounds(130,100,100, 40);//x axis, y axis, width, height
7. f.add(b);//adding button in JFrame
8. f.setSize(400,500);//400 width and 500 height
9. f.setLayout(null);//using no layout managers
10. f.setVisible(true);//making the frame visible } }
Java JFrame
Unlike Frame, JFrame has the option to hide or close the window with the
help of setDefaultCloseOperation(int) method.
Nested Class
Modifier Class Description
and Type
protected JFrame.AccessibleJFrame This
class class
impleme
nts
accessibility
support for
the JFrame
class.
Fields
Modifier and Type Field Description
accessibleContext The
accessible
protected context
AccessibleContext property.
static int EXIT_ON_CLOSE The exit application
default
window
close
operation.
protected rootPane
JRootPane
The JRootPane instance
that manages the
contentPane and
optional menuBar for
this frame, as well as
the glassPane.
protected boolean rootPaneCheckingEnabled
If true then calls to add
and setLayout will be
forwarded to the
contentPane.
Constructors
Constructor Description
JFrame() It constructs a new
frame that is initially
invisible.
JFrame(GraphicsConfiguration It creates a Frame in the
gc) specified GraphicsConfiguration
of a screen device and a blank
title.
JFrame(String title) It creates a new,
initially invisible
Frame with the
specified title.
JFrame(String title, It creates a JFrame
GraphicsConfiguration gc) with the specified title
and the specified
GraphicsConfiguration
of a screen device.
Useful Methods
Modif Method Descri
ier and ption
Type
prote addImpl(Component c O
cted constraints o b
void , int index) m j Adds the
p e specified child
, ct Component.
pr
ote
cte createRo
d otPane() Called by the
JRoot
Pane constructor.
protected void frameInit()
Called by the
constructors to init
the JFrame
properly.
void setContentPane(Containe contentPane) It
se
ts
th
e
content
Pane
property
static setDefaultLookAndFeelDecorated(boole
Provides a hint as
void an defaultLookAndFeelDecorated)
to whether or not
newly
void setIconImage(Image image)
JFrame Example
1. import java.awt.FlowLayout;
2. import javax.swing.JButton;
3. import javax.swing.JFrame;
4. import javax.swing.JLabel;
5. import javax.swing.Jpanel;
6. publicclass JFrameExample {
7. publicstaticvoid main(String s[]) {
8. JFrame frame = new JFrame("JFrame Example");
9. JPanel panel = new JPanel();
10. panel.setLayout(new FlowLayout());
11. JLabel label = new JLabel("JFrame By Example");
12. JButton button = new JButton();
13. button.setText("Button");
14. panel.add(label); panel.add(button);
15. frame.add(panel); frame.setSize(200, 300);
16. frame.setLocationRelativeTo(null);
17. frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
18. frame.setVisible(true); } }
Output
Java JTextArea
The object of a JTextArea class is a multi line region that displays text. It
allows the editing of multiple line text. It inherits JTextComponent class
JRadioButton Constructors
1. JRadioButton(): It is used to create an unselected radio button with
no text.
2. JRadioButton(Label): It is used to create an unselected radio button
with specified text.
3. JRadioButton(Label, boolean): It is used to create a radio button
with the specified text and selected status.
ButtonGroup
This class is used to place multiple RadioButton into a single group. So the
user can select only one value from that group. We can add RadioButtons to
the ButtonGroup by using the add method.
Example : add(jrb);
Syntax : ButtonGroup bg = new ButtonGroup();
JCheckBox
This component allows the user to select multiple items from a group of
items. It is used to create a CheckBox. It is used to turn an option ON or
OFF.
Declaration: public class JCheckBox extends
JToggleButton implements AccessibleJCheckBox Constructors
1. JCheckBox(): It is used to create an initially unselected checkbox
button with no text, no icon.
2. JCheckBox(Label): It is used to create an initially unselected
checkbox with text.
3. JCheckBox(Label, boolean): It is used to create a checkbox with
text and specifies whether or not it is initially selected.
4. JCheckBox(Action a): It is used to create a checkbox where
properties are taken from the Action supplied.
JTextField
The JTextField component allows the user to type some text in a single line.
It basically inherits the JTextComponent class.
Declaration: public class JTextField extends
JTextComponent implements SwingConstants
Syntax: JTextField jtf = new JTextField();
JTextField Constructors
1. JTextField(): It is used to create a new Text Field.
2. JTextField(String text): It is used to create a new Text Field
initialized with the specified text.
3. JTextField(String text, int columns): It is used to create a new Text
field initialized with the specified text and columns.
4. JTextField(int columns): It is used to create a new empty TextField
with the specified number of columns.
JTextArea
The JTextArea component allows the user to type the text in multiple lines.
It also allows the editing of multiple-line text. It basically inherits the
JTextComponent class.
Declaration: public class JTextArea extends JTextComponent
Syntax: JTextArea jta = new JTextArea();JTextArea
Constructors
1. JTextArea(): It is used to create a text area that displays no text
initially.
2. JTextarea(String s): It is used to create a text area that displays
specified text initially.
3. JTextArea(int row, int column): It is used to create a text area with
the specified number of rows and columns that display no text initially.
4. JTextarea(String s, int row, int column): It is used to create a text
area with the specified number of rows and columns that display
specified text.
JButton
This component can be used to perform some operations when the user clicks
on it. When the button is pushed, the application results in some action. It
basically inherits the AbstractButton class.
Declaration: public class JButton extends AbstractButton implements
Accessible
Syntax: JButton jb = new JButton();
JButton Constructors
1. JButton(): It is used to create a button with no text and icon.
2. JButton(String s): It is used to create a button with the specified
text.
3. JButton(Icon i): It is used to create a button with the specified icon
object.
Border
The border is an interface using which we can apply a border to every
component. To create the borders we have to use the methods available in
BorderFactory class. We can apply the created border to any component by
using SetBorder() method.Component.setBorder(Border);Methods of
Border
1.Border createLineBorder(Color, int), Border
createEtchedBorder(int, Color, Color), Border
createBevelBorder(int, Color, Color), MatteBorder
createMatteBorder(int, int, int, int, Icon) TitledBorder
createTitledBorder(Border, String, int, int, Font, Color),.
CompoundBorder createCompoundBorder(Border, Border):
JComboBox
This component will display a group of items as a drop-down menu from
which one item can be selected. It basically inherits JComponent class. We
can add the items to the ComboBox by using the addItem() method.
Example: jcb.addItem(item);
Declaration: public class JComboBox extends JComponent
implements ItemSelectable, ListDataListener, ActionListener,
Accessible
Syntax: JComboBox jcb = new JComboBox();
JComboBox Constructors
1. JComboBox(): It is used to create a JComboBox with a default data
model.
2. JComboBox(Object[] items): It is used to create a JComboBox that
contains the elements in the specified array.
3. JComboBox(Vector<?> items): It is used to create a JComboBox
that contains the elements in the specified Vector.
JTabbedPane
It is a pane that can contain tabs and each tab can display any component in
the same pane. It is used to switch between a group of components by
clicking on a tab with a given title or icon. To add the tabs to the
JTabbedPane we can use the following methods:
jtp.add(TabName, Components)jtp.addTab(TabName,
Components)
Declaration: public class JTabbedPane extends JComponent
implements Serializable, Accessible, SwingConstants
Syntax: JTabbedPane jtp = new JTabbedPane();
JTabbedPane Constructors
1. JTabbedPane(): It is used to create an empty TabbedPane.
2. JTabbedPane(int tabPlacement): It is used to create an empty
TabbedPane with a specified tab placement.
3. JTabbedPane(int tabPlacement, int tabLayoutPolicy): It is used
to create an empty TabbedPane with a specified tab placement and tab
layout policy
JPasswordField
It is a text component specialized for password entry. It allows the
editing of a single line of text. It basically inherits the JTextField class.
Declaration: public class JPasswordField extends JTextField
Syntax: JPasswordField jpf = new JPasswordField(); JPasswordFiled
Constructors
1. JPasswordField(): It is used to construct a new JPasswordField, with
a default document, null starting text string, and column width.
2. JPasswordField(int columns): It is used to construct a new empty
JPasswordField with the specified number of columns.
3. JPasswordField(String text): It is used to construct a new
JPasswordField initialized with the specified text.
4. JPasswordField(String text, int columns): It is used to construct a
new JPasswordField initialized with the specified text and columns.
Look and Feel Management in Java Swing
To manage a look and feel for the UI components swing package provides
look and feel managers. In the Swing environment, look and feel are
controlled by the UI Manager class.
Look and Feel Managements are shown below:
1. MetalLookAndFeel ,MotifLookAndFeel ,NimbusLooAndFeel
2. WindowsLookAndFeel ,WindowsClassicLookAndFeelThe
above looks and feels are the predefined classes.Steps to apply a
look and feel:
1. Decide a look and feel type and inform a UI Manager to set a given look and
feel and this will be done using setLookAndFeel().
2. Once the look and feel are set we can apply to the UI Component or
Component tree
These controls are subclasses of Component. Although this is not a particularly ric set
of controls, it is sufficient for simple applications. (Note that both Swing and JavaF
provide a substantially larger, more sophisticated set of controls.)
Short Questions
1.what are the applet basics?
2.what is the HTML applet tag ?
3.what are the adapter classes?
4.what is layout manager?
Long Questions
5. Features of applet and explain?
6.Explain about SWING?
7. Explain about layout managers and menus ?
8. Explain the events in GUI programming
UNIT-5
Networking programming with java
Java Networking
Java Networking is a concept of connecting two or more computing devices
together so that we can share resources. Java socket programming
provides facility to share data between different computing devices.
1. IP Address
2. Protocol
3. Port Number
4. MAC Address
6. Socket
1) IP Address
IP address is a unique number assigned to a node of a network e.g.
192.168.0.1 . It is composed of octets that range from 0 to 255.
2) Protocol
A protocol is a set of rules basically that is followed for communication. For
example:
oTCP, FTP ,Telnet ,SMTP,POP etc
3) Port Number
The port number is used to uniquely identify different applications. It acts as
a communication endpoint between applications.
4) MAC Address
MAC (Media Access Control) Address is a unique identifier of NIC (Network
Interface Controller). A network node can have multiple NIC but each with
unique MAC.
6) Socket
A socket is an endpoint between two way communication.
package
INTERFACES
CookiePolicy CookieStore
FileNameMap SocketOption
InetAddress ServerSocket
SocketImplFactory ProtocolFamily
InetAddress
Inet Address encapsulates both numerical IP address and the domain name
for that address. Inet address can handle both IPv4 and Ipv6 addresses. Inet
Address class has no visible constructor. To create an inet Address object,
you have to use Factory methods.
Three commonly used Inet Address factory methods are.
URL class
Java URL Class present in java.net package, deals with URL (Uniform
Resource Locator) which uniquely identify or locate resources on internet.
Java includes support for both IPv4 and IPv6 addresses. Because of this,
two subclassesof InetAddress were
created: Inet4Address and Inet6Address. Inet4Address represents
atraditional-style IPv4 address. Inet6Address encapsulates a newer
IPv6 address. Because they are subclasses of InetAddress, an
InetAddress reference can refer to either. This is one way that Java was
able to add IPv6 functionality without breaking existing code or adding many
more classes. For the most part, you can simply use InetAddress when
working with IP addresses because it can accommodate both styles
Java Socket Programming
2. Port number.
Here, we are going to make one-way client and server communication. In this
application, client sends a message to the server, server reads the message
and prints it. Here, two classes are being used: Socket and ServerSocket.
The Socket class is used to communicate client and server. Through this
class, we can read and write message. The ServerSocket class is used at
server-side. The accept() method of ServerSocket class blocks the console
until the client is connected. After the successful connection of client, it
returns the instance of Socket at server-side.
Factory Methods
The InetAddress class has no visible constructors. To create an
InetAddress object, you have to use one of the available factory methods.
Factory methods are merely a convention whereby static methods in a class
return an instance of that class. This is done in lieu of overloading a
constructor with various parameter lists when having unique method names
makes the results much clearer. Three commonly used InetAddress factory
methods are shown here:
UnknownHostException
The getLocalHost( ) method simply returns the InetAddress object that
represents the local host. The getByName( ) method returns an
InetAddress for a host name passed to it. If these methods are unable to
resolve the host name, they throw an UnknownHostException.
Instance Methods
The InetAddress class has several other methods, which can be used on
the objects returned by the methods just discussed. Here are some of the
more commonly used methods:
boolean equals(Object other) : Returns true if this object has the same
Internet address as other.
String toString( ) : Returns a string that lists the host name and the IP
address for convenience.
Java URL
The Java URL class represents an URL. URL is an acronym for Uniform
Resource Locator. It points to a resource on the World Wide Web. For
example:
4. File Name or directory name: In this case, index.jsp is the file name.
URL(String spec)
Creates an instance of a URL from the given protocol, host, port number, and
file.
URL(String protocol, String host, int port, String file,
URLStreamHandler handler)
Creates an instance of a URL from the given protocol, host, port number, file,
and handler.
Creates an instance of a URL from the given protocol name, host name, and
file name.
Creates an instance of a URL by parsing the given spec with the specified
handler within a given context.
Method Description
The URLConnection class provides many methods, we can display all the data
of a webpage by using the getInputStream() method. The getInputStream()
method returns all the data of the specified URL in the stream that can be
read and displayed.
1. ServerSocket API
The ServerSocketclass is used to implement a server program. Here are the
typical steps involve in developing a server program:
The steps 1 to 5 can be repeated for each new client. And each new
connection should be handled by a separate thread.
Note that the accept() method blocks the current thread until a connection is
made. And the connection is represented by the returned Socket object.
The InputStream allows you to read data at low level: read to a byte array. So
if you want to read the data at higher level, wrap it in an InputStreamReader to
read data as characters:
As the OutputStream provides only low-level methods (writing data as a byte array), y
can wrap it in a PrintWriter to send data in text format, for example:
The argument true indicates that the writer flushes the data after each method call (au
flush).
Invoke the close() method on the client Socket to terminate the connection with the clien
1 socket.close();
This method also closes the socket’s InputStream and OutputStream,
and it c throw IOException if an I/O error occurs when closing the
socket. Terminate t server:
A server should be always running, waiting for incoming requests from clients. In case t
server must be stopped for some reasons, call the close() method on the ServerSock
instance:
1 serverSocket.close();
The ServerSocket class also provides other methods which you can consult in
Javadochere
while (true) {
Socket socket = serverSocket.accept();
writer.println(new Date().toString());}
} catch (IOException ex) {
System.out.println("Server exception: " + ex.getMessage());
ex.printStackTrace();}}}
And the following code is for a client program that simply connects to the serv
and prints the data received, and then terminates:
import java.net.*;
import java.io.*;
System.out.println(time);
1. import java.io.*;
2. import java.net.*;
3. publicclass MyServer {
4. publicstaticvoid main(String[] args){
5. try{
6. ServerSocket ss=new ServerSocket(6666);
7. Socket s=ss.accept();//establishes connection
8. DataInputStream dis=new DataInputStream(s.getInputStream());
9. String str=(String)dis.readUTF();
10. System.out.println("message= "+str);
11. ss.close();
12. }catch(Exception e){System.out.println(e);} }} File: MyClient.java
1. import java.io.*;
2. import java.net.*;
3. publicclass MyClient {
4. publicstaticvoid main(String[] args) {
5. try{
6. Socket s=new Socket("localhost",6666);
7. DataOutputStream dout=new
DataOutputStream(s.getOutputStream());
8. dout.writeUTF("Hello Server");
9. dout.flush();
10. dout.close();
11. s.close();
12. }catch(Exception e){System.out.println(e);} }}
Java Database Connectivity with 5 Step
There are 5 steps to connect any java application with the database using
JDBC. These steps are as follows: oRegister the Driver class oCreate
connection oCreate statement oExecute queries oClose connection
1) Register the driver class
The forName() method of Class class is used to register the driver class.
This method is used to dynamically load the driver class.
createStatement()throws SQLException
close()throws SQLException
Create a Table
Before establishing connection, let's first create a table in oracle database.
Following is the SQL query to create a table.
1. import java.sql.*;
2. class OracleCon{
3. publicstaticvoid main(String args[]){
4. try{
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6. Connection con=DriverManager.getConnection(
7. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
8. Statement stmt=con.createStatement();
9. ResultSet rs=stmt.executeQuery("select * from emp");
10. while(rs.next())
11. System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString
(3));
12. con.close(); }catch(Exception e){ System.out.println(e);} }}
To connect java application with the Oracle database ojdbc14.jar file is
required to be loaded.
download the jar file ojdbc14.jar
2. set classpath
2) set classpath:
There are two ways to set the classpath:
o temporary
o permanent
1.C:>set classpath=c:\folder\ojdbc14.jar;.;
You can read your big query and store results in some kind of buffer. And
only when buffer is full you should run subquery for all data collected in
buffer. This significantly reduces number of SQL statements to execute.
2. Using efficient maps to store content from many selects.
If your records are no so big you can store them all at once event for 4 mln
table.
When you load a lot of records from database it is very, very important to set
proper fetch size on your jdbc connection. This reduces number of physical
hits to database socket and speeds your process
4. PreparedStatement
Java performance tuning tips relevent for tuning JDBC usage. The top tips
are:
Short Questions
1.What is the Java networking?
2. What is the inet address?
3.How to knowing IP address?
4.what are the stages in JDBC program?
Long Questions
5. Briefly explain about networking classes and interfaces ?
6. Explain about URL - URL connection classes
7. Explain the how to create server that sends and receives data ?
8. How to improving the performance of JDBC Program and explain?
Section-A
Answer any five from the following 5*2=10m
1.what is access protection?
2.what are the importing packages?
3.What are the exception types?
4.what is thread model?
5.what is polymorphism?
6.what is inheritance?
7.Explain about constructors.
8.what is method overriding in java?
Section- B
ANSWER THE FOLLOWING 2*10=20m
UNIT -1
9.Explain the 1.what are the applet basics?
2.what is the HTML applet tag ?
3.what are the adapter classes?
4.what is layout manager? of object oriented programming?
Or
10.Write about inheritance to classes and it's methods?
UNIT-2
11.Explain about packages and interfaces?
Or
12.Discuss about the concept of exception handling?
S.V.U. COLLEGE OF COMMERCE MANAGEMENT AND
COMPUTER SCIENCE :: TIRUPATHI
DEPARTMENT OF COMPUTER SCIENCE
Time:2hours INTERNAL EXAMINATIONS -2 MAX MARKS:30
Section-A
Answer any five from the following 5*2=10m
PART- A
Answer any 5 questions from the following 5*2=10M
1.a) What are the commands used for compilation and execution of java
programs?
b) What is java bytecode? What is JVM?
c) What is a package? Write the syntax to define a “package”.
d) What does Java API package contain?
e) What are the run time errors and logical errors in Java?
f) What is an exception? What are two exception types?
g) What are the properties of hash table?
h) Differentiate between Iterator and for-each.
i) What are the differences between an applet and stand alone java application?
j) What are the methods in applet life cycle?
PART-B
Answer the following 10*5=50M
Unit-1
2.a) Exaplain briefly class, public, static, void, main, string[] and
system.out.println() key words.
b) Write a java method to find minimum value in given two values.
OR
3.a) Discuss about precedence of operators and associativity.
b) Explain the polymorphism and overloading with an example.
Unit-2
4.a) Write the benefits of packages and interfaces.
b) How can we add a class to a package? Write about relative and absolute
paths.
OR
5.a) Write the differences between interface and abstract class.
b) Write the procedure to a create package with multiple public classes.
Unit-3
6.a) What is exception handling? Explain an example of exception handling in
the case of division by zero.
b)Write a simple java program to create threads.
OR
7.a) Write about some Java’s built in exceptions.
b) With an example, demonstrate the concept of thread synchronization.
Unit-4
OR
9.a) Compare and contrast any two collection algorithms.
b) Explain the process of accessing collection through iterator.
Unit-5
10.a) Write the step wise procedure to create and run an applet.
b) List the event classes and Listener Interfaces.
OR
11. Write an applet code to demonstrate parameter passing to applet.