CS6501 Internet Programming V - Semester

You might also like

You are on page 1of 16

CS6501 – INTERNET PROGRAMMING

IN

V - SEMESTER

STUDY MATERIAL

CS6501
INTERNET PROGRAMMING

ANNA UNIVERSITY

REGULATION 2013

PREPARED BY V.BALAMURUGAN, ASST.PROF/CSE

PREPARED BY V.BALAMURUGAN, ASST.PROF/CSE


CS6501 – INTERNET PROGRAMMING
IN
5. Define class and object.
UNIT – 1 JAVA PROGRAMMING  A class is defined as collection of variables and methods
that are bound together for manipulation.
Part - A  It is a template/blueprint that tells the behavior and state of
an object. Ex: car.
1. Mention the features (principles) of Java.  Variables (state) : no_of_wheels, cc, topspeed, mileage
 Simple and object oriented  Methods (behavior) : move(), brake(), start(), stop()
 Robust and secure  An object is defined as the instance of a class; they
 Architecture neutral and portable represent real world entity. Ex: Maruti Swift.
 High performance
 Interpreted, threaded, dynamic 6. What is an array? What are its types?
2. Mention the differences between C++ and Java.  An array is defined as the data structure to store the
C++ Java collection of elements of similar elements together in a same
Compiled language Compiled and interpreted name stored in continuous memory locations.
Platform dependent Platform independent  Array index always start from zero.
Not a pure OOP language Pure OOP language  Types: One dimensional array, Multi-dimensional array.
No multi-threading, GUI, DB Multi-threading, GUI, JDBC  Ex: int a [ ] = new int [5];
connectivity available
It cannot be embedded Can be embedded in Scripts 7. What are packages in Java?
Pointers and templates are No pointers and templates  A package is a collection of classes and interfaces that
available provides a high-level layer of access protection and name
Simple Safe, reliable and powerful space management.
Compilers: DevC++, Turbo Compiler: JAVAC  To organize files when a project consists of multiple modules.
C++, GCC, etc  It eliminates naming conflicts when different packages have
classes same names.
3. What are the data types in Java?  Packages access level also allows protecting data from non-
Type Capacity Range Default authorized classes.
value
byte 1B ( 8 bits) -27 to 27 - 1 0 8. What is method overloading and overriding?
short 2B (16 bits) -215 to 215 – 1 0 Method overloading Method overriding
int 4B (32 bits) -231 to 231 – 1 0 If a class has multiple If a child class has the same
long 8B (64 bits) -263 to 263 – 1 0.0L methods in same name, but method as defined in its
float 32 bits IEEE 754 floating point 0.0f different parameters, then it is parent class, then it is called
double 64 bits IEEE 754 floating point 0.0D called method overloading method overriding
boolean 1 bit True / False False Compile-time polymorphism Run-time polymorphism
char 16 bits ‘\u0000’ to ‘\uffff’ NA
9. What is the use of static keyword?
4. What is the use of break and continue statements? Static variable: A variable whose value remains constant for the
Break: entire class. It is used to share common properties of a class.
 Break statement is used to break the execution of the Static method: A method that access static data members alone.
current executing loop or block. It can be accessed without an object.
 Statements after the break statement will not be executed. Static block: A block that initializes static data members. It is
Continue: executed before the main method.
 Continue statement is used to skip the current iteration of
the current executing loop or block. 10. What is an abstract class?
 Statements after the continue statement will be executed.  A super class that does nothing, but lists the features of the
Break Continue other classes are called abstract class.
for(int i = 0; i < 5; i++ ) for(int i = 0; i < 5; i++ )  Abstract keyword is used.
{ {  It may contain abstract methods.
if ( i = = 3) break; if ( i = = 3) continue;  If a class has at least one abstract method, then that class
System.out.println(i); System.out.println(i); must be declared abstract.
} }
O/p:- O/p:- 11. What are interfaces?
0 0  An interface in java is defined as the reference type in java,
1 1 which is similar to a class, but not actually a class.
2 2  It is a collection of abstract methods
4  If a class implements interface, it inherits all the abstract
methods of that interface
 Objects cannot be created for interface
PREPARED BY V.BALAMURUGAN, ASST.PROF/CSE
CS6501 – INTERNET PROGRAMMING
IN
12. What is an exception? Bring out its types. 17. What is an applet? Mention its advantages.
 An exception (or exceptional event) is a problem that  Applets are small applications that are accessed on an
arises during the execution of a program. Internet server, transported over the Internet, automatically
 When an Exception occurs the normal flow of the program installed, and run as part of a web document.
is disrupted and the program/Application terminates  After an applet arrives on the client, it has limited access to
abnormally, which is not recommended, therefore these resources
exceptions are to be handled.  It produces GUI without introducing the risk of viruses or
 Reasons: User has entered invalid data/ File not found/ breaching data integrity.
