v - semester - wordpress.com neutral ... what is an applet? mention its advantages. applets are...

16
CS6501 – INTERNET PROGRAMMING PREPARED BY V.BALAMURUGAN, ASST.PROF/CSE V - SEMESTER PREPARED BY V.BALAMURUGAN, ASST.PROF/CSE STUDY MATERIAL ANNA UNIVERSITY REGULATION 2013 CS6501 INTERNET PROGRAMMING

Upload: phunganh

Post on 13-Apr-2018

213 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: V - SEMESTER - WordPress.com neutral ... What is an applet? Mention its advantages. Applets are small applications ... It produces GUI without introducing the risk of

CS6501 – INTERNET PROGRAMMING

IN

PREPARED BY V.BALAMURUGAN, ASST.PROF/CSE

V - SEMESTER

PREPARED BY V.BALAMURUGAN, ASST.PROF/CSE

STUDY MATERIAL

ANNA UNIVERSITY

REGULATION 2013

CS6501

INTERNET PROGRAMMING

Page 2: V - SEMESTER - WordPress.com neutral ... What is an applet? Mention its advantages. Applets are small applications ... It produces GUI without introducing the risk of

CS6501 – INTERNET PROGRAMMING

IN

PREPARED BY V.BALAMURUGAN, ASST.PROF/CSE

Part - A 1. Mention the features (principles) of Java.

Simple and object oriented

Robust and secure

Architecture neutral and portable

High performance

Interpreted, threaded, dynamic 2. Mention the differences between C++ and Java.

C++ Java

Compiled language Compiled and interpreted

Platform dependent Platform independent

Not a pure OOP language Pure OOP language

No multi-threading, GUI, DB connectivity

Multi-threading, GUI, JDBC available

It cannot be embedded Can be embedded in Scripts

Pointers and templates are available

No pointers and templates

Simple Safe, reliable and powerful

Compilers: DevC++, Turbo C++, GCC, etc

Compiler: JAVAC

3. What are the data types in Java?

Type Capacity Range Default value

byte 1B ( 8 bits) -27 to 27 - 1 0

short 2B (16 bits) -215 to 215 – 1 0

int 4B (32 bits) -231 to 231 – 1 0

long 8B (64 bits) -263 to 263 – 1 0.0L

float 32 bits IEEE 754 floating point 0.0f

double 64 bits IEEE 754 floating point 0.0D

boolean 1 bit True / False False

char 16 bits ‘\u0000’ to ‘\uffff’ NA

4. What is the use of break and continue statements? Break:

Break statement is used to break the execution of the current executing loop or block.

Statements after the break statement will not be executed. Continue:

Continue statement is used to skip the current iteration of the current executing loop or block.

Statements after the continue statement will be executed.

Break for(int i = 0; i < 5; i++ ) { if ( i = = 3) break; System.out.println(i); } O/p:- 0 1 2

Continue for(int i = 0; i < 5; i++ ) { if ( i = = 3) continue; System.out.println(i); } O/p:- 0 1 2 4

5. Define class and object.

A class is defined as collection of variables and methods that are bound together for manipulation.

It is a template/blueprint that tells the behavior and state of an object. Ex: car.

Variables (state) : no_of_wheels, cc, topspeed, mileage

Methods (behavior) : move(), brake(), start(), stop()

An object is defined as the instance of a class; they represent real world entity. Ex: Maruti Swift.

6. What is an array? What are its types?

An array is defined as the data structure to store the collection of elements of similar elements together in a same name stored in continuous memory locations.

Array index always start from zero.

Types: One dimensional array, Multi-dimensional array.

Ex: int a [ ] = new int [5]; 7. What are packages in Java?

A package is a collection of classes and interfaces that provides a high-level layer of access protection and name space management.

To organize files when a project consists of multiple modules.

It eliminates naming conflicts when different packages have classes same names.

Packages access level also allows protecting data from non-authorized classes.

8. What is method overloading and overriding?

Method overloading Method overriding

If a class has multiple methods in same name, but different parameters, then it is called method overloading

If a child class has the same method as defined in its parent class, then it is called method overriding

Compile-time polymorphism Run-time polymorphism

9. What is the use of static keyword? Static variable: A variable whose value remains constant for the entire class. It is used to share common properties of a class.

Static method: A method that access static data members alone. It can be accessed without an object.

Static block: A block that initializes static data members. It is executed before the main method. 10. What is an abstract class?

A super class that does nothing, but lists the features of the other classes are called abstract class.

Abstract keyword is used.

It may contain abstract methods.

If a class has at least one abstract method, then that class must be declared abstract.

11. What are interfaces?

An interface in java is defined as the reference type in java, which is similar to a class, but not actually a class.

It is a collection of abstract methods

If a class implements interface, it inherits all the abstract methods of that interface

Objects cannot be created for interface

UNIT – 1 JAVA PROGRAMMING

Page 3: V - SEMESTER - WordPress.com neutral ... What is an applet? Mention its advantages. Applets are small applications ... It produces GUI without introducing the risk of

CS6501 – INTERNET PROGRAMMING

IN

PREPARED BY V.BALAMURUGAN, ASST.PROF/CSE

12. What is an exception? Bring out its types.

An exception (or exceptional event) is a problem that arises during the execution of a program.

When an Exception occurs the normal flow of the program is disrupted and the program/Application terminates abnormally, which is not recommended, therefore these exceptions are to be handled.

Reasons: User has entered invalid data/ File not found/ Network connection lost, etc.

Checked exception: an exception that occurs at the compile time, cannot simply be ignored Ex: IOException, SQLException

Unchecked exception: an exception that occurs at the time of execution including programming bugs. Ex: NullPointerException, ArrayIndexOutOfBoundsException

Error: It is irrecoverable. It arises beyond the control of the user

13. What is the use of finally keyword in Java? “finally” block provides assurance of execution of some

important code that must be executed after the try block.

If an exception happens at try block, its execution gets break off. “finally” block executes finally at the end.

It is sometimes called as “clean-up” code.

14. What are different types of access modifiers?

“Access specifiers” are keywords that specify the type of access to the member of a class. They allow privileges to parts of a program such as functions and variables.

Public : Anything declared as public can be accessed from anywhere.

Private : Anything declared as private can’t be accessed outside of its class.

Protected : Anything declared as protected can be accessed by classes in the same package and subclasses in the other packages.

Default : Can be accessed only to classes in the same package

15. Define threads.

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

Each thread performs a certain task.

16. What is multithreading? Give its advantages.

A multithreaded program contains two or more parts that can run concurrently.

Each part of such a program is called a thread, and each thread defines a separate path of execution.

Advantages:

Threads share common memory area; thereby it saves memory.

Context-switching between threads takes less time than that of process.

It is used in Games and animation

User can perform multiple operations at the same time.

17. What is an applet? Mention its advantages.

Applets are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part of a web document.

After an applet arrives on the client, it has limited access to resources

It produces GUI without introducing the risk of viruses or breaching data integrity.

They are used in performing arithmetic operations, displaying graphics, playing sounds, creating animation, etc.

Advantages:

To display dynamic web pages (constantly changing).

To add special effects such as sound, animation, etc.

They can be run in many platforms such as Windows, Linux, Mac., and supported by different browsers such as IE, Netscape, Mozilla, etc.

PART – B

1. Explain the structure and execution of a Java program.

Invented by James Gosling and his team on 23-5-1995

It is a language for internet

Theme: Written Once – Run Anywhere (WORA)

It is a platform independent, strongly typed language.

Editions of Java: Java card, J2ME, J2SE, J2EE

Principles of Java: Simple and object oriented, Robust and secure, architecture neutral and portable, high performance, interpreted-threaded and dynamic.

It supports GUI, JBDC, embedding, multithreading

It doesnot support pointers and templates

It is a pure OOP language, interpreted and compiled. Structure of a Java program

Documentation section(optional) Package statements(optional) Import statements(optional) Main class definition Main method Other classes (optional)

Example:- /*This is a hello world program */ class sample { public static void main(String bala[ ] ) { System.out.println(“Hello world”); } } O/p:- >javac sample.java (compilation) >java sample (Execution) Hello world

Sample is the main class name and program name

Main method should always be public, static, void

public – it should be accessible by all other classes

static – allocate memory statically in jvm

void – it does not return any values

String bala[ ] – String class, bala [ ] is the array object

This parameter is passed in main method for getting and manipulating command line arguments (CLA)

Page 4: V - SEMESTER - WordPress.com neutral ... What is an applet? Mention its advantages. Applets are small applications ... It produces GUI without introducing the risk of

CS6501 – INTERNET PROGRAMMING

IN

PREPARED BY V.BALAMURUGAN, ASST.PROF/CSE

System is a class; out is a output stream in console; println() is a method to write onto console screen

There should be at least one class and main method Compilation and execution of a Java program

Source code (sample.java) is received by JAVAC when

javac command is issued by user in command prompt

JAVAC checks the syntax and on successful compilation, creates sample.class file (Byte code)

This sample.class is platform independent file, that can be executed anywhere if Java is supported.

Then the sample.class file is executed if the user enters java command in command prompt

JVM has many internal components, such as class loader, byte code verifier and JIT

Class loader loads the byte code file into JVM interpreter