Network connection lost, etc.  They are used in performing arithmetic operations, displaying
 Checked exception: an exception that occurs at the graphics, playing sounds, creating animation, etc.
compile time, cannot simply be ignored Ex: IOException, Advantages:
SQLException  To display dynamic web pages (constantly changing).
 Unchecked exception: an exception that occurs at the  To add special effects such as sound, animation, etc.
time of execution including programming bugs. Ex:  They can be run in many platforms such as Windows, Linux,
NullPointerException, ArrayIndexOutOfBoundsException Mac., and supported by different browsers such as IE,
 Error: It is irrecoverable. It arises beyond the control of the Netscape, Mozilla, etc.
user
PART – B
13. What is the use of finally keyword in Java? 1. Explain the structure and execution of a Java program.
 “finally” block provides assurance of execution of some  Invented by James Gosling and his team on 23-5-1995
important code that must be executed after the try block.  It is a language for internet
 If an exception happens at try block, its execution gets  Theme: Written Once – Run Anywhere (WORA)
break off. “finally” block executes finally at the end.  It is a platform independent, strongly typed language.
 It is sometimes called as “clean-up” code.  Editions of Java: Java card, J2ME, J2SE, J2EE
 Principles of Java: Simple and object oriented, Robust and
14. What are different types of access modifiers? secure, architecture neutral and portable, high performance,
 “Access specifiers” are keywords that specify the type of interpreted-threaded and dynamic.
access to the member of a class. They allow privileges to  It supports GUI, JBDC, embedding, multithreading
parts of a program such as functions and variables.  It doesnot support pointers and templates
 Public : Anything declared as public can be accessed from  It is a pure OOP language, interpreted and compiled.
anywhere. Structure of a Java program
 Private : Anything declared as private can’t be accessed Documentation section(optional)
outside of its class. Package statements(optional)
 Protected : Anything declared as protected can be Import statements(optional)
accessed by classes in the same package and subclasses Main class definition
in the other packages. Main method
 Default : Can be accessed only to classes in the same Other classes (optional)
package Example:-
/*This is a hello world program */
class sample
15. Define threads.
{
 A thread in java is defined as the smallest unit of a program public static void main(String bala[ ] )
that runs continuously, which is a part of a process. {
 It is a light weight process in Java System.out.println(“Hello world”);
 Each thread performs a certain task. }
}
16. What is multithreading? Give its advantages. O/p:-
 A multithreaded program contains two or more parts that >javac sample.java  (compilation)
can run concurrently. >java sample  (Execution)
 Each part of such a program is called a thread, and each Hello world
thread defines a separate path of execution.  Sample is the main class name and program name
Advantages:  Main method should always be public, static, void
 Threads share common memory area; thereby it saves  public – it should be accessible by all other classes
memory.  static – allocate memory statically in jvm
 Context-switching between threads takes less time than  void – it does not return any values
that of process.  String bala[ ] – String class, bala [ ] is the array object
 It is used in Games and animation  This parameter is passed in main method for getting and
manipulating command line arguments (CLA)
 User can perform multiple operations at the same time.
PREPARED BY V.BALAMURUGAN, ASST.PROF/CSE
CS6501 – INTERNET PROGRAMMING
IN
 System is a class; out is a output stream in console; Relational operators
println() is a method to write onto console screen - There are 6 relational operators in java which computes the
 There should be at least one class and main method relation between any two operands of same data type.
Compilation and execution of a Java program - Its return value is binary: Either true or false.

public class relational


{
public static void main(String bala[])
{ O/p:-
int a=10, b=20;
System.out.println(a==b); false
System.out.println(a!=b); true
System.out.println(a > b); false
System.out.println(a < b); true
System.out.println(a >= b); false
System.out.println(a <= b); true
}
}

The Bitwise Operators


- Java contains some bitwise operators that perform operation on
the operands after converting them into Binary Digits (bits).
 Source code (sample.java) is received by JAVAC when - Bitwise AND(&), bitwise OR ( | ), bitwise XOR (^), negation (~),
javac command is issued by user in command prompt left shift (<<), right shift (>>), right zero fill (>>>)
 JAVAC checks the syntax and on successful compilation,
creates sample.class file (Byte code) class bitwise
 This sample.class is platform independent file, that can be {
executed anywhere if Java is supported. public static void main(String args[])
 Then the sample.class file is executed if the user enters { O/p:-
java command in command prompt int a=8, b=10;
 JVM has many internal components, such as class loader, System.out.println(a&b); 8
byte code verifier and JIT System.out.println(a|b); 10
 Class loader loads the byte code file into JVM interpreter System.out.println(a^b); 2
 Byte code verifier performs security check System.out.println(~a); -9
 JIT – Just-In-Time compiler converts sample.class file into System.out.println(a<<2); 32
native machine code very faster System.out.println(a>>2); 2
System.out.println(a>>>2); 2
 This native machine code is run in the machine.
}
}
2. Explain in detail about operators in java with example.
Logical operators
Arithmetic Operators
- Logical operators perform the Logic operations on two operands.
 All these operators are binary and hence take two operands. - There are three basic logical operators such as Logical AND (&&),
 - Addition +, subtraction -, multiplication *, division /, modulus Logical OR (||), logical NOT (!)