Byte code verifier performs security check

JIT – Just-In-Time compiler converts sample.class file into native machine code very faster

This native machine code is run in the machine.

2. Explain in detail about operators in java with example.

Arithmetic Operators

All these operators are binary and hence take two operands.

- Addition +, subtraction -, multiplication *, division /, modulus %, Increment ++, decrement --

public class arithmetic { public static void main(String bala[]) {

int a=10, b=20, c=25, d=25; System.out.println(a+b); System.out.println(a-b); System.out.println(a*b); System.out.println(b/a); System.out.println(b%a); System.out.println(a++); System.out.println(++a); System.out.println(a--); System.out.println(--a); System.out.println(a++ + ++a); System.out.println(a++ - ++a); System.out.println(a-- + --a); System.out.println(a-- - --a);

Relational operators - There are 6 relational operators in java which computes the relation between any two operands of same data type. - Its return value is binary: Either true or false. public class relational {

public static void main(String bala[]) {

int a=10, b=20; System.out.println(a==b); System.out.println(a!=b); System.out.println(a > b); System.out.println(a < b); System.out.println(a >= b); System.out.println(a <= b);

} } The Bitwise Operators - Java contains some bitwise operators that perform operation on the operands after converting them into Binary Digits (bits). - Bitwise AND(&), bitwise OR ( | ), bitwise XOR (^), negation (~), left shift (<<), right shift (>>), right zero fill (>>>) class bitwise {

public static void main(String args[]) {

int a=8, b=10; System.out.println(a&b); System.out.println(a|b); System.out.println(a^b); System.out.println(~a); System.out.println(a<<2); System.out.println(a>>2); System.out.println(a>>>2);

} } Logical operators - Logical operators perform the Logic operations on two operands. - There are three basic logical operators such as Logical AND (&&), Logical OR (||), logical NOT (!) public class logical {

public static void main(String bala[]) {

boolean a = true, b=false; System.out.println(a&&b); System.out.println(a||b); System.out.println( !(a||b) );

} }

O/p:- 30 -10 200 2 0 10 12 12 10 22 -2 26 2

O/p:- false true false true false true

O/p:- 8 10 2 -9 32 2 2

O/p:- false true false

Page 5: V - SEMESTER - WordPress.com neutral ... What is an applet? Mention its advantages. Applets are small applications ... It produces GUI without introducing the risk of

CS6501 – INTERNET PROGRAMMING

IN

PREPARED BY V.BALAMURUGAN, ASST.PROF/CSE

} } Assignment Operator - The assignment operator is the single equal sign = - The assignment operator works in Java much as it does in any other computer language. public class assignment {

public static void main(String bala[]) {

int a=8, b=15; System.out.println(a+=b); System.out.println(a-=b); System.out.println(a*=b); System.out.println(a/=b); System.out.println(a%=b); System.out.println(a<=2); System.out.println(a>=2); System.out.println(a&=b); System.out.println(a^=b); System.out.println(a|=b);

} } Conditional Operator - It is also called as Ternary/Conditional/Question-colon/three-way operator - It can replace “if-then-else” - General form: expression1? expression2:expression3 - If expression1 is true, then expression2 is evaluated; otherwise, expression3 is evaluated. public class conditional {

public static void main(String bala[]) {

int a = 20, b; b = (a = = 1) ? 50 : 100; System.out.println(b);

} } 3. What is an array? Explain the types of array with ex. Defn: An array in Java is defined as a collection of elements of similar data type, which are stored in continuous memory locations.

The elements are accessed by their indexes.

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

int [ ] a = {1,2,3}; // declared and initialized Types:-

Single Dimensional array (1-D array) - 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)

1-D array example:- class array { public static void main(String bala [ ] ) { int a [ ] = { 1, 2, 3 }; int b [ ] = { 2, 4, 6 }; int c [ ] = new int [ 3 ] ; for(int i = 0; i < 3 ; i++) { c [ i ] = a [ i ] + b [ i ]; System.out.println(c[i]); } } } 2-D array example:- class array { 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} } ; int c [ ] [ ] = new int [ 3 ] [ 3 ] ; for(int i = 0; i < 3 ; i++) { for(int j = 0; j<3; j++) { c [ i ] [ j ] = a [ i ] [ j ] + b [ i ] [ j ] ; System.out.println(c[ i ] [ j ] ); } System.out.println(“\n”); } } }

4. Explain the concept of inheritance and its types.

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.

“extends” is the keyword used to inherit the properties of parent class.

Ex: Class parent { ------------- ------------- }

Class child extends parent { ------- ------- }

Types: Single, Multilevel, Hierarchical (Multiple & Hybrid - achieved thru interface)

Advantages: Flexibility, Reusability, Extensibility, Data hiding, Overriding

O/p:- 23 8 120 8 8 false true 8 7 15

O/p:- 100

O/p:- 3 6 9

O/p:- 3 3 3 3 3 3 3 3 3

Page 6: V - SEMESTER - WordPress.com neutral ... What is an applet? Mention its advantages. Applets are small applications ... It produces GUI without introducing the risk of

CS6501 – INTERNET PROGRAMMING

IN

PREPARED BY V.BALAMURUGAN, ASST.PROF/CSE

Single inheritance:-

Single inheritance in java is defined as the process of deriving a single derived class from a single base class.

It is the simplest form of inheritance in Java.

class base { int a=10; void value() { System.out.println(a); } } class derived extends base { int b=20; void add() { System.out.println(a+b); } } class single { public static void main(String bala[]) { base b = new base(); derived d = new derived(); d.value(); d.add(); } } Multilevel Inheritance:-

It is the process of deriving a child class from another child class.

Multiple levels of inheritance is followed here.

class base { int a=10; void value1() { System.out.println(a); } } class derived1 extends base { int b=20; void value2() { System.out.println(b); } }

class derived2 extends derived1 { int c=30; void add() { System.out.println(a+b+c); } } Class multilevel { public static void main(String bala[])

{ base b = new base(); derived1 d1 = new derived1(); derived2 d2 = new derived2(); d2.value1(); d2.value2(); d2.add(); } }

Hierarchical inheritance

It is the process of deriving more than one child class from the same parent class.

Two or more child classes having the same parent class.

hierarchical levels of inheritance is followed here. class base { int a=10; void value1() { System.out.println(a); } } class derived1 extends base { int b=20; void add1() { System.out.println(a+b); } } class derived2 extends base { int c=30; void add2() { System.out.println(a+c); } }

O/p:- 10 30

O/p:- 10 20 60

base

derived

base

derived1

derived2

base

derived1 derived2

Page 7: V - SEMESTER - WordPress.com neutral ... What is an applet? Mention its advantages. Applets are small applications ... It produces GUI without introducing the risk of

CS6501 – INTERNET PROGRAMMING

IN

PREPARED BY V.BALAMURUGAN, ASST.PROF/CSE

class hierarchical { public static void main(String bala[])

{ base b = new base(); derived1 d1 = new derived1(); derived2 d1 = new derived2(); d1.value1(); d2.value1(); d1.add1(); d2.add2(); } }

Hybrid inheritance

If more than tyo types of inheritance combined together in deriving child classes, it is called hybrid inheritance.

It may be a combination of single-multilevel, multilevel-hierarchical, etc.

class base { int a=10; void value1() { System.out.println(a); } } class derived1 extends base { int b=20; void value2() { System.out.println(b); } } class derived2 extends derived1 { int c=30; void add1() { System.out.println(a+b+c); } } class derived3 extends derived1 { int d=40; void add2() { System.out.println(a+b+d); } }

class multilevel { public static void main(String bala[])

{ base b = new base(); derived1 d1 = new derived1(); derived2 d2 = new derived2(); derived3 d3 = new derived3(); d2.value1(); d2.value2(); d2.add1(); d3.value1(); d3.value2(); d3.add2(); } } Disadvantages of Inheritance:-

Both classes (super and subclasses) are tightly-coupled.

As they are tightly coupled (bonded each other strongly with extends keyword), they cannot work independently of each other.

Changing the code in super class method also affects the subclass functionality.

If super class method is deleted, the code may not work as subclass may call the super class method with super keyword.

5. Explain abstract classes in Java with ex.

An abstract class is defined as a super class in java that does nothing, but lists out the common features of the other class

“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 be declared as “abstract”

Abstract class can’t be instantiated (object cannot be created)

To use abstract class, we have to inherit it from another class, then define the abstract methods in it.

If abstract class is inherited, all the abstract methods in it, should be defined in derived class.

abstract class abs { abstract void absmethod(); } class sample extends abs { void absmethod() { ------------------- ------------------- } }

O/p:- 10 10 30 40

O/p:- 10 20 60 10 20 70

base

derived1

derived2 Derived3

Page 8: V - SEMESTER - WordPress.com neutral ... What is an applet? Mention its advantages. Applets are small applications ... It produces GUI without introducing the risk of

CS6501 – INTERNET PROGRAMMING

IN

PREPARED BY V.BALAMURUGAN, ASST.PROF/CSE

abstract class A { abstract void absmethod(); } class B extends A { void absmethod() { System.out.println("One "); } } class C extends A { void absmethod() { System.out.println("Two "); } } class abs { public static void main(String arg[]) { B b=new B(); C c=new C(); b.absmethod(); c.absmethod(); } }