%, Increment ++, decrement --
public class arithmetic { public class logical
public static void main(String bala[]) { O/p:- { O/p:-
int a=10, b=20, c=25, d=25; public static void main(String bala[])
System.out.println(a+b); 30 false
{
System.out.println(a-b); -10 true
boolean a = true, b=false;
System.out.println(a*b); 200 false
System.out.println(a&&b);
System.out.println(b/a); 2
System.out.println(a||b);
System.out.println(b%a); 0
System.out.println( !(a||b) );
System.out.println(a++); 10
}
System.out.println(++a); 12
}
System.out.println(a--); 12
System.out.println(--a); 10
System.out.println(a++ + ++a); 22
System.out.println(a++ - ++a); -2
System.out.println(a-- + --a); 26
System.out.println(a-- - --a); 2

PREPARED BY V.BALAMURUGAN, ASST.PROF/CSE


CS6501 – INTERNET PROGRAMMING

} } IN
Assignment Operator 1-D array example:-
- The assignment operator is the single equal sign = class array
- The assignment operator works in Java much as it does in {
any other computer language. public static void main(String bala [ ] )
{
public class assignment int a [ ] = { 1, 2, 3 }; O/p:-
{ int b [ ] = { 2, 4, 6 }; 3
public static void main(String bala[]) int c [ ] = new int [ 3 ] ;
6
{ for(int i = 0; i < 3 ; i++) 9
int a=8, b=15; O/p:- {
System.out.println(a+=b); 23 c [ i ] = a [ i ] + b [ i ];
System.out.println(a-=b); 8 System.out.println(c[i]);
System.out.println(a*=b); 120 }
System.out.println(a/=b); 8 }
System.out.println(a%=b); 8 }
System.out.println(a<=2); false
System.out.println(a>=2); true 2-D array example:-
System.out.println(a&=b); 8 class array
System.out.println(a^=b); 7 {
System.out.println(a|=b); 15 public static void main(String bala [ ] )
} {
} int a [ ] [ ] = { { 1, 1, 1 }, {1,1,1}, {1,1,1} } ;
int b [ ] [ ] = { { 2, 2, 2 }, {2,2,2}, {2,2,2} } ; O/p:-
Conditional Operator int c [ ] [ ] = new int [ 3 ] [ 3 ] ; 333
- It is also called as Ternary/Conditional/Question-colon/three- for(int i = 0; i < 3 ; i++) 333
way operator { 333
- It can replace “if-then-else” for(int j = 0; j<3; j++)
- General form: expression1? expression2:expression3 {
- If expression1 is true, then expression2 is evaluated; c[i][j]=a[i][j] +b[i][j];
otherwise, expression3 is evaluated. System.out.println(c[ i ] [ j ] );
}
public class conditional System.out.println(“\n”);
{ }
public static void main(String bala[]) }
{ }
int a = 20, b; O/p:-
b = (a = = 1) ? 50 : 100; 100 4. Explain the concept of inheritance and its types.
System.out.println(b);  Inheritance in java is defined as the process of deriving
} a child class from a parent class. The child class
} acquires all the properties of the parent class.
3. What is an array? Explain the types of array with ex.
 “extends” is the keyword used to inherit the properties
Defn: An array in Java is defined as a collection of elements of of parent class.
similar data type, which are stored in continuous memory Ex:
locations. Class parent Class child extends
 The elements are accessed by their indexes. { parent
 Array index always starts from zero ------------- {
 The size of the array is fixed. ------------- -------
 All the elements are stored under the same name. } -------
Ex:- }
 int a [ ] = new int [ 5 ] ; //declaration
 int [ ] a = new int [ 5 ]; //another way of declaration  Types: Single, Multilevel, Hierarchical (Multiple &
 int [ ] a = {1,2,3}; // declared and initialized Hybrid - achieved thru interface)
Types:-  Advantages: Flexibility, Reusability, Extensibility, Data
 Single Dimensional array (1-D array) hiding, Overriding
- Here elements are stored with reference to rows only.
 Multi-dimensional array (n-D array)
- Here elements are stored with reference to rows and
columns. (rows x columns)

PREPARED BY V.BALAMURUGAN, ASST.PROF/CSE


CS6501 – INTERNET PROGRAMMING
IN
Single inheritance:-
 Single inheritance in java is defined as the process of class derived2 extends derived1