6. Explain interfaces in java with ex.

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

If a class implements interface, it inherits the abstract methods of the interface.

Method body will exist only for concrete methods and static methods inside an interface.

Class = variables + methods of an object.

Interface = behavior that a class implements. Similarities between a class and an interface

Both can contain any number of methods

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

Class keyword is used Interface keyword is used

All Methods are defined Not all Methods are defined

Executable source code Outline source code

Object can be created Object can’t be created

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

No Multiple inheritance Multiple inheritance supported

By Default: private specifier By default: abstract & public

Differences between an abstract class and an interface:-

Abstract class Interface

We can inherit only one abstract class

We can inherit more than one interfaces

abstract class members can be public, private or protected

Interface members are only public

Method may or may not have definition

No method definition(default)

Efficient Slow

They can be extended They can be implemented

Variables are non-final Variables are final (default)

inter.java public interface inter { void imethod(); } iface.java class A implements inter { public void imethod() { System.out.print("defined here"); } } class iface { public static void main(String[] bala) { A a=new A(); a.imethod(); } } F:\ex>javac iface.java F:\ex>java iface defined here 7. Explain the concept of inner class and its types with ex.

Inner class in java is defined as a class within another class

They are also called as nested class Class one { Class two { ------- ------- } }

O/p:one Two

Nested class

Non-static

inner class

static inner

class

Normal

inner

class

Method-

local inner

class

Anonymous

inner

class

Page 9: V - SEMESTER - WordPress.com neutral ... What is an applet? Mention its advantages. Applets are small applications ... It produces GUI without introducing the risk of

CS6501 – INTERNET PROGRAMMING

IN

PREPARED BY V.BALAMURUGAN, ASST.PROF/CSE

Static inner class

They are the static members of another class

Static keyword is present before the inner class

Static member of outer class are visible to static inner class Non static members of outer lass are invisible to static inner class

outer.java

class outer { static class inner { public void imethod() { System.out.println("Inner class"); } } public static void main(String[ ] bala) { outer o = new outer(); inner i = new inner(); i.imethod(); } }

Normal inner class

They are non-static member of outer class

They can access only non-static members of outer class innernormal.java class outer { class inner { public void imethod() { System.out.println("inner class"); } } void omethod() { inner i = new inner(); i.imethod(); } } public class innernormal { public static void main(String bala[ ]) { outer o = new outer(); o.omethod(); } }

Method-local inner class:-

A class that is defined within a method of outer class

No access specifier is used in declaration

Its scope is within the block it is declared

They are hides from outside world outer.java public class outer { void omethod() { int a=10; class inner { public void imethod() { System.out.println(a); } } inner i = new inner(); i.imethod(); } public static void main(String bala[ ]) { oter o = new outer(); o.omethod(); } } Anonymous inner class

Local class without a name

One-shot class, created for ad-hoc purpose

It is used under these situations:- - When a class has short body - Only one instance of class needed - Class is used immediately after defining

outer1.java abstract class anony { abstract void absmethod(); } public class outer1 { public static void main(String bala[ ]) { anony a = new anony() { public void absmethod() { System.out.println("anonymous class"); } }; a.absmethod(); } }

O/p:- Inner class

O/p:- Inner class

O/p:- 10

O/p:- Anonymous class

Page 10: V - SEMESTER - WordPress.com neutral ... What is an applet? Mention its advantages. Applets are small applications ... It produces GUI without introducing the risk of

CS6501 – INTERNET PROGRAMMING

IN

PREPARED BY V.BALAMURUGAN, ASST.PROF/CSE

8. Explain the concept of exception handling in java with ex.

Exception is an exceptional event which is a problem that arises during the execution of the program, that is not desired, breaks the normal flow of the execution.

So these exceptions have to be handled efficiently in order to avoid program getting crashed.

Reasons

User entered invalid input.

File not found

Network connection lost

JVM ran out of memory Benefits

Avoid crashing of applications abruptly.

Various types of errors grouped together. Types

i) Checked exception

It occurs during the compile time.

It cannot be ignored.

Programmer should take care/handle exceptions.

Ex: FileNotFoundException

ii) Unchecked exception

It occurs during runtime

It includes programming bugs, logical errors, etc.

It is ignored at the run time.

Ex: int num[] = {1,2,3}; 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.

Keywords used try Error prone block of code to be

monitored for exception

catch Each corresponding ‘try’ block

finally The code that must be executed even though exception may/may not occur.

throw To throw the specific exception from program code

throws It specifies exceptions that can be thrown by particular method.

sample1.java class sample1 { public static void main(String bala[]) { int a; try { a=10/0; } catch(ArithmeticException e) { System.out.println("Div by zero error"); } } }