deriving a single derived class from a single base class. {
 It is the simplest form of inheritance in Java. int c=30;
void add()
class base {
{ System.out.println(a+b+c);
int a=10; base }
void value() }
{ Class multilevel
System.out.println(a); derived {
} public static void main(String bala[])
} {
class derived extends base base b = new base();
{ derived1 d1 = new derived1();
int b=20; O/p:-
O/p:- derived2 d2 = new derived2();
void add() 10
10 d2.value1(); 20
{ 30 d2.value2(); 60
System.out.println(a+b); d2.add();
} }
} }
class single
{
public static void main(String bala[]) Hierarchical inheritance
{  It is the process of deriving more than one child class from
base b = new base(); the same parent class.
derived d = new derived();  Two or more child classes having the same parent class.
d.value();  hierarchical levels of inheritance is followed here.
d.add();
} class base
} {
int a=10;
Multilevel Inheritance:- void value1()
 It is the process of deriving a child class from another {
child class. System.out.println(a);
 Multiple levels of inheritance is followed here. }
} base
class base class derived1 extends base
{ {
int a=10; int b=20; derived1 derived2
void value1() void add1()
{ {
System.out.println(a); System.out.println(a+b);
} }
} base }
class derived1 extends base class derived2 extends base
{ {
int b=20; derived1 int c=30;
void value2() void add2()
{ {
System.out.println(b); derived2 System.out.println(a+c);
} }
} }

PREPARED BY V.BALAMURUGAN, ASST.PROF/CSE


CS6501 – INTERNET PROGRAMMING
IN
class hierarchical class multilevel
{ {
public static void main(String bala[]) public static void main(String bala[])
{ { O/p:-
base b = new base(); base b = new base(); 10
O/p:- 20
derived1 d1 = new derived1(); 10 derived1 d1 = new derived1();
derived2 d1 = new derived2(); derived2 d2 = new derived2(); 60
10
d1.value1(); derived3 d3 = new derived3(); 10
30
d2.value1(); 40 20
d1.add1(); d2.value1(); 70
d2.add2(); d2.value2();
} d2.add1();
}
d3.value1();
Hybrid inheritance d3.value2();
 If more than tyo types of inheritance combined together d3.add2();
in deriving child classes, it is called hybrid inheritance. }
 It may be a combination of single-multilevel, multilevel- }
hierarchical, etc.
Disadvantages of Inheritance:-
class base  Both classes (super and subclasses) are tightly-coupled.
{  As they are tightly coupled (bonded each other strongly
int a=10; with extends keyword), they cannot work independently of
void value1() each other.
{  Changing the code in super class method also affects the
System.out.println(a); subclass functionality.
}  If super class method is deleted, the code may not work as
} subclass may call the super class method with super
class derived1 extends base keyword.
{
int b=20; 5. Explain abstract classes in Java with ex.
void value2()  An abstract class is defined as a super class in java that does
{ nothing, but lists out the common features of the other class
System.out.println(b);  “abstract” keyword is used
}  It may contain abstract methods (methods without body)
}  If a class has at least one abstract method, then the class must
class derived2 extends derived1 be declared as “abstract”
{  Abstract class can’t be instantiated (object cannot be created)
int c=30;  To use abstract class, we have to inherit it from another class,
void add1() then define the abstract methods in it.
{  If abstract class is inherited, all the abstract methods in it,
System.out.println(a+b+c); base should be defined in derived class.
}
} abstract class abs
{
class derived3 extends derived1 derived1
abstract void absmethod();
{ }
int d=40; class sample extends abs
void add2() Derived3 derived2 {
{ void absmethod()
System.out.println(a+b+d); {
} -------------------
} -------------------
}
}

PREPARED BY V.BALAMURUGAN, ASST.PROF/CSE


CS6501 – INTERNET PROGRAMMING
IN
abstract class A Differences between an abstract class and an interface:-
{ Abstract class Interface
abstract void absmethod(); We can inherit only one We can inherit more than one
} abstract class interfaces
class B extends A abstract class members can Interface members are only
be public, private or protected public
{
Method may or may not have No method definition(default)
void absmethod() definition
{ Efficient Slow
System.out.println("One "); They can be extended They can be implemented
} Variables are non-final Variables are final (default)
}
class C extends A inter.java
{ public interface inter
void absmethod() {
{ void imethod();
System.out.println("Two "); }
}
} iface.java
class A implements inter
class abs
{
{ public void imethod()
public static void main(String arg[]) {
{ System.out.print("defined here");
B b=new B(); O/p: }
C c=new C(); one }
b.absmethod(); Two class iface
c.absmethod(); {
} public static void main(String[] bala)
} {
A a=new A();
6. Explain interfaces in java with ex. a.imethod();
 Interface in java is defined as a reference type in java, which }
is similar to a class, but actually not a class. }
 It is a collection of abstract methods
F:\ex>javac iface.java
 If a class implements interface, it inherits the abstract
F:\ex>java iface
methods of the interface.
defined here
 Method body will exist only for concrete methods and static
methods inside an interface.
7. Explain the concept of inner class and its types with ex.
 Class = variables + methods of an object.
 Inner class in java is defined as a class within another class
 Interface = behavior that a class implements.
 They are also called as nested class
Class one
Similarities between a class and an interface
{
 Both can contain any number of methods Class two
 Both are saved as .java extension {
 Both can be arranged within a package -------
 Both can create .class file upon successful compilation -------
Differences between a class and an interface }
Class Interface } Nested class
Class keyword is used Interface keyword is used
All Methods are defined Not all Methods are defined
Executable source code Outline source code Non-static static inner
Object can be created Object can’t be created inner class class
Public, private, protected Only public is supported
Members are constant/final Members are always final
Constructors available No constructors
A Class can be extended An interface can be implemented Normal Method- Anonymous
No Multiple inheritance Multiple inheritance supported inner local inner inner
By Default: private specifier By default: abstract & public class class class

PREPARED BY V.BALAMURUGAN, ASST.PROF/CSE


CS6501 – INTERNET PROGRAMMING
IN
Static inner class Method-local inner class:-
 They are the static members of another class  A class that is defined within a method of outer class
 Static keyword is present before the inner class  No access specifier is used in declaration
 Static member of outer class are visible to static inner class  Its scope is within the block it is declared
 Non static members of outer lass are invisible to static inner class  They are hides from outside world

outer.java outer.java
class outer public class outer
{ {
static class inner void omethod()
{ {
public void imethod() int a=10;
{ class inner
System.out.println("Inner class"); {
} public void imethod()
} {
public static void main(String[ ] bala) System.out.println(a);
{ }
outer o = new outer(); O/p:- }
inner i = new inner(); Inner class inner i = new inner();
i.imethod(); i.imethod();
} }
} public static void main(String bala[ ])
{
oter o = new outer(); O/p:-
Normal inner class o.omethod(); 10
 They are non-static member of outer class }
 They can access only non-static members of outer class }

innernormal.java
class outer Anonymous inner class
{  Local class without a name
class inner  One-shot class, created for ad-hoc purpose
{  It is used under these situations:-
public void imethod() - When a class has short body
{ - Only one instance of class needed
System.out.println("inner class"); - Class is used immediately after defining
}
} outer1.java
void omethod() abstract class anony
{ {
inner i = new inner(); abstract void absmethod();
i.imethod(); }
} public class outer1
} {
public class innernormal public static void main(String bala[ ])
{ {
public static void main(String bala[ ]) anony a = new anony()
{ {
outer o = new outer(); O/p:- public void absmethod()
o.omethod(); Inner class {
}
} System.out.println("anonymous class");
}
}; O/p:-
a.absmethod(); Anonymous class
}
}

PREPARED BY V.BALAMURUGAN, ASST.PROF/CSE


CS6501 – INTERNET PROGRAMMING
IN
8. Explain the concept of exception handling in java with ex. Keywords used
 Exception is an exceptional event which is a problem that try Error prone block of code to be
arises during the execution of the program, that is not monitored for exception
desired, breaks the normal flow of the execution. catch Each corresponding ‘try’ block
 So these exceptions have to be handled efficiently in order finally The code that must be executed even
to avoid program getting crashed. though exception may/may not occur.
Reasons throw To throw the specific exception from
 User entered invalid input. program code
 File not found throws It specifies exceptions that can be
 Network connection lost thrown by particular method.
 JVM ran out of memory
Benefits sample1.java
 Avoid crashing of applications abruptly. class sample1
 Various types of errors grouped together. {
Types public static void main(String bala[])
i) Checked exception {
 It occurs during the compile time. int a;
 It cannot be ignored. try
 Programmer should take care/handle exceptions. {
 Ex: FileNotFoundException a=10/0;
}
ii) Unchecked exception catch(ArithmeticException e)
 It occurs during runtime {
 It includes programming bugs, logical errors, etc. System.out.println("Div by zero error");
 It is ignored at the run time. }
 Ex: }
} O/p:-
int num[] = {1,2,3};
Div by zero error
System.out.println(num[10]);
Error:
ArrayIndexOutOfBoundsException
iii) Errors
- It is not exception, but actually problems.
- They occur beyond the programmers’ control
- It is ignored, because we cannot do anything about it.
- Ex: StackOverFlowError, JVM out of memory error.

java.lang Object throwable

Error Exception

Other
ClassNotFoundExceptio RunTimeExcep
IOException exception
n tion

ArithmeticExce IllegalAssignm IndexOutOfBo NullPointerExc


EOFExceptio FileNotFoundExc ption undsException eption
entException
n eption

ArrayIndexOutOfBoundsException

PREPARED BY V.BALAMURUGAN, ASST.PROF/CSE