java.lang Object throwable

Error Exception

IOExceptionClassNotFoundExceptio

n

EOFException

FileNotFoundException

RunTimeException

ArithmeticException

IllegalAssignmentException

IndexOutOfBoundsException

ArrayIndexOutOfBoundsException

NullPointerException

Other exception

O/p:- Div by zero error

Page 11: V - SEMESTER - WordPress.com neutral ... What is an applet? Mention its advantages. Applets are small applications ... It produces GUI without introducing the risk of

CS6501 – INTERNET PROGRAMMING

IN

PREPARED BY V.BALAMURUGAN, ASST.PROF/CSE

Multiple catch blocks for a single try block class sample1 { public static void main(String bala[]) { int a[] = new int[5]; try { System.out.println(a[10]); System.out.println(10/0); } catch(ArrayIndexOutOfBoundsException e) { System.out.println(e); } catch(ArithmeticException e) { System.out.println(e); } } } O/p:- java.lang.ArrayIndexOutOfBoundsException: 10 Finally Block class sample1 { public static void main(String bala[]) { try { System.out.println(10/0); } catch(ArithmeticException e) { System.out.println(e); } finally { System.out.println("This is from Finally block"); } } } O/p:- java.lang.ArithmeticException: / by zero This is from Finally block Method that throws exception class sample1 { static void xyz(int a[]) { try { System.out.println(a[10]); } catch(ArrayIndexOutOfBoundsException e) { System.out.println(e); }

public static void main(String bala[]) { int a[] = {1,2}; xyz(a); } } O/p:- java.lang.ArrayIndexOutOfBoundsException: 10 User-defined Exception import java.lang.Exception; class own extends Exception { own(String msg) { super(msg); } } class sample1 { public static void main(String bala[]) { int a=10; try { if(a<20) throw new own("This is userdefined Exception"); } catch(own e) { System.out.println(e); } } } O/p:- own: This is user-defined Exception 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

Each thread performs a certain task.

Implementation:- 1. By extending “Thread” class 2. By implementing “Runnable” interface

extends implements overrides overrides

Thread

implementation

Class ex1 extends Thread Class ex2 implements Runnable

public void run() { --------------- }

Page 12: V - SEMESTER - WordPress.com neutral ... What is an applet? Mention its advantages. Applets are small applications ... It produces GUI without introducing the risk of

CS6501 – INTERNET PROGRAMMING

IN

PREPARED BY V.BALAMURUGAN, ASST.PROF/CSE

} Life cycle of a thread:-

States of a Java Thread:-

New: A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It is also referred to as a born thread.

Runnable: After a newly born thread is started, the thread becomes runnable. A thread in this state is considered to be executing its task.

Waiting: Sometimes, a thread transitions to the waiting state while the thread waits for another thread to perform a task. A thread transitions back to the runnable state only when another thread signals the waiting thread to continue executing.

Timed waiting: A runnable thread can enter the timed waiting state for a specified interval of time. A thread in this state transitions back to the runnable state when that time interval expires or when the event it is waiting for occurs.

Terminated: A runnable thread enters the terminated state when it completes its task or otherwise terminates.

Type-1 Example program:- class ex1 extends Thread { public void run() { System.out.println(“Thread is running”); } public static void main(String bala[ ] ) { ex1 e = new ex1( ); e.start( ); } }

run() is the method used to tell a thread, what task it should perform while running.

start() is the method used to start execution of a thread

Thread scheduler handles all the thread processes.

This type is the easiest, but not efficient one.

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 ( ); Thread t = new Thread( e ); 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

So we need to create explicitly an object for Thread class and pass it to our own class object that implements Runnable, so that run() method is extended

This method is efficient and time saving for Threads. Some popular Thread methods in Java:- class sleep extends Thread { public void run() { for(int i = 0; i < 2; i++) { try { Thread.sleep(1000); } catch(InterruptedException e) { System.out.print("Exception here"); } System.out.println(i); System.out.println(Thread.currentThread().getName()); } } public static void main(String bala[ ] ) { sleep s1 = new sleep(); System.out.println(s1.getName() ); s1.setName("bala"); System.out.println(s1.getName() ); s1.start(); } }

O/p:- Thread is running

O/p:-

Thread is running

O/p:- Thread-0 name of thread1 Bala Thread name modified 0 for loop’s i value printed Bala current thread name is printed 1 for loop’s i value printed

Bala current thread name is printed

Page 13: V - SEMESTER - WordPress.com neutral ... What is an applet? Mention its advantages. Applets are small applications ... It produces GUI without introducing the risk of

CS6501 – INTERNET PROGRAMMING

IN

PREPARED BY V.BALAMURUGAN, ASST.PROF/CSE

Multi threading in Java:-

Multithreading is the process of executing more than one thread at a time.

Each thread performs a specific task

All the threads run simultaneously

OS divides the processing time among each thread

Thereby the available CPU resources are optimally used when a computer has multiple CPUs.

Performing multiple activities in a program concurrently is called multithreading.

class class1 extends Thread { public void run() { System.out.print("onetask"); } } class class2 extends Thread { public void run() { System.out.print("twotask"); } } class MT { public static void main(String aad[]) { class1 c1=new class1(); class2 c2=new class2(); c1.start(); c2.start(); } }

We cannot guarantee which thread is executed first

Thread scheduler decides it based on optimality Advantages of multi-threading:-

More than one task executed simultaneously

Time saving and efficient

Quicker execution

Less memory space occupied by each thread

It is useful in developing Gaming applications, graphics 10. Explain string methods and StringBuffer class with ex. String:-

A string in Java is defined as an object that represents a sequence of characters.

char c [ ] = { ‘B’,’A’,’L’,’A’ }; is equal to String s = “BALA”;

They are immutable (values cannot be changed)

But new instance can be created.

String class is used to create object for it. Splitting a string:- class ex { public static void main(String bala[ ] ) { String s = “i-am-a-tamilan”; for(String w: s.split(“ - “, 4)) System.out.println(w); } }

String manipulation:- class str { public static void main(String bala[ ] ) { String s = “sachin”; System.out.println(“s.concat(“SIR”)); System.out.println(s.length()); System.out.println(s+”SIR”); System.out.println(s.charAt(3)); String s2 = “BALA”; System.out.println(s.equals(s2)); String s3 = “bala”; System.out.println(s2.equalsIgnoreCase(s3)); System.out.println(s.substring(1,4)); System.out.println(s.substring(2)); String s4 = s2.replace(‘L’,’B’); System.out.println(s4); System.out.println(s.toUpperCase()); System.out.println(s2.toLowerCase()); System.out.println(s3.lastIndexOf(‘a’)); } } O/p:- String Buffer:-

StringBuffer in java is defined as a class that is alternative to String class

It is more flexible than String class

We can insert some components to a string

They are Mutable (values can be changed)

StringBuilder class in Java is almost same as this. class strbuf { public static void main(String bala[ ] ) { StringBuffer s = new StringBuffer("Bala"); System.out.println(s); System.out.println(s.length()); System.out.println(s.capacity()); s.setCharAt(2,'b'); System.out.println(s); s.append("movie"); System.out.println(s); s.insert(4," is a "); System.out.println(s); s.reverse(); System.out.println(s); StringBuffer s2 = new StringBuffer("012345"); s2.delete(0,3); System.out.println(s2); } }

O/p:- Two task One task

O/p:- i am a tamilan

O/p:-

SachinSIR 6 sachinSIR h false true ach chin BABA SACHIN Bala 3

O/p:- Bala 4 20 Baba Babamovie Baba is a movie Eivom a si abaB 345

Page 14: V - SEMESTER - WordPress.com neutral ... What is an applet? Mention its advantages. Applets are small applications ... It produces GUI without introducing the risk of

CS6501 – INTERNET PROGRAMMING

IN

PREPARED BY V.BALAMURUGAN, ASST.PROF/CSE

} 11. Describe various input and output stream classes with ex

A stream is defined as a continuous flow of objects sequentially.

In Java, A stream is defined as a channel on which data flow from sender to receiver

Categories: Input stream and output stream

Input Stream: Input stream is defined as an object that reads a stream of data from a file

Output Stream: Output stream is defined as an object that writes stream of data to a file

Nature of stream: Byte Stream and character stream Byte Stream

To give input and get output in bytes

Super classes available: InputStream, OutputStream

Methods: read(), write()

InputStream classes OutputStream classes

FileInputStream PipedInputStream FilterInputStream ByteArrayInputStream

FileOuputStream PipedOuputStream FilterOuputStream ByteArrayOuputStream

Character Stream

To give input and get output in character

Super classes available: Reader, Writer

Methods: read(), write()

Classes in Reader Classes in Writer

FileReader PipeReader FilterReader ByteArrayreader

FileWriter PipeWriter FilterWriter ByteArrayWriter

Example for FileInputStream and FileOutputStream classes import java.io.*; class fis { public static void main(String bala[ ] ) { int n; try { InputStream is = new FileInputStream("bala.txt"); System.out.println("Total Bytes = "+(n=is.available())); for(int i = 0; i <n; i++) System.out.println((char)is.read()); is.close(); } catch(FileNotFoundException e1) { System.out.print(e1); } catch(IOException e2) { System.out.print(e2); } } } O/p:- Total bytes = 20 This is the file content from bala.txt