CS6501 – INTERNET PROGRAMMING
IN
Multiple catch blocks for a single try block public static void main(String bala[])
class sample1 {
{ int a[] = {1,2};
public static void main(String bala[]) xyz(a);
{ }
int a[] = new int[5]; }
try O/p:-
{ java.lang.ArrayIndexOutOfBoundsException: 10
System.out.println(a[10]);
System.out.println(10/0);
} User-defined Exception
catch(ArrayIndexOutOfBoundsException e)
{ import java.lang.Exception;
System.out.println(e); class own extends Exception
} {
catch(ArithmeticException e) own(String msg)
{ {
System.out.println(e); super(msg);
} }
} }
} class sample1
O/p:- {
java.lang.ArrayIndexOutOfBoundsException: 10 public static void main(String bala[])
{
Finally Block int a=10;
class sample1 try
{ {
public static void main(String bala[]) if(a<20)
{ throw new own("This is
try userdefined Exception");
{ }
System.out.println(10/0); catch(own e)
} {
catch(ArithmeticException e) System.out.println(e);
{ }
System.out.println(e); }
} }
finally O/p:-
{ own: This is user-defined Exception
System.out.println("This is from
Finally block"); 9. What is a thread in Java? Explain how it is implemented.
}  A thread in java is defined as the smallest unit of a program
} that runs continuously, which is a part of a process.
}  It is a light weight process in Java
O/p:-  Each thread performs a certain task.
java.lang.ArithmeticException: / by zero
Implementation:-
This is from Finally block
1. By extending “Thread” class
2. By implementing “Runnable” interface
Method that throws exception
class sample1 Thread
{ implementation
static void xyz(int a[])
extends implements
{
try Class ex1 extends Thread Class ex2 implements Runnable
{
System.out.println(a[10]);
overrides overrides
}
catch(ArrayIndexOutOfBoundsException e) public void run()
{ {
System.out.println(e); ---------------
} }
PREPARED BY V.BALAMURUGAN, ASST.PROF/CSE
CS6501 – INTERNET PROGRAMMING

} IN
Life cycle of a thread:- Type-2 : Example program:-
class ex2 implements Runnable
{
public void run( )
{
System.out.println(“Thread is running”);
}
public static void main(String bala[ ] )
{
ex2 e = new ex2 ( ); O/p:-
Thread t = new Thread( e ); Thread is running
t.start( ) ;
}
}
Type-2 is preferable because:-
 A class that extends Thread class can’t be extended further
 If a class extends a Thread class, then all its functionalities
are extended, which is an expensive operation
 In the above program, “Thread” class object is created
separately, because, only by extending Thread class, our own
class object will be treated as Thread object. We did not do it
States of a Java Thread:-  So we need to create explicitly an object for Thread class and
 New: A new thread begins its life cycle in the new state. It pass it to our own class object that implements Runnable, so
remains in this state until the program starts the thread. It is also that run() method is extended
referred to as a born thread.  This method is efficient and time saving for Threads.
 Runnable: After a newly born thread is started, the thread
becomes runnable. A thread in this state is considered to be Some popular Thread methods in Java:-
executing its task. class sleep extends Thread
 Waiting: Sometimes, a thread transitions to the waiting state {
while the thread waits for another thread to perform a task. A public void run()
thread transitions back to the runnable state only when another {
thread signals the waiting thread to continue executing. for(int i = 0; i < 2; i++)
 Timed waiting: A runnable thread can enter the timed waiting {
state for a specified interval of time. A thread in this state try
transitions back to the runnable state when that time interval {
expires or when the event it is waiting for occurs. Thread.sleep(1000);
 Terminated: A runnable thread enters the terminated state }
when it completes its task or otherwise terminates. catch(InterruptedException e)
{
Type-1 Example program:- System.out.print("Exception here");
class ex1 extends Thread }
{ System.out.println(i);
public void run() System.out.println(Thread.currentThread().getName());
{ }
System.out.println(“Thread is running”); }
} public static void main(String bala[ ] )
public static void main(String bala[ ] ) {
{ sleep s1 = new sleep();
ex1 e = new ex1( ); System.out.println(s1.getName() );
O/p:-
e.start( ); s1.setName("bala");
Thread is running
} System.out.println(s1.getName() );
} s1.start();
 run() is the method used to tell a thread, what task it }
should perform while running. } O/p:-
 start() is the method used to start execution of a thread Thread-0  name of thread1
Bala  Thread name modified
 Thread scheduler handles all the thread processes.
0  for loop’s i value printed
 This type is the easiest, but not efficient one. Bala  current thread name is printed
1  for loop’s i value printed
Bala  current thread name is printed

PREPARED BY V.BALAMURUGAN, ASST.PROF/CSE


CS6501 – INTERNET PROGRAMMING
IN
Multi threading in Java:- String manipulation:-
 Multithreading is the process of executing more than one class str
thread at a time. {
 Each thread performs a specific task public static void main(String bala[ ] )
 All the threads run simultaneously {
 OS divides the processing time among each thread String s = “sachin”;
 Thereby the available CPU resources are optimally used O/p:- System.out.println(“s.concat(“SIR”));
when a computer has multiple CPUs. SachinSIR System.out.println(s.length());
 Performing multiple activities in a program concurrently 6 System.out.println(s+”SIR”);
is called multithreading. sachinSIR System.out.println(s.charAt(3));
class class1 extends Thread h String s2 = “BALA”;
{ false System.out.println(s.equals(s2));
public void run() true String s3 = “bala”;
{ ach System.out.println(s2.equalsIgnoreCase(s3));
System.out.print("onetask"); chin System.out.println(s.substring(1,4));
} BABA System.out.println(s.substring(2));
} SACHIN String s4 = s2.replace(‘L’,’B’);
class class2 extends Thread Bala System.out.println(s4);
{ 3 System.out.println(s.toUpperCase());
public void run() System.out.println(s2.toLowerCase());
{ System.out.println(s3.lastIndexOf(‘a’));
System.out.print("twotask"); }
} }
} O/p:-
class MT
{ String Buffer:-
public static void main(String aad[])  StringBuffer in java is defined as a class that is
{ alternative to String class
class1 c1=new class1();  It is more flexible than String class
class2 c2=new class2();  We can insert some components to a string
c1.start();  They are Mutable (values can be changed)
c2.start(); O/p:-  StringBuilder class in Java is almost same as this.
Two task class strbuf
}
One task {
}
public static void main(String bala[ ] )
 We cannot guarantee which thread is executed first {
 Thread scheduler decides it based on optimality StringBuffer s = new StringBuffer("Bala");
Advantages of multi-threading:- System.out.println(s);
 More than one task executed simultaneously System.out.println(s.length());
 Time saving and efficient System.out.println(s.capacity());
 Quicker execution s.setCharAt(2,'b');
System.out.println(s);
 Less memory space occupied by each thread
s.append("movie");
 It is useful in developing Gaming applications, graphics
System.out.println(s);
s.insert(4," is a ");
10. Explain string methods and StringBuffer class with ex.
System.out.println(s);
String:-
s.reverse();
 A string in Java is defined as an object that represents a System.out.println(s);
sequence of characters. StringBuffer s2 = new StringBuffer("012345");
 char c [ ] = { ‘B’,’A’,’L’,’A’ }; is equal to String s = “BALA”; s2.delete(0,3);
 They are immutable (values cannot be changed) System.out.println(s2);
 But new instance can be created. }
 String class is used to create object for it. }
Splitting a string:- O/p:-
class ex { Bala
public static void main(String bala[ ] ) { 4
20
String s = “i-am-a-tamilan”; Baba
for(String w: s.split(“ - “, 4)) O/p:-
Babamovie
i
System.out.println(w); am
Baba is a movie
} Eivom a si abaB
a
345
} tamilan
PREPARED BY V.BALAMURUGAN, ASST.PROF/CSE
CS6501 – INTERNET PROGRAMMING

} IN
11. Describe various input and output stream classes with ex import java.io.*;
 A stream is defined as a continuous flow of objects class fos
sequentially. {
 In Java, A stream is defined as a channel on which data flow public static void main(String bala[ ] ) throws Exception
from sender to receiver {
 Categories: Input stream and output stream try
 Input Stream: Input stream is defined as an object that {
reads a stream of data from a file String s = "I am a Tamilan";
 Output Stream: Output stream is defined as an object that byte a[] = new byte[50];
writes stream of data to a file a= s.getBytes();
 Nature of stream: Byte Stream and character stream OutputStream os = new
Byte Stream FileOutputStream("bala.txt");
 To give input and get output in bytes for(byte i=0; i<a.length; i++)
os.write(a[i]);
 Super classes available: InputStream, OutputStream
System.out.print("\n Write finished");
 Methods: read(), write()
os.close();
InputStream classes OutputStream classes }
FileInputStream FileOuputStream catch(FileNotFoundException e1)
PipedInputStream PipedOuputStream {
FilterInputStream FilterOuputStream System.out.print(e1);
ByteArrayInputStream ByteArrayOuputStream }
catch(IOException e2)
Character Stream {
 To give input and get output in character System.out.print(e2);
 Super classes available: Reader, Writer }
 Methods: read(), write()
Classes in Reader Classes in Writer }
FileReader FileWriter }
PipeReader PipeWriter O/p:-
FilterReader FilterWriter d:\> javac fos.java
ByteArrayreader ByteArrayWriter d:\> java fos
write finished
Example for FileInputStream and FileOutputStream classes d:\> type bala.txt
import java.io.*; I am a tamilan
class fis
{ FilterInputStream and FilterOutputStream class
public static void main(String bala[ ] )  FilterStream is a class that wraps the input stream with
{ a byte
int n;  With input stream, we can read only bytes
try  But if we want to read int, double, char, etc, we need a
{ filter class to wrap the byte input stream
InputStream is = new FileInputStream("bala.txt"); i) DataInputStream and DataOutputStream class
System.out.println("Total Bytes = "+(n=is.available()));  DataInputStream reads bytes from stream, converts to
for(int i = 0; i <n; i++) primitive data type
System.out.println((char)is.read());  DataOutputStream converts the primitive data type into
is.close(); bytes and writes these bytes to stream
} import java.io.*;
catch(FileNotFoundException e1) class data
{ {
System.out.print(e1); public static void main(String bala[ ] )
} {
catch(IOException e2) try
{ {
System.out.print(e2); DataOutputStream dos = new
} DataOutputStream(new FileOutputStream("bala.txt"));
dos.writeUTF("Bala");
} dos.writeDouble(12345.67);
} dos.writeInt(1234);
O/p:- dos.writeChar('s');
Total bytes = 20 dos.close();
This is the file content from bala.txt
PREPARED BY V.BALAMURUGAN, ASST.PROF/CSE
CS6501 – INTERNET PROGRAMMING
IN
DataInputStream dis = new DataInputStream(new 12. Explain applet programming in Java with ex.
FileInputStream("bala.txt"));  Applets are small Java programs that can be used in internet
System.out.println(dis.readUTF());  They can be transferred over internet from one PC to another,
System.out.println(dis.readDouble()); displayed on Java enabled web browsers
System.out.println(dis.readInt()); Uses: To perform arithmetic operations, display graphics, play
System.out.println(dis.readChar()); sounds, display videos, etc
} Situations for applet usage:-
catch(FileNotFoundException e1)  To display dynamic web pages
{  To display special effects (Audio/Video)
System.out.print(e1);  To transfer an application to a user who is located remotely
} Differences between applet and application
catch(IOException e2)  Applet does not have main() method
{  On loading applets, some methods of applet are called
System.out.print(e2); automatically by JVM
}
O/p:-  It cannot work independently; either executed by embedding
Bala applet tag in HTML page (or) using appletviewer.exe
} 12345.67  They cannot read from a file, cannot write into a file
} 1234
s  They cannot execute any program in local PC
 They cannot communicate with other server in a network
BufferedInputStream and BufferedOutputStream classes  They cannot use library files of other languages
 It is preferred over other streams for R/W operations  They are more secured
 It is more efficient in handling files Implement applet:-
 All their methods are extended from InputStream and  We should import java.awt.*; and import java.applet.*;
OutputStream class which are their parents.  AWT = Abstract Window toolkit (contains graphics)
 We can specify buffer size (default size = 512 bytes) Class hierarchy:-
import java.io.*;  Object
class buf
{
Offers GUI  Component
public static void main(String bala[ ] ) (button,check box, etc)
{
try Java.awt
Container
{
DataOutputStream dos = new DataOutputStream(new
BufferedOutputStream(new FileOutputStream("bala.txt"))); Panel
dos.writeUTF("Bala");
dos.writeDouble(12345.67); Java.applet
dos.writeInt(1234); Applet
dos.writeChar('s'); Advantages Disadvantages
dos.close();
Simple, good GUI Java-plugin web browsers
DataInputStream dis = new DataInputStream(new needed
BufferedInputStream(new FileInputStream("bala.txt"));
Supports many platforms GUI based programming is
System.out.println(dis.readUTF());
complex, compared to latest
System.out.println(dis.readDouble());
PHP, HTML&CSS
System.out.println(dis.readInt());
Supported by many browsers Takes a lot of downloading
System.out.println(dis.readChar());
time
}
Suitable for Real time apps Slow to execute
catch(FileNotFoundException e1)
{ Client-server communication Outdated as of now
System.out.print(e1); is possible
}
catch(IOException e2) Life cycle of an applet
{ applet loaded
System.out.print(e2);
} new init( )
O/p:-
}
Bala start( ) stop( ) destroy( )
12345.67 idle dead
} 1234 running
s start( )

browser closed
PREPARED BY V.BALAMURUGAN, ASST.PROF/CSE
CS6501 – INTERNET PROGRAMMING
IN
import java.awt.*;
import java.applet.*;
public class smiley extends Applet
{
public void paint(Graphics g)
{
g.drawOval(60,60,200,200);
g.fillOval(90,120,50,20);
g.fillOval(190,120,50,20);
g.drawLine(165,125,165,175);
g.drawArc(110,130,95,95,0,-180);

}
}

O/p:-
D:\>javac smiley.java
D:\>appletviewer smiley.java

PREPARED BY V.BALAMURUGAN, ASST.PROF/CSE

You might also like