import java.io.*; class fos { public static void main(String bala[ ] ) throws Exception { try { String s = "I am a Tamilan"; byte a[] = new byte[50]; a= s.getBytes(); OutputStream os = new FileOutputStream("bala.txt"); for(byte i=0; i<a.length; i++) os.write(a[i]); System.out.print("\n Write finished"); os.close(); } catch(FileNotFoundException e1) { System.out.print(e1); } catch(IOException e2) { System.out.print(e2); } } } O/p:- d:\> javac fos.java d:\> java fos write finished d:\> type bala.txt I am a tamilan FilterInputStream and FilterOutputStream class

FilterStream is a class that wraps the input stream with a byte

With input stream, we can read only bytes

But if we want to read int, double, char, etc, we need a filter class to wrap the byte input stream

i) DataInputStream and DataOutputStream class

DataInputStream reads bytes from stream, converts to primitive data type

DataOutputStream converts the primitive data type into bytes and writes these bytes to stream

import java.io.*; class data { public static void main(String bala[ ] ) { try { DataOutputStream dos = new DataOutputStream(new FileOutputStream("bala.txt")); dos.writeUTF("Bala"); dos.writeDouble(12345.67); dos.writeInt(1234); dos.writeChar('s'); dos.close();

Page 15: V - SEMESTER - WordPress.com neutral ... What is an applet? Mention its advantages. Applets are small applications ... It produces GUI without introducing the risk of

CS6501 – INTERNET PROGRAMMING

IN

PREPARED BY V.BALAMURUGAN, ASST.PROF/CSE

DataInputStream dis = new DataInputStream(new FileInputStream("bala.txt")); System.out.println(dis.readUTF()); System.out.println(dis.readDouble()); System.out.println(dis.readInt()); System.out.println(dis.readChar()); } catch(FileNotFoundException e1) { System.out.print(e1); } catch(IOException e2) { System.out.print(e2); } } } BufferedInputStream and BufferedOutputStream classes

It is preferred over other streams for R/W operations

It is more efficient in handling files

All their methods are extended from InputStream and OutputStream class which are their parents.

We can specify buffer size (default size = 512 bytes) import java.io.*; class buf { public static void main(String bala[ ] ) { try { DataOutputStream dos = new DataOutputStream(new BufferedOutputStream(new FileOutputStream("bala.txt"))); dos.writeUTF("Bala"); dos.writeDouble(12345.67); dos.writeInt(1234); dos.writeChar('s'); dos.close(); DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream("bala.txt")); System.out.println(dis.readUTF()); System.out.println(dis.readDouble()); System.out.println(dis.readInt()); System.out.println(dis.readChar()); } catch(FileNotFoundException e1) { System.out.print(e1); } catch(IOException e2) { System.out.print(e2); } } }

12. Explain applet programming in Java with ex.

Applets are small Java programs that can be used in internet

They can be transferred over internet from one PC to another, displayed on Java enabled web browsers

Uses: To perform arithmetic operations, display graphics, play sounds, display videos, etc Situations for applet usage:-

To display dynamic web pages

To display special effects (Audio/Video)

To transfer an application to a user who is located remotely Differences between applet and application

Applet does not have main() method

On loading applets, some methods of applet are called automatically by JVM

It cannot work independently; either executed by embedding applet tag in HTML page (or) using appletviewer.exe

They cannot read from a file, cannot write into a file

They cannot execute any program in local PC

They cannot communicate with other server in a network

They cannot use library files of other languages

They are more secured Implement applet:-

We should import java.awt.*; and import java.applet.*;

AWT = Abstract Window toolkit (contains graphics) Class hierarchy:-

Offers GUI (button,check box, etc)

Java.awt Java.applet

Advantages Disadvantages

Simple, good GUI Java-plugin web browsers needed

Supports many platforms GUI based programming is complex, compared to latest PHP, HTML&CSS

Supported by many browsers Takes a lot of downloading time

Suitable for Real time apps Slow to execute

Client-server communication is possible

Outdated as of now

Life cycle of an applet applet loaded init( ) start( ) stop( ) destroy( ) start( ) browser closed

O/p:- Bala 12345.67 1234 s

O/p:- Bala 12345.67 1234 s

Object

Component

Container

Panel

Applet

new

running idle dead

Page 16: V - SEMESTER - WordPress.com neutral ... What is an applet? Mention its advantages. Applets are small applications ... It produces GUI without introducing the risk of

CS6501 – INTERNET PROGRAMMING

IN

PREPARED BY V.BALAMURUGAN, ASST.PROF/CSE

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