Java Material

Download as pdf or txt
Download as pdf or txt
You are on page 1of 89

lOMoAR cPSD| 42403338

Java Material
BY NIRANJAN
lOMoAR cPSD| 42403338

UNIT - I
1. FUNDAMENTALS OF OBJECT
Java is an Object-Oriented Language. As a language that has the Object Oriented feature, Java supports the
following fundamental concepts:
• Polymorphism
• Inheritance

• Encapsulation
• Abstraction
• Classes
• Objects
• Instance
• Method
• Message Parsing

OBJECT-ORIENTED PROGRAMMING: INTRODUCTION

OBJECT
CLASS
ABSTRACTION
ENCAPSULATION
INHERITANCE
POLYMORPHISM
OVERLOADING

3. OBJECT ORIENTED PARADIGM


• The first object–oriented language was Simula developed in 1960 by researchers at the Norwegian
Computing Center.
• In 1970, Alan Kay and his research group at Xerox PARK created a personal computer named
Dynabook and the first pure object-oriented programming language (OOPL) - Smalltalk, for
programming the Dynabook.
• In the 1980s, Grady Booch published a paper titled Object Oriented Design that mainly presented a
design for the programming language, Ada. In the ensuing editions, he extended his ideas to a complete
object–oriented design method.
• In the 1990s, Coad incorporated behavioral ideas to object-oriented methods.

The other significant innovations were Object Modeling Techniques (OMT) by James Rumbaing and Object-
Oriented Software Engineering (OOSE) by Ivar Jacobson.
lOMoAR cPSD| 42403338

OBJECT-ORIENTED PROGRAMMING
The important features of object–oriented programming are:
• Bottom–up approach in program design
• Programs organized around objects, grouped in classes
• Focus on data with methods to operate upon object’s data
• Interaction between objects through functions
• Reusability of design through creation of new classes by adding features to existing classes
4. BASIC CONCEPTS OF OBJECT
Java is an Object-Oriented Language. Java supports the following fundamental concepts:
• Polymorphism
• Inheritance

• Encapsulation
• Abstraction
• Classes
• Objects
• Instance
• Method
• Message Parsing.
• Object - Objects have states and behaviors. Example: A dog has states - color, name, breed as well as
behaviors -wagging, barking, eating. An object is an instance of a class.
• Class - A class can be defined as a template/blue print that describes the behaviors/states that object of
its type support

5. BENEFITS OF OOP
The main advantages are
• It is easy to model a real system as real objects are represented by programming objects in OOP.
With the help of inheritance, we can reuse the existing class. This saves time and cost of program.
• In OOP, data can be made private to a class such that only member functions of the class can access
the data.
• With the help of polymorphism, the same function or same operator can be used for different
purposes. This helps to manage software complexity easily.
• Large problems can be reduced to smaller and more manageable problems. It is easy to partition the
work in a project based on objects.
6. APPLICATIONS OF OOP
Main application areas of OOP are
• User interface design such as windows, menu ,…
• Real Time Systems
• Simulation and Modeling
• Object oriented databases
• AI and Expert System
• Neural Networks and parallel programming
• Decision support and office automation system

lOMoAR cPSD| 42403338

7. JAVA EVOLUTION: JAVA HISTORY


• Java began life in 1991 as a programming language for consumer electronics devices at Sun
Microsystems, Inc.
• The engineers decided to create a new language called Oak, built specifically for their task.
• Oak was based on C++ but lacked certain C++ features known to be a common source of pro-
gramming errors. It also had additional features not found in C++.
▪ A preliminary (alpha) version of Java and HotJava was made widely available over the Internet
as part of a free Java Developer’s Kit (JDK
▪ The experiences of users and developers who experimented with Java were helpful to Sun
engineers, who released a second (beta) version of the JDK that incorporated suggested improvements and
corrections.
▪ In 1996, Netscape Communications Corp. announced that support for Java applets would be
included in version 2.0 of its Navigator browser.
▪ Later that year Microsoft followed suit by announcing Java support for its Internet Explorer
version 3.0. The Java revolution was on!

8. JAVA FEATURES

The new J2 versions were renamed as Java SE, Java EE and Java ME respectively. Java is guaranteed
to be Write Once, Run Anywhere.

• Object Oriented
• Platform independent

• Simple

• Secure

• Architectural-neutral

• Portable

• Robust

• Multithreaded

• Interpreted

• High Performance

• Distributed

• Dynamic
lOMoAR cPSD| 42403338

9. HOW JAVA DIFFERS FROM C AND C++


POINTERS
Java does not have an explicit pointer type. Instead of pointers, all references to objects are
accomplished by using implicit references.
References also allow structures such as linked lists to be created easily in Java without explicit pointers;
ARRAYS:
Arrays in Java are first class objects, and references to arrays and their contents are accomplished
through implicit references rather than via point arithmetic.
Arrays of objects are arrays of references that are not automatically initialized to contain actual
objects.
Java does not support multidimensional arrays as in C and C++.
STRINGS:
Strings in C and C++ are arrays of characters, terminated by a null character (‘ \0’).
Strings in Java are objects, and all methods that operate on strings can treat the string as a
complete entity. Strings are not terminated by a null.

MEMORY MANAGEMENT:
All memory management in Java is automatic; memory is allocated automatically when an
object is created, and a run-time garbage collector (the “gc”) frees that memory when the object is no longer in
use. C’s malloc() and free() functions do not exist in Java.
DATA TYPES:
Java primitive data types (char, int, long, and so on) have consistent sizes and behavior across
platforms and operating systems.
The Boolean primitive data type can have two values: true or false. Boolean is not an integer, nor
can it be treated as one, although you can cast 0 or 1 (integers) to boolean types in Java.
Composite data types are accomplished in Java exclusively through the use of class definitions.
The struct, union, and typedef keywords have all been removed in favor of classes.

OPERATORS:
Operator precedence and association behaves as it does in C.
Operator overloading, as in C++, cannot be accomplished in Java. The, operator of C has been deleted.
The + operator can be used to concatenate strings.
CONTROL FLOW
Although the if, while, for, and do-while statements in Java are syntactically the same as they are
in C and C++, there is one significant difference. The test expression for each control flow construct must
return an actual boolean value (true or false). In C and C++, the expression can return an integer.

ARGUMENTS
Java does not support mechanisms for variable-length argument lists to functions as in C and C+
+. All method definitions must have a specific number of arguments. Command-line arguments in Java
behave differently from those in C and C++. The first element in the argument vector (argv[0]) in C and C+
+ is the name of the program itself; in Java, that first argument is the first of the additional arguments. In
other words, in Java, argv[0] is argv[1] in C and C++; there is no way to get hold of the actual name of the
Java program.
lOMoAR cPSD| 42403338

OTHER DIFFERENCES

• Java does not have a preprocessor, and as such, does not have #defines or macros. Constants can be
created by using the final modifier when declaring class and instance variables.
• Java does not have template classes as in C++.

• Java does not include C’s const keyword or the ability to pass by const reference explicitly.

• Java classes are singly inherited, with some multiple-inheritance features provided through
interfaces.

• All functions must be methods. There are no functions that are not tied to classes.

• The goto keyword does not exist in Java (it’s a reserved word, but currently unimplemented). You
can, however, use labeled breaks and continues to break out of and continue executing complex
switch or loop constructs.
10. OVERVIEW OF JAVA LANGUAGE: SIMPLE JAVA PROGRAM
To create a simple java program, you need to create a class that contains main method. Let's understand
the requirement first.
11. REQUIREMENT FOR HELLO JAVA EXAMPLE
For executing any java program, you need to
• install the JDK if you don't have installed it, download the JDK and install it.
• set path of the jdk/bin directory.
• create the java program
• compile and run the java program
12. CREATING HELLO JAVA EXAMPLE
1. class Simple{
2. public static void main(String args[]){
3. System.out.println("Hello Java");
4. }
5. }

save this file as Simple.java

To compile: javac Simple.java


To execute: java Simple

Output: Hello Java

13. JAVA PROGRAM STRUCTURE


Let’s use example of HelloWorld Java program to understand structure and features of class.
This program is written on few lines, and its only task is to print “Hello World from Java” on the screen. Refer
the following picture.
lOMoAR cPSD| 42403338

1. “PACKAGES”:
2. “PUBLIC CLASS HELLOWORLD”:
3. COMMENTS SECTION:
4. “PUBLIC STATIC VOID MAIN (STRING [ ] ARGS)”:
5. SYSTEM.OUT.PRINTLN("HELLO WORLD FROM JAVA")

14. JAVA TOKENS


A Java program is basically a collection of classes. A class is defined by a set of
declaration statements and methods containing executable statements. Most statements contain expressions,
which describe the actions carried out on data. Smallest individual unit in a program are known as tokens. The
compiler recognizes them for building up expressions and statements.
15. JAVA CHARACTER SET
The smallest units of Java language are the characters used to write Java tokens. These
characters are defined by the Unicode character set, and emerging standard that tries to create characters for a
large number of scripts worldwide.

16. KEYWORDS IN JAVA


Java Keywords also called a reserved word. Keywords are identifiers that Java reserves
for its own use. These identifiers have built-in meanings that cannot change. There are 49 reserved keywords
currently defined in the Java language and they are shown in the below table. Eg. Boolean, interface, abstract

17. IDENTIFIERS
Identifiers are programmer-designed tokens. They can have alphabets, digits, and the
underscore and dollar sign characters.
1. They must not begin with a digit.
2. Uppercase and lowercase letters are distinct.
3. They can be of any length.
Example:
average sum dayTemperature firstDayO Batch_strength
TOTAL F_MAX PRINCIPAL_AMOUNT
lOMoAR cPSD| 42403338

18. LITERALS
A literal is the source code representation of a fixed value. Literals in Java is a sequence of
characters (digits, letters, and other characters) that represent constant values to be stored in variables. Integer
literals

• Floating literals
• Character literals
• String literals
19. LITERALS IN JAVA
Literals in Java are a sequence of characters (digits, letters, and other characters) that
represent constant values to be stored in variables. Java language specifies five major types of literals.

1. Integer literals
2. Floating-point literals
3. Character literals
4. String literals
5. Null literals
6. Boolean literals

20. OPERATORS SUPPORTED BY JAVA LANGUAGE


Java operators can be classified into a number of related categories as below:
ARITHMETIC OPERATORS
+ Additive operator (also used for String concatenation) - Subtraction operator
* Multiplication operator / Division operator % Remainder operator

RELATIONAL OPERATORS
== Equal to != Not equal to > Greater than >= Greater than or equal to
< Less than <= Less than or equal to
LOGICAL OPERATORS
&& Logical AND || Logical OR ! Logical NOT

ASSIGNMENT OPERATORS = Assignment

INCREMENT AND DECREMENT OPERATORS


++ Adds 1 to the Operand -- Subtracts 1 from the Operand

CONDITIONAL OPERATORS ?: Ternary (shorthand for if-then-else statement)


BITWISE OPERATORS
~ Unary bitwise complement << Signed left shift >> Signed right shift
>>> Unsigned right shift & Bitwise AND ^ Bitwise exclusive OR | Bitwise inclusive OR
SPECIAL OPERATORS
(Dot Operator) - To access instance variable instanceof - Object reference Operator
lOMoAR cPSD| 42403338

21. SEPARATORS
Separators help define the structure of a program. The separators used in HelloWorld are
parentheses, ( ), braces, { }, the period, ., and the semicolon, ;. The table lists the six Java separators (nine if you
count opening and closing separators as two). Following are the some characters which are generally used as the
separators in Java.

Separator Name Use


.Period ,Comma ;Semicolon ()Parenthesis {}Braces []Brackets
22. JAVA STATEMENT
STATEMENTS
Statements are roughly equivalent to sentences in natural languages. A statement forms a
complete unit of execution. The following types of expressions can be made into a statement by terminating the
expression with a semicolon (;).
• Assignment expressions
• Any use of ++ or --
• Method invocations
• Object creation expressions
Such statements are called expression statements. Here are some examples of expression statements.
// assignment statement
aValue = 8933.234;
// increment statement
aValue++;
// method invocation statement
System.out.println("Hello World!");
// object creation statement
Bicycle myBike = new Bicycle();

23. JAVA VIRTUAL MACHINE


JVM (JAVA VIRTUAL MACHINE)
1. Java Virtual Machine
2. Internal Architecture of JVM
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment in
which java bytecode can be executed.
JVMs are available for many hardware and software platforms (i.e.JVM is plateform dependent).
WHAT IS JVM?
It is:
• A specification where working of Java Virtual Machine is specified. But implementation provider is
independent to choose the algorithm. Its implementation has been provided by Sun and other companies.
• An implementation Its implementation is known as JRE (Java Runtime Environment).
• Runtime Instance Whenever you write java command on the command prompt to run the java class,
and instance of JVM is created.
WHAT IT DOES?
The JVM performs following operation:
• Loads code
• Verifies code
• Executes code
• Provides runtime environment
lOMoAR cPSD| 42403338

JVM provides definitions for the:


• Memory area
• Class file format
• Register set

• Garbage-collected heap
• Fatal error reporting etc.

24. CONSTANTS
A constant in Java is used to map an exact and unchanging value to a variable name.
Constants are used in programming to make code a bit more robust and human readable.

25. VARIABLES
A variable provides us with named storage that our programs can manipulate. Each variable in
Java has a specific type, which determines the size and layout of the variable's memory.
The basic form of a variable declaration is shown here:
data type variable [ = value][, variable [= value] ...] ;
Here data type is one of Java's data types and variable is the name of the variable.
Following are valid examples of variable declaration and initialization in Java:
int a, b, c; // Declares three ints, a, b, and c.
int a = 10, b = 10; // Example of initialization
byte B = 22; // initializes a byte type variable B.
double pi = 3.14159; // declares and assigns a value of PI.
char a = 'a'; // the char variable a iis initialized with value 'a'

26. DATA TYPES IN JAVA


There are two data types available in Java:
• Primitive Data Types
• Reference/Object Data Types
PRIMITIVE DATA TYPES:
There are eight primitive data types supported by Java. Primitive data types are predefined by the
language and named by a keyword. Let us now look into detail about the eight primitive data types.
BYTE:
• Byte data type is an 8-bit signed two's complement integer.
• Example: byte a = 100 , byte b = -50
SHORT:
• Short data type is a 16-bit signed two's complement integer.
• Default value is 0.

• Example: short s = 10000, short r = -20000


INT:
• Int data type is a 32-bit signed two's complement integer.
• The default value is 0.
•Example: int a = 100000, int b = -200000
LONG:
lOMoAR cPSD| 42403338

• Long data type is a 64-bit signed two's complement integer.


• Default value is 0L.
• Example: long a = 100000L, long b = -200000L

FLOAT:
• Float data type is a single-precision 32-bit IEEE 754 floating point.
• Example: float f1 = 234.5f
DOUBLE:
• double data type is a double-precision 64-bit IEEE 754 floating point.
• Default value is 0.0d.

• Example: double d1 = 123.4


BOOLEAN:
• boolean data type represents one bit of information.
• There are only two possible values: true and false.

• Default value is false.


•Example: boolean one = true
CHAR:
• char data type is a single 16-bit Unicode character.
• Char data type is used to store any character.

• Example: char letterA ='A'


REFERENCE DATA TYPES:
• Reference variables are created using defined constructors of the classes.
• Class objects, and various type of array variables come under reference data type.

• Default value of any reference variable is null.


• A reference variable can be used to refer to any object of the declared type or any compatible type.
• Example: Animal animal = new Animal("giraffe");
JAVA LITERALS:
A literal is a source code representation of a fixed value. They are represented directly in the code
without any computation.
Literals can be assigned to any primitive type variable. For example:
byte a = 68;
char a = 'A'
byte, int, long, and short can be expressed in decimal(base 10), hexadecimal(base 16) or octal(base 8)
number systems as well.
Prefix 0 is used to indicate octal and prefix 0x indicates hexadecimal when using these number systems
for literals. For example:
int decimal = 100;
int octal = 0144;
int hexa = 0x64;

Examples of string literals are:


lOMoAR cPSD| 42403338

"Hello World"
"two\nlines"
"\"This is in quotes\""
String and char types of literals can contain any Unicode characters. For example:
char a = '\u0001';
String a = "\u0001";

Java language supports few special escape sequences for String and char literals as well. They are:

NOTATION CHARACTER REPRESENTED


\n Newline \r Carriage return \f Formfeed
\b Backspace \s Space \t tab \" Double quote
\' Single quote \\ backslash
\ddd Octal character \uxxxx Hexadecimal UNICODE character

UNIT-I
1. Java programming is a ----------------
a. Structure oriented programming b. Object oriented programming c. a & b
d. none of the above
2. What is object oriented programming------------------
a. object b. class c.methods d. all the above
3. What is object?
a. Data & Methods b. Data & object C. Data & class d. none of the above
4. Object may be communicate with the--------------
a. Through object b. Through class c.Through methods d.Through data
5. Java program follows approach in program design
a. Top-up approach b. bottom-up approach c. a & b d. none of the above
6. Object are the basic ------------------ in an object-oriented systems
a. runtime entities b. compiler time entities c. debug time entities d. all of the above
7. What is Data Abstraction and Encapsulation--------------------
a. Data & objects b. Data & Methods c. Data Class d. Data & concepts
8. What is Dynamic Binding ------------------ ?
a. Procedure methods b. Procedure class c. Procedure objects d. Procedure calls
9. Java Message communication can be supported -----------------
a. Sending b. Receiving c. a & b d .none of the above
10. What is application of OOP?
a. Real time system b. Object oriented data base c. CAD system d. all of the above
11. Java Developed year & place
a.1995, USA b.1991, USA c.1998, USA d.1999, USA
12. J2SE with SDK 1.3 was released
a.2000 b.2001 c. 2002 d. 2003
13. J2SE with SDK 1.4 was released
a.2000 b.2001 c. 2002 d. 2003
14. J2SE with SDK 5.0 was released
a.2001 b.2002 c. 2003 d. 2004
lOMoAR cPSD| 42403338

15. The java does not support----------------------


a. operator overloading b. method overloading c. a & b d. none of the above
16.The java does not support --------------
a. variables b. operators c. methods d. Global variable
17. Which one of the java token
a. Identifiers b. Operators c. Literals d. all the above
18. What is Literals
a. Characters b. methods c. class d.object
19. Java supported Memory
a. 8 KB b. 8 GB c. 8 MB d. 16 MB
20. Java does not supported
a. template b. objects c. class d. methods
5 MARKS:
1. Introduction to the object oriented programming?
2. Explain the details about the object-oriented paradigm?
3. List out the basic concepts of object-oriented programming?
4. Explain to the objects and classes?
5. Write the benefits of object-oriented programming?
6. Explain to the application of object-oriented programming?
7. Explain to the java history?
8. Explain to the java features?
9. Write the concept of compiled and interpreted?
10. Write the concept of platform-independend and portable?
11. Write the concept of robust and secure?
12. Write the concept of distributed?
13. Write the concept of desktop client?
14. How java differs from c & c++?
15. Write the concept of java tokens?
16. Explain to the details of java statements?
17. Explain to the java virtual machine?
18. Write the concept constants?
19. Explain to the concept of variables?
20. Explain to the concept of the data types?

8 MARKS:
1. Briefly explain to the concept of object-oriented programming?
2. Write the notes on object-oriented paradigm?
3. Explain to the basic concept of object-oriented programming?
4. Write the concept of benefits of object oriented programming?
5. Explain to the concept of application of OOP?
6. Write the notes on java history?
7. Write the concept of java features?
8. How java differs from c & C++?
9. Write the concept of java program structure?
10. Explain to the concept of java tokens?
lOMoAR cPSD| 42403338

11. Write the concept of java statement?


12. Write the concept of java virtual machine?
13. Explain to the details about data types in java?

UNIT – II

1. OPERATORS AND EXPRESSIONS: INTRODUCTION

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the
following groups:

• Arithmetic Operators
• Relational Operators
• Bitwise Operators
• Logical Operators
• Assignment Operators
• Misc Operators

2. TYPES OF OPERATORS
THE ARITHMETIC OPERATORS:
Arithmetic operators are used in mathematical expressions in the same way that they are
used in algebra. The following table lists the arithmetic operators:

Assume integer variable A holds 10 and variable B holds 20, then:

1 + ( Addition )
2 - ( Subtraction )
3 * ( Multiplication )
4 / (Division)
5 % (Modulus)
6 ++ (Increment)
7 -- ( Decrement )

THE RELATIONAL OPERATORS:

There are following relational operators supported by Java language

1 == (equal to)

2 != (not equal to)


3 > (greater than)
4 < (less than)
lOMoAR cPSD| 42403338

5 >= (greater than or equal to)


6 <= (less than or equal to)

THE BITWISE OPERATORS:


Java defines several bitwise operators, which can be applied to the integer types, long, int, short,
char, and byte.
Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60; and b = 13;
now in binary format they will be as follows:

The following are the bitwise operators:

1 & (bitwise and)


2 | (bitwise or)
3 ^ (bitwise XOR)
4 ~ (bitwise compliment)
5 << (left shift)
6 >> (right shift)
7 >>> (zero fill right shift)

THE LOGICAL OPERATORS:

The following table lists the logical operators:

OPERATOR DESCRIPTION
1 && (logical and)
2 || (logical or)
3 ! (logical not)

THE ASSIGNMENT OPERATORS:

There are following assignment operators supported by Java language:

1 =
2 +=
3 -=
4 *=
5 /=
6 %=
7 <<=
8 >>=
9 &=
10 ^=
11 |=

PRECEDENCE OF JAVA OPERATORS:


lOMoAR cPSD| 42403338

Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Certain operators have higher precedence than others; for example, the multiplication
operator has higher precedence than the addition operator:

For example, x = 7 + 3 * 2; here x is assigned 13, not 20 because operator * has higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7.

3. TYPE CONVERSION

TYPE CASTING

Assigning a value of one type to a variable of another type is known as Type Casting.

EXAMPLE :
int x = 10;
byte y = (byte)x;
In Java, type casting is classified into two types,
• Widening Casting(Implicit)

• Narrowing Casting(Explicitly done)

Widening or Automatic type conversion


Automatic Type casting take place when,
• The two types are compatible
• The target type is larger than the source type

NARROWING OR EXPLICIT TYPE CONVERSION

When you are assigning a larger type value to a variable of smaller type, then you need to perform explicit type
casting.

4. DECISION MAKING AND BRANCHING & LOOPING: INTRODUCTION


DECISION MAKING WITH IF STATEMENT:
An if statement tests a particular condition; if the condition evaluates to true , a course of
action is followed i.e a statement or set of statements is executed . Otherwise (if the condition evaluates to false)
,the course-of-action is ignored.
The if statement may be implemented in different forms depending on the complexity of conditions to be tested.
lOMoAR cPSD| 42403338

• Simple if statement
• if... else statement
• Nested if. ..else statement
• else if ladder

SIMPLE IF STATEMENT:
The syntax of the if statement is shown below:
if(expression)
statements;
Where a statement may consist of a single statement , a compound statement, or nothing. The expression must
be enclosed in parentheses. If the expression evaluates to true, the statement is executed, otherwise ignored.
Example:
if(a>10)
if(b<15)
c=(a-b)*(a+b);

If the value of a is greater than 10, then the following statement is executed which in turn is another if
statement. This if statement tests b and if b is less than 15, then c is calculated.
THE IF... ELSE STATEMENT:
This form of if allows either-or condition by providing an else clause. The syntax
of the if-else statement is the following:

if(expression)
statement-1;
else
statement-2;
If the expression evaluates to true i.e., a non-zero value, the statement-1 is executed, otherwise statement-2 is
executed. The statement-1 and statement-2 can be a single statement, or a compound statement, or a null
statement.
Example:
int a,b;
if(a<=b)
a=0;
else
b=0;
NESTED IF ... ELSE STATEMENT:
A Nested if is an if that has another if in it's 'if's' body or in it's else's body. The
nested if can have one of the following three forms:
1. if(expression1)
{
if(expression2)
statement-1;
else
statement-2;
}
lOMoAR cPSD| 42403338

else
body of else;

2. if(expression1)
body-of-if;
else
{
if(expression2)
statement-1;
else
statement-2;
}

3. if(expression1)
{
if(expression2)
statement-1;
else
statement-2;
}
else
{
if(expression3)
statement-3;
else
statement-4;
}
THE ELSE-IF LADDER:
A common programming construct in the java is the if-else-if ladder , which is often also
called the if-else-if staircase because of it's appearence.

It takes the following general form:


if(expression1) statement1;
else
if(expression2) statement2;
else
if(expression3) statement3;
:
else statement n;

SWITCH
Java provides a multiple branch selection statement known as switch. This selection statement
successively tests the value of an expression against a list of integer or character constants. When a match is
found, the statements associated with that constant are executed.
The general form of switch is:
switch(expression)
lOMoAR cPSD| 42403338

{
case value1:
Codesegment 1
case value2:
Codesegment 2
...
case valuen:
Codesegment n
default:
default Codesegment
}
A switch statement is used for multiple way selection that will branch to different code segments based on the
value of a variable or an expression .
CONDITIONAL OPERATORS
Java has an operator that can be used as an alternative to if statement. You are familier with this
operator, the conditional operator ?: This operator can be used to relace if-else statements of the general form:
if (expression 1)
expression 2;
else
expression 3;
The above form of if can be alternativlely written using ?: as follows:
expression 1? expression 2: expression 3;
THE WHILE STATEMENT:
The most simple and general looping structure available in java is the
while statement. The syntax of while loop is:
while(condition)
{
// loop-body
}
Where the loop body may contain a single statement, a compound statement or an empty statement. The loop
iterates while the condition evaluates to true. When the expression becomes false, the program control passes to
the line after the loop body code.

Do
Unlike the while loop, the do-while is an exit-controlled loop i.e it evaluates its text-expression at the bottom
of the loop after executing it's loop-body statements. This means that a do-while loop always executes at least
once. The syntax of the do-while loop is:
do
{
loop-body;
}
while(condition);

FOR STATEMENTS
lOMoAR cPSD| 42403338

The for loop is the easiest to understand of the java loops. All its loop-control elements are gathered in one
place (on the top of the loop), while in the other loop construction of C++ , they( top-contol elements) are
scattered about the program. The Syntax of the for loop statement is:

for( initialization expression(s); test condition; update expression)


{
loop-body;
}
//program showing usage of for loop

5. CLASSES,OBJECTS AND METHODS:


INTRODUCTION:
Object - Objects have states and behaviors. Example: A dog has states - color, name, breed as well as
behaviors -wagging, barking, eating. An object is an instance of a class.
• Class - A class can be defined as a template/blue print that describes the behaviors/states that object of
its type support.
6. METHODS:
A Java method is a collection of statements that are grouped together to perform an operation. When you
call the System.out.println() method, for example, the system actually executes several statements in order to
display a message on the console.
CREATING METHOD:
Considering the following example to explain the syntax of a method:
public static int method Name(int a, int b) {
// body
}

Here,

• public static : modifier.


• int: return type

• method Name: name of the method

• a, b: formal parameters

• int a, int b: list of parameters

Method definition consists of a method header and a method body. The same is shown below:

modifier returnType nameOfMethod (Parameter List) {


// method body
}

The syntax shown above includes:


lOMoAR cPSD| 42403338

• modifier: It defines the access type of the method and it is optional to use.
• returnType: Method may return a value.

• nameOfMethod: This is the method name. The method signature consists of the method name and the
parameter list.

• Parameter List: The list of parameters, it is the type, order, and number of parameters of a method.
These are optional, method may contain zero parameters.

• method body: The method body defines what the method does with statements.
METHOD CALLING:
For using a method, it should be called. There are two ways in which a method is called i.e.
method returns a value or returning nothing (no return value).
The process of method calling is simple. When a program invokes a method, the program control
gets transferred to the called method. This called method then returns control to the caller in two conditions,
when:

• return statement is executed.


• reaches the method ending closing brace.

THE VOID KEYWORD:


The void keyword allows us to create methods which do not return a value. Here, in the
following example we're considering a void method methodRankPoints. This method is a void method which
does not return any value. Call to a void method must be a statement i.e. methodRankPoints(255.7);. It is a Java
statement which ends with a semicolon as shown below.

PASSING PARAMETERS BY VALUE:


While working under calling process, arguments is to be passed. These should be in the same
order as their respective parameters in the method specification. Parameters can be passed by value or by
reference.

Passing Parameters by Value means calling a method with a parameter. Through this the
argument value is passed to the parameter.

6, DEFINING A CLASS

CLASSES IN JAVA:

A class is a blue print from which individual objects are created.


A sample of a class is given below:
public class Dog{
String breed;
int ageC
String color;

void barking(){
lOMoAR cPSD| 42403338

void hungry(){
}

void sleeping(){
}
}

A class can contain any of the following variable types.

• Local variables
• Instance variables
• Class variables

7.METHOD DECLARATION

DEFINING METHODS

Here is an example of a typical method declaration:

public double calculateAnswer(double wingSpan, int numberOfEngines,


double length, double grossTons) {
//do the calculation here
}

The only required elements of a method declaration are the method's return type, name, a pair of parentheses, (),
and a body between braces, {}.

NAMING A METHOD
Although a method name can be any legal identifier, code conventions restrict method
names. By convention, method names should be a verb in lowercase or a multi-word name that begins with a
verb in lowercase, followed by adjectives, nouns, etc. In multi-word names, the first letter of each of the second
and following words should be capitalized. Here are some examples:

run
runFast
getBackground
getFinalData
compareTo
setX
isEmpty

Typically, a method has a unique name within its class. However, a method might have the same name as other
methods due to method overloading.
lOMoAR cPSD| 42403338

8. CREATING OBJECTS
As mentioned previously, a class provides the blueprints for objects. So basically an object is
created from a class. In Java, the new key word is used to create new objects.

There are three steps when creating an object from a class:

• Declaration: A variable declaration with a variable name with an object type.


• Instantiation: The 'new' key word is used to create the object.

• Initialization: The 'new' keyword is followed by a call to a constructor. This call initializes the new
object.

9.CONSTRUCTORS
When discussing about classes, one of the most important sub topic would be constructors. Every class
has a constructor. If we do not explicitly write a constructor for a class the Java compiler builds a default
constructor for that class.

Each time a new object is created, at least one constructor will be invoked. The main rule of constructors is that
they should have the same name as the class. A class can have more than one constructor.

10.METHOD OVERLOADING

When a class has two or more methods by same name but different parameters, it is
known as method overloading. It is different from overriding. In overriding a method has same method name,
type, number of parameters etc.

11.STATIC MEMBERS
CLASS/STATIC VARIABLES:

• Class variables also known as static variables are declared with the static keyword in a class, but outside
a method, constructor or a block.
• There would only be one copy of each class variable per class, regardless of how many objects are
created from it.

• Static variables are rarely used other than being declared as constants. Constants are variables that are
declared as public/private, final and static. Constant variables never change from their initial value.

• Static variables are stored in static memory. It is rare to use static variables other than declared final and
used as either public or private constants.

• Static variables are created when the program starts and destroyed when the program stops.

• Static variables can be accessed by calling with the class name ClassName.VariableName.
lOMoAR cPSD| 42403338

• When declaring class variables as public static final, then variables names (constants) are all in upper
case. If the static variables are not public and final the naming syntax is the same as instance and local
variables.
12.INHERITANCE
Inheritance can be defined as the process where one class acquires the properties (methods and
fields) of another. With the use of inheritance the information is made manageable in a hierarchical order.

The class which inherits the properties of other is known as subclass (derived class, child class)
and the class whose properties are inherited is known as superclass (base class, parent class).

EXTENDS KEYWORD

extends is the keyword used to inherit the properties of a class. Below given is the syntax of
extends keyword.

class Super{
.....
}

class Sub extends Super{.....


}

THE SUPER KEYWORD

The super keyword is similar to this keyword following are the scenarios where the super keyword is used.

• It is used to differentiate the members of superclass from the members of subclass, if they have same
names.
• It is used to invoke the superclass constructor from subclass.

TYPES OF INHERITANCE

There are various types of inheritance as demonstrated below.


lOMoAR cPSD| 42403338

A very important fact to remember is that Java does not support multiple inheritance. This means that a class
cannot extend more than one class. Therefore following is illegal:

public class extends Animal, Mammal{}

However, a class can implement one or more interfaces. This has made Java get rid of the impossibility of
multiple inheritance.

1) SINGLE INHERITANCE
2) MULTIPLE INHERITANCE
3) MULTILEVEL INHERITANCE
4) HIERARCHICAL INHERITANCE
5) HYBRID INHERITANCE

13.METHOD OVERRIDING.

The benefit of overriding is: ability to define a behaviour that's specific to the subclass type
which means a subclass can implement a parent class method based on its requirement.In object-oriented terms,
overriding means to override the functionality of an existing method.
RULES FOR METHOD OVERRIDING:

• The argument list should be exactly the same as that of the overridden method.
• The return type should be the same or a subtype of the return type declared in the original overridden
method in the superclass.
lOMoAR cPSD| 42403338

• The access level cannot be more restrictive than the overridden method's access level. For example: if
the superclass method is declared public then the overridding method in the sub class cannot be either
private or protected.

• Instance methods can be overridden only if they are inherited by the subclass.

• A method declared final cannot be overridden.

• A method declared static cannot be overridden but can be re-declared.

• If a method cannot be inherited, then it cannot be overridden.

UNIT-II
1. Which is not operator ----------------
a. Pointer b. arithmetic c. special d. bitwise
2. Which is one of the mixed mode operator?
a. 5 b. 10.5 c. 15/10.5 d. all of the above
3. Which is one of the relational operators?
a. < b. > c. == d. all of the above
4. Which is not logical operator?
a. && b.!! c.! d.||
5. Which is one of the assignment operators?
a. == b. & c. = d.!
6. Which is one of the increment operators?
a. ++ b. -- c. ** d. //
7. Which is one of the decrement operators?
a. ++ b. -- c. ** d. //
8. Which is one of the conditional operators?
a. ? b. : c. a & b d. none of the above
9. Which is one of the bitwise operators?
a. & b. ! c. ~ d. all of the above
10. Which is one of the special operators?
a. instanceof b. instanceif c. instanceelse d. all of the above
11. What is arithmetic Expressions?
a. variables b. constants c. operator d. all of the above
12. What is casting a value?
a. expression b. ratio c. operator d. all of the above
13. What is Generic Type casting?
a. <T> b. >T< c. >T> d. <T<
14. What is decision making and branching?
a. while b. do c. for d. switch
15. What is decision making and looping?
a. for b. do c. a & b d. if
16. If statement< -------- >
lOMoAR cPSD| 42403338

a. test operator b. test condition c. test expression d. all of the above


17. while statement< -------- >
a. test operator b. test condition c. test expression d. all of the above
18. switch statement< -------- >
a. operator b. condition c. expression d. all of the above
19. switch statement< -------- >
a. operator b. condition c. expression d. all of the above
20. for statement< --------->
a. initialization b. test condition c. increment d. all of the above

5 MARKS
1. Write the short notes on operators in java?
2. Write the concept of expressions in java?
3. Explain to the concept of evaluation of expressions?
4. Explain to the concept of automatic type conversion?
5. Write the concept of casting a value?
6. Write the short notes on generic type casting?
7. Explain to the concept of if statement?
8. Explain to the concept of switch statement?
9. Write the short notes on the while statement?
10. Write the short notes on the do statement?
11. Write the short notes on the for statement?
12. Explain to the concept of class?
13. Explain to the concept of methods?
14. Explain to the concepts constructors?
15. Write the short notes on method overloading?
16. Explain to the concept of static members.
17. Write the short notes on inheritance.
18. Explain to the concept of types of inheritance?
19. Write the short notes on method overriding?
8 MARKS
1. Explain to the types operators in java?
2. Explain to the types expressions in java?
3. Write the concept of type conversion in java?
4. Explain to the concept of decision Making and branching?
5. Explain to the concept of decision Making and looping?
6. Explain to the concept of conditional operators?
7. Explain to the concept of class-method?
8. Write the concepts of declaring to the object?
9. Write the concepts of creating to the object?
10. Explain to the concept of constructors?
11. Explain to the concept of method overloading?
12. Write the concept of static members?
13. Write the notes on inheritance?
14. Write the concept of types of inheritance with sample program?
15. Explain to the method overriding?
lOMoAR cPSD| 42403338

UNIT - III
1. ARRAYS:
INTRODUCTION

Java provides a data structure, the array, which stores a fixed-size sequential collection of
elements of the same type. An array is used to store a collection of data, but it is often more useful to think of an
array as a collection of variables of the same type.

DECLARING ARRAYS:

To use an array in a program, you must declare a variable to reference the array, and you must
specify the type of array the variable can reference. Here is the syntax for declaring an array variable:
lOMoAR cPSD| 42403338

dataType[] arrayRefVar; // preferred way.

or

dataType arrayRefVar[]; // works but not preferred way.


EXAMPLE:

The following code snippets are examples of this syntax:

double[ ] myList;

2. CREATION OF ARRAYS

CREATING ARRAYS:

You can create an array by using the new operator with the following syntax:

arrayRefVar = new dataType[arraySize];

The above statement does two things:

• It creates an array using new dataType[arraySize];


• It assigns the reference of the newly created array to the variable arrayRefVar.

Declaring an array variable, creating an array, and assigning the reference of the array to the
variable can be combined in one statement, as shown below:

dataType[] arrayRefVar = new dataType[arraySize];

Alternatively you can create arrays as follows:

dataType[] arrayRefVar = {value0, value1, ..., valuek};

The array elements are accessed through the index. Array indices are 0-based; that is, they start
from 0 to

ARRAYLENGTH

EXAMPLE:

Following statement declares an array variable, myList, creates an array of 10 elements of double
type and assigns its reference to myList:

double[] myList = new double[10];

Following picture represents array myList. Here, myList holds ten double values and the indices are from 0 to 9.
lOMoAR cPSD| 42403338

2. Strings
Strings, which are widely used in Java programming, are a sequence of characters. In the Java
programming language, strings are objects.

The Java platform provides the String class to create and manipulate strings.

CREATING STRINGS:

The most direct way to create a string is to write:

String greeting = "Hello world!";

Whenever it encounters a string literal in your code, the compiler creates a String object with its
value in this case, "Hello world!'.

public class StringDemo{

public static void main(String args[]){


char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.'};
String helloString = new String(helloArray);
System.out.println( helloString );
}
}

This would produce the following result:

hello.

STRING LENGTH:
Methods used to obtain information about an object are known as accessor methods. One
accessor method that you can use with strings is the length() method, which returns the number of characters
contained in the string object.
lOMoAR cPSD| 42403338

Below given program is an example of length() , method String class.

public class StringDemo {

public static void main(String args[]) {


String palindrome = "Dot saw I was Tod";
int len = palindrome.length();
System.out.println( "String Length is : " + len );
}
}

This would produce the following result:

String Length is : 17
CONCATENATING STRINGS:
The String class includes a method for concatenating two strings:

string1.concat(string2);

This returns a new string that is string1 with string2 added to it at the end. You can also use the
concat() method with string literals, as in:

"My name is ".concat("Zara");

Strings are more commonly concatenated with the + operator, as in:

"Hello," + " world" + "!"

which results in:

"Hello, world!"

Let us look at the following example:

public class StringDemo {

public static void main(String args[]) {


String string1 = "saw I was ";
System.out.println("Dot " + string1 + "Tod");
}
}

This would produce the following result:

Dot saw I was Tod


4. STRING METHODS
lOMoAR cPSD| 42403338

STRING METHODS:

Here is the list of methods supported by String class:

SN METHODS WITH DESCRIPTION


char charAt(int index)
1
Returns the character at the specified index.
int compareTo(Object o)
2
Compares this String to another Object.
int compareTo(String anotherString)
3
Compares two strings lexicographically.
int compareToIgnoreCase(String str)
4
Compares two strings lexicographically, ignoring case differences.
String concat(String str)
5
Concatenates the specified string to the end of this string.
boolean contentEquals(StringBuffer sb)
6 Returns true if and only if this String represents the same sequence of characters as the specified
StringBuffer.
static String copyValueOf(char[] data)
7
Returns a String that represents the character sequence in the array specified.
static String copyValueOf(char[] data, int offset, int count)
8
Returns a String that represents the character sequence in the array specified.
boolean endsWith(String suffix)
9
Tests if this string ends with the specified suffix.
boolean equals(Object anObject)
10
Compares this string to the specified object.
boolean equalsIgnoreCase(String anotherString)
11
Compares this String to another String, ignoring case considerations.
byte getBytes()
12 Encodes this String into a sequence of bytes using the platform's default charset, storing the result into a new
byte array.
byte[] getBytes(String charsetName
13 Encodes this String into a sequence of bytes using the named charset, storing the result into a new byte
array.
14 void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
lOMoAR cPSD| 42403338

Copies characters from this string into the destination character array.
int hashCode()
15
Returns a hash code for this string.
int indexOf(int ch)
16
Returns the index within this string of the first occurrence of the specified character.
int indexOf(int ch, int fromIndex)
17 Returns the index within this string of the first occurrence of the specified character, starting the search at
the specified index.
int indexOf(String str)
18
Returns the index within this string of the first occurrence of the specified substring.
int indexOf(String str, int fromIndex)
19 Returns the index within this string of the first occurrence of the specified substring, starting at the specified
index
String intern()
20
Returns a canonical representation for the string object.
int lastIndexOf(int ch)
21
Returns the index within this string of the last occurrence of the specified character.
int lastIndexOf(int ch, int fromIndex)
22 Returns the index within this string of the last occurrence of the specified character, searching backward
starting at the specified index.
int lastIndexOf(String str)
23
Returns the index within this string of the rightmost occurrence of the specified substring.
int lastIndexOf(String str, int fromIndex)
24 Returns the index within this string of the last occurrence of the specified substring, searching backward
starting at the specified index.
int length()
25
Returns the length of this string.
boolean matches(String regex)
26
Tells whether or not this string matches the given regular expression.
boolean regionMatches(boolean ignoreCase, int toffset, String other, int ooffset, int len)
27
Tests if two string regions are equal.
boolean regionMatches(int toffset, String other, int ooffset, int len)
28
Tests if two string regions are equal
29 String replace(char oldChar, char newChar)
lOMoAR cPSD| 42403338

Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
String replaceAll(String regex, String replacement
30
Replaces each substring of this string that matches the given regular expression with the given replacement.
String replaceFirst(String regex, String replacement)
31 Replaces the first substring of this string that matches the given regular expression with the given
replacement.
String[] split(String regex)
32
Splits this string around matches of the given regular expression.
String[] split(String regex, int limit)
33
Splits this string around matches of the given regular expression.
boolean startsWith(String prefix)
34
Tests if this string starts with the specified prefix.
boolean startsWith(String prefix, int toffset)
35
Tests if this string starts with the specified prefix beginning a specified index.
CharSequence subSequence(int beginIndex, int endIndex)
36
Returns a new character sequence that is a subsequence of this sequence.
String substring(int beginIndex)
37
Returns a new string that is a substring of this string.
String substring(int beginIndex, int endIndex)
38
Returns a new string that is a substring of this string.
char[] toCharArray()
39
Converts this string to a new character array.
String toLowerCase()
40
Converts all of the characters in this String to lower case using the rules of the default locale.
String toLowerCase(Locale locale)
41
Converts all of the characters in this String to lower case using the rules of the given Locale.
String toString()
42
This object (which is already a string!) is itself returned.
String toUpperCase()
43
Converts all of the characters in this String to upper case using the rules of the default locale.
String toUpperCase(Locale locale)
44
Converts all of the characters in this String to upper case using the rules of the given Locale.
String trim()
45
Returns a copy of the string, with leading and trailing whitespace omitted.
lOMoAR cPSD| 42403338

static String valueOf(primitive data type x)


46
Returns the string representation of the passed data type argument.
5. INTERFACES

An interface is a reference type in Java, it is similar to class, it is a collection of abstract methods.


A class implements an interface, thereby inheriting the abstract methods of the interface.

An interface is similar to a class in the following ways:

• An interface can contain any number of methods.


• An interface is written in a file with a .java extension, with the name of the interface matching the name
of the file.

• The byte code of an interface appears in a .class file.

• Interfaces appear in packages, and their corresponding bytecode file must be in a directory structure that
matches the package name.

However, an interface is different from a class in several ways, including:

• You cannot instantiate an interface.


• An interface does not contain any constructors.

• All of the methods in an interface are abstract.

• An interface cannot contain instance fields. The only fields that can appear in an interface must be
declared both static and final.

• An interface is not extended by a class; it is implemented by a class.

• An interface can extend multiple interfaces.

DECLARING INTERFACES:

The interface keyword is used to declare an interface. Here is a simple example to declare an
interface:

EXAMPLE:

Below given is an example of an interface:

/* File name : NameOfInterface.java */


import java.lang.*;
//Any number of import statements

public interface NameOfInterface


lOMoAR cPSD| 42403338

{
//Any number of final, static fields
//Any number of abstract method declarations\
}

Interfaces have the following properties:

• An interface is implicitly abstract. You do not need to use the abstract keyword while declaring an
interface.
• Each method in an interface is also implicitly abstract, so the abstract keyword is not needed.

• Methods in an interface are implicitly public.

EXAMPLE:
/* File name : Animal.java */
interface Animal {

public void eat();


public void travel();
}
6. DEFINING INTERFACES

DEFINING AN INTERFACE

An interface declaration consists of modifiers, the keyword interface, the interface name, a
comma-separated list of parent interfaces (if any), and the interface body. For example:

public interface GroupedInterface extends Interface1, Interface2, Interface3


{
// constant declaration
// base of natural logarithms
double E = 2.718282;
// method signatures
void doSomething (int i, double x);
int doSomethingElse(String s);
}
The public access specifier indicates that the interface can be used by any class in any package.
If you do not specify that the interface is public, then your interface is accessible only to classes defined in the
same package as the interface.
An interface can extend other interfaces, just as a class subclass or extend another class.
However, whereas a class can extend only one other class, an interface can extend any number of interfaces.
The interface declaration includes a comma-separated list of all the interfaces that it extends.

THE INTERFACE BODY


lOMoAR cPSD| 42403338

The interface body can contain abstract methods, default methods, and static methods. An
abstract method within an interface is followed by a semicolon, but no braces (an abstract method does not
contain an implementation). Default methods are defined with the default modifier, and static methods with the
static keyword. All abstract, default, and static methods in an interface are implicitly public, so you can omit the
public modifier.

7. IMPLEMENTING INTERFACES

When a class implements an interface, you can think of the class as signing a contract, agreeing
to perform the specific behaviors of the interface. If a class does not perform all the behaviors of the interface,
the class must declare itself as abstract.

A class uses the implements keyword to implement an interface. The implements keyword appears in the class
declaration following the extends portion of the declaration.

/* File name : MammalInt.java */


public class MammalInt implements Animal{

public void eat(){


System.out.println("Mammal eats");
}

public void travel(){


System.out.println("Mammal travels");
}

public int noOfLegs(){


return 0;
}

public static void main(String args[]){


MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}

This would produce the following result:

ammal eats
ammal travels

When overriding methods defined in interfaces there are several rules to be followed:

• Checked exceptions should not be declared on implementation methods other than the ones declared by
the interface method or subclasses of those declared by the interface method.
• The signature of the interface method and the same return type or subtype should be maintained when
overriding the methods.
lOMoAR cPSD| 42403338

• An implementation class itself can be abstract and if so interface methods need not be implemented.

When implementation interfaces there are several rules:

• A class can implement more than one interface at a time.


• A class can extend only one class, but implement many interfaces.

• An interface can extend another interface, similarly to the way that a class can extend another class.

8. PACKAGES:
INTRODUCTION:
Packages are used in Java in order to prevent naming conflicts, to control access, to make
searching/locating and usage of classes, interfaces, enumerations and annotations easier, etc.

A Package can be defined as a grouping of related types (classes, interfaces, enumerations and
annotations ) providing access protection and name space management.

Some of the existing packages in Java are::

• java.lang - bundles the fundamental classes

• java.io - classes for input , output functions are bundled in this package

Programmers can define their own packages to bundle group of classes/interfaces, etc. It is a
good practice to group related classes implemented by you so that a programmer can easily determine that the
classes, interfaces, enumerations, annotations are related.

Since the package creates a new namespace there won't be any name conflicts with names in
other packages. Using packages, it is easier to provide access control and it is also easier to locate the related
classes.

9. CREATING PACKAGES

While creating a package, you should choose a name for the package and include a package
statement along with that name at the top of every source file that contains the classes, interfaces, enumerations,
and annotation types that you want to include in the package.

The package statement should be the first line in the source file. There can be only one package
statement in each source file, and it applies to all types in the file.

If a package statement is not used then the class, interfaces, enumerations, and annotation types
will be placed in the current default package.
lOMoAR cPSD| 42403338

To compile the Java programs with package statements you have to do use -d option as shown below.

javac -d Destination_folder file_name.java

Then a folder with the given package name is created in the specified destination, and the
compiled class files will be placed in that folder

EXAMPLE:
Let us look at an example that creates a package called animals. It is a good practice to use
names of packages with lower case letters to avoid any conflicts with the names of classes, interfaces.

Below given package example contains interface named animals:

/* File name : Animal.java */


package animals;
interface Animal {
public void eat();
public void travel();
}

Now, let us implement the above interface in the same package animals:

package animals;

/* File name : MammalInt.java */


public class MammalInt implements Animal{

public void eat(){


System.out.println("Mammal eats");
}

public void travel(){


System.out.println("Mammal travels");
}

public int noOfLegs(){


return 0;
}

public static void main(String args[]){


MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}

Now compile the java files as shown below:


lOMoAR cPSD| 42403338

$ javac -d . Animal.java
$ javac -d . MammalInt.java

Now a package/folder with the name animals will be created in the current directory and these class files will
be placed in it as shown below.

You can execute the class file with in the package and get the result as shown below.

$ java animals.MammalInt
ammal eats
ammal travels

10. JAVA API PACKAGE


An applet is a Java program that runs in a Web browser. An applet can be a fully functional Java
application because it has the entire Java API at its disposal.

There are some important differences between an applet and a standalone Java application,
including the following:

• An applet is a Java class that extends the java.applet.Applet class.


• A main() method is not invoked on an applet, and an applet class will not define main().

• Applets are designed to be embedded within an HTML page.

• When a user views an HTML page that contains an applet, the code for the applet is downloaded to the
user's machine.

• A JVM is required to view an applet. The JVM can be either a plug-in of the Web browser or a separate
runtime environment.

• The JVM on the user's machine creates an instance of the applet class and invokes various methods
during the applet's lifetime.
lOMoAR cPSD| 42403338

• Applets have strict security rules that are enforced by the Web browser. The security of an applet is
often referred to as sandbox security, comparing the applet to a child playing in a sandbox with various
rules that must be followed.

• Other classes that the applet needs can be downloaded in a single Java Archive (JAR) file.

CREATING THREADS
Java is amulti threaded programming language which means we can develop multi
threaded program using Java. A multi threaded program contains two or more parts that can run concurrently
and each part can handle different task at the same time making optimal use of the available resources specially
when your computer has multiple CPUs.

By definition multitasking is when multiple processes share common processing resources such
as a CPU. Multi threading extends the idea of multitasking into applications where you can subdivide specific
operations within a single application into individual threads. Each of the threads can run in parallel. The OS
divides processing time not only among different applications, but also among each thread within an
application.

Multi threading enables you to write in a way where multiple activities can proceed concurrently in the same
program.

THREAD METHODS:

Following is the list of important methods available in the Thread class.

SN METHODS WITH DESCRIPTION


public void start()
1
Starts the thread in a separate path of execution, then invokes the run() method on this Thread object.
public void run()

If this Thread object was instantiated using a separate Runnable target, the run() method is invoked on that
2 Runnable

object.

public final void setName(String name)


3
Changes the name of the Thread object. There is also a getName() method for retrieving the name.
public final void setPriority(int priority)
4
Sets the priority of this Thread object. The possible values are between 1 and 10.
public final void setDaemon(boolean on)
5
lOMoAR cPSD| 42403338

A parameter of true denotes this Thread as a daemon thread.


public final void join(long millisec)
6
The current thread invokes this method on a second thread, causing the current thread to block until the
second thread terminates or the specified number of milliseconds passes.
public void interrupt()
7
Interrupts this thread, causing it to continue execution if it was blocked for any reason.
public final boolean isAlive()
8
Returns true if the thread is alive, which is any time after the thread has been started but before it runs to
completion.

The previous methods are invoked on a particular Thread object. The following methods in the Thread class are
static. Invoking one of the static methods performs the operation on the currently running thread.

SN METHODS WITH DESCRIPTION

public static void yield()


1
Causes the currently running thread to yield to any other threads of the same priority that are waiting to be
scheduled.
public static void sleep(long millisec)
2
Causes the currently running thread to block for at least the specified number of milliseconds.
public static boolean holdsLock(Object x)
3
Returns true if the current thread holds the lock on the given Object.
public static Thread currentThread()
4
Returns a reference to the currently running thread, which is the thread that invokes this method.
public static void dumpStack()
5
Prints the stack trace for the currently running thread, which is useful when debugging a multithreaded
application.

EXAMPLE:

The following ThreadClassDemo program demonstrates some of these methods of the Thread class. Consider a
class DisplayMessage which implements Runnable:

// File Name : DisplayMessage.java


// Create a thread to implement Runnable
public class DisplayMessage implements Runnable
{
lOMoAR cPSD| 42403338

private String message;


public DisplayMessage(String message)
{
this.message = message;
}
public void run()
{
while(true)
{
System.out.println(message);
}
}
}

Following is another class which extends Thread class:

// File Name : GuessANumber.java


// Create a thread to extentd Thread
public class GuessANumber extends Thread
{
private int number;
public GuessANumber(int number)
{
this.number = number;
}
public void run()
{
int counter = 0;
int guess = 0;
do
{
guess = (int) (Math.random() * 100 + 1);
System.out.println(this.getName()
+ " guesses " + guess);
counter++;
}while(guess != number);
System.out.println("** Correct! " + this.getName()
+ " in " + counter + " guesses.**");
}
}

Following is the main program which makes use of above defined classes:

// File Name : ThreadClassDemo.java


public class ThreadClassDemo
{
public static void main(String [] args)
lOMoAR cPSD| 42403338

{
Runnable hello = new DisplayMessage("Hello");
Thread thread1 = new Thread(hello);
thread1.setDaemon(true);
thread1.setName("hello");
System.out.println("Starting hello thread...");
thread1.start();

Runnable bye = new DisplayMessage("Goodbye");


Thread thread2 = new Thread(bye);
thread2.setPriority(Thread.MIN_PRIORITY);
thread2.setDaemon(true);
System.out.println("Starting goodbye thread...");
thread2.start();

System.out.println("Starting thread3...");
Thread thread3 = new GuessANumber(27);
thread3.start();
try
{
thread3.join();
}catch(InterruptedException e)
{
System.out.println("Thread interrupted.");
}
System.out.println("Starting thread4...");
Thread thread4 = new GuessANumber(75);

thread4.start();
System.out.println("main() is ending...");
}
}

This would produce the following result. You can try this example again and again and you would get different
result every time.

Starting hello thread...


Starting goodbye thread...
Hello
Hello
Hello
Hello
Hello
Hello
Goodbye
Goodbye
Goodbye
lOMoAR cPSD| 42403338

Goodbye
Goodbye
.......
EXTENDING THREAD CLASS
CREATE THREAD BY EXTENDING THREAD CLASS:
The second way to create a thread is to create a new class that extends Thread class
using the following two simple steps. This approach provides more flexibility in handling multiple threads
created using available methods in Thread class.

STEP 1
You will need to override run( ) method available in Thread class. This method provides entry
point for the thread and you will put you complete business logic inside this method. Following is simple syntax
of run() method:

public void run( )


STEP 2
Once Thread object is created, you can start it by calling start( ) method, which executes a call
to run( ) method. Following is simple syntax of start() method:

void start( );

EXAMPLE:

Here is the preceding program rewritten to extend Thread:

class ThreadDemo extends Thread {


private Thread t;
private String threadName;

ThreadDemo( String name){


threadName = name;
System.out.println("Creating " + threadName );
}
public void run() {
System.out.println("Running " + threadName );
try {
for(int i = 4; i > 0; i--) {
System.out.println("Thread: " + threadName + ", " + i);
// Let the thread sleep for a while.
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Thread " + threadName + " interrupted.");
}
lOMoAR cPSD| 42403338

System.out.println("Thread " + threadName + " exiting.");


}

public void start ()


{
System.out.println("Starting " + threadName );
if (t == null)
{
t = new Thread (this, threadName);
t.start ();
}
}

public class TestThread {


public static void main(String args[]) {

ThreadDemo T1 = new ThreadDemo( "Thread-1");


T1.start();

ThreadDemo T2 = new ThreadDemo( "Thread-2");


T2.start();
}
}

This would produce the following result:

Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 4
Running Thread-2
Thread: Thread-2, 4
Thread: Thread-1, 3
Thread: Thread-2, 3
Thread: Thread-1, 2
Thread: Thread-2, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-1 exiting.
Thread Thread-2 exiting.
13. THREAD LIFE CYCLE
lOMoAR cPSD| 42403338

LIFE CYCLE OF A THREAD:


A thread goes through various stages in its life cycle. For example, a thread is born, started, runs,
and then dies. Following diagram shows complete life cycle of a thread.

Above-mentioned stages are explained here:

• 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 ( Dead ): A runnable thread enters the terminated state when it completes its task or
otherwise terminates.

14. THREAD PRIORITY


THREAD PRIORITIES:
Every Java thread has a priority that helps the operating system determine the order in which
threads are scheduled.Java thread priorities are in the range between MIN_PRIORITY (a constant of 1) and
MAX_PRIORITY (a constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant
of 5).

Threads with higher priority are more important to a program and should be allocated processor time before
lower-priority threads. However, thread priorities cannot guarantee the order in which threads execute and very
much platform dependent.
lOMoAR cPSD| 42403338

CREATE THREAD BY IMPLEMENTING RUNNABLE INTERFACE:


If your class is intended to be executed as a thread then you can achieve this by
implementing Runnable interface. You will need to follow three basic steps:

STEP 1:
As a first step you need to implement a run() method provided by Runnable interface. This
method provides entry point for the thread and you will put you complete business logic inside this method.
Following is simple syntax of run() method:

public void run( )

STEP 2:
At second step you will instantiate a Thread object using the following constructor:

Thread(Runnable threadObj, String threadName);

Where, threadObj is an instance of a class that implements the Runnable interface and threadName is the
name given to the new thread.

STEP 3
Once Thread object is created, you can start it by calling start( ) method, which executes a call
to run( ) method. Following is simple syntax of start() method:

void start( );
EXAMPLE:
Here is an example that creates a new thread and starts it running:

class RunnableDemo implements Runnable {


private Thread t;
private String threadName;

RunnableDemo( String name){


threadName = name;
System.out.println("Creating " + threadName );
}
public void run() {
System.out.println("Running " + threadName );
try {
for(int i = 4; i > 0; i--) {
System.out.println("Thread: " + threadName + ", " + i);
// Let the thread sleep for a while.
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Thread " + threadName + " interrupted.");
}
System.out.println("Thread " + threadName + " exiting.");
lOMoAR cPSD| 42403338

public void start ()


{
System.out.println("Starting " + threadName );
if (t == null)
{
t = new Thread (this, threadName);
t.start ();
}
}

public class TestThread {


public static void main(String args[]) {

RunnableDemo R1 = new RunnableDemo( "Thread-1");


R1.start();

RunnableDemo R2 = new RunnableDemo( "Thread-2");


R2.start();
}
}

This would produce the following result:

Creating Thread-1
Starting Thread-1
Creating Thread-2
Starting Thread-2
Running Thread-1
Thread: Thread-1, 4
Running Thread-2
Thread: Thread-2, 4
Thread: Thread-1, 3
Thread: Thread-2, 3
Thread: Thread-1, 2
Thread: Thread-2, 2
Thread: Thread-1, 1
Thread: Thread-2, 1
Thread Thread-1 exiting.
Thread Thread-2 exiting.
MANAGING ERRORS AND EXCEPTIONS: INTRODUCTION
lOMoAR cPSD| 42403338

An exception (or exeptional 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.

An exception can occur for many different reasons, below given are some scenarios where exception occurs.

• A user has entered invalid data.


• A file that needs to be opened cannot be found.
• A network connection has been lost in the middle of communications or the JVM has run out of
memory.

Some of these exceptions are caused by user error, others by programmer error, and others by physical
resources that have failed in some manner.

THREE TYPES OF ERRORS


There are basically three types of errors that you must contend with when writing computer programs:

• Runtime errors
• Compile Time errors
lOMoAR cPSD| 42403338

Generally speaking, the errors become more difficult to find and fix as you move down the above list

Compile Time errors


In effect, syntax errors represent grammar errors in the use of the programming language. Common examples
are:
• Misspelled variable and function names
• Missing semicolons

• Improperly matches parentheses, square brackets, and curly braces


• Incorrect format in selection and loop statements

RUNTIME ERRORS
Runtime errors occur when a program with no syntax errors asks the computer to do something
that the computer is unable to reliably do. Common examples are:
• Trying to divide by a variable that contains a value of zero
• Trying to open a file that doesn't exist

There is no way for the compiler to know about these kinds of errors when the program is compiled.

16. EXCEPTIONS
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.
An exception can occur for many different reasons, below given are some scenarios where exception occurs.
• A user has entered invalid data.
• A file that needs to be opened cannot be found.

• A network connection has been lost in the middle of communications or the JVM has run out of
memory.

Some of these exceptions are caused by user error, others by programmer error, and others by physical
resources that have failed in some manner.

Based on these we have three categories of Exceptions you need to understand them to know how exception
handling works in Java,

• Checked exceptions: A checked exception is an exception that occurs at the compile time, these are
also called as compile time exceptions. These exceptions cannot simply be ignored at the time of
compilation, the Programmer should take care of (handle) these exceptions.

For example, if you use FileReader class in your program to read data from a file, if the file specified in
its constructor doesn't exist, then an FileNotFoundException occurs, and compiler prompts the
programmer to handle the exception.

import java.io.File;
lOMoAR cPSD| 42403338

import java.io.FileReader;

public class FilenotFound_Demo {

public static void main(String args[]){


File file=new File("E://file.txt");
FileReader fr = new FileReader(file);
}

}
If you try to compile the above program you will get exceptions as shown below.

C:\>javac FilenotFound_Demo.java
FilenotFound_Demo.java:8: error: unreported exception FileNotFoundException; must be caught or declared to
be thrown
FileReader fr = new FileReader(file);
^
1 error

THROWING EXCEPTIONS

To throw an exception, you simply use the throw keyword with an object reference, as in:

throw new TooColdException();


The type of the reference must be Throwable or one of its subclasses.
lOMoAR cPSD| 42403338

CATCHING EXCEPTIONS
To catch an exception in Java, you write a try block with one or more catch clauses. Each catch
clause specifies one exception type that it is prepared to handle. The try block places a fence around a bit of
code that is under the watchful eye of the associated catchers. If the bit of code delimited by the try block
throws an exception, the associated catch clauses will be examined by the Java Virtual Machine. If the virtual
machine finds a catch clause that is prepared to handle the thrown exception, the program continues execution
starting with the first statement of that catch clause.

As an example, consider a program that requires one argument on the command line, a string that
can be parsed into an integer. When you have a String and want an int, you can invoke the parseInt() method of
the Integer class. If the string you pass represents an integer, parseInt() will return the value. If the string doesn't
represent an integer, parseInt() throws NumberFormatException. Here is how you might parse an int from a
command-line argument:

THE THROWS EXCEPTION


As you may have guessed from the examples above, the Java language requires that a method
declare in a throws clause the exceptions that it may throw. A method's throws clause indicates to client
programmers what exceptions they may have to deal with when they invoke the method.

For example, the drinkCoffee() method of class VirtualPerson, shown below, declares three
exceptions in its throws clause: TooColdException, TemperatureException, and UnusualTasteException. These
are the three exceptions that the method throws but doesn't catch. The method may also throw
TooHotException, but this exception doesn't appear in the throws clause because drinkCoffee() catches and
handles it internally. Only exceptions that will cause a method to complete abruptly should appear in its throws
clause.

// In Source Packet in file except/ex7/VirtualPerson.java


class VirtualPerson {

public void drinkCoffee(CoffeeCup cup) throws TooColdException,


TemperatureException, UnusualTasteException {

try {
int i = (int) (Math.random() * 4.0);
switch (i) {
case 0:
throw new TooHotException();

case 1:
throw new TooColdException();

case 2:
throw new UnusualTasteException();

default:
lOMoAR cPSD| 42403338

throw new TemperatureException();


}
}
catch (TooHotException e) {
System.out.println("This coffee is too hot.");
// Customer will wait until it cools to an
// acceptable temperature.
}
}
//...
}
USING EXCEPTIONS FOR DEBUGGING.
Any good program makes use of a language’s exception handling mechanisms. There is
no better way to frustrate an end-user then by having them run into an issue with your software and displaying a
big ugly error message on the screen, followed by a program crash.
Exception handling is all about ensuring that when your program encounters an issue, it
will continue to run and provide informative feedback to the end-user or program administrator. Any Java
programmer becomes familiar with exception handling on day one, as some Java code won’t even compile
unless there is some form of exception handling put into place via the try-catch-finally syntax. Python has
similar constructs to that of Java, and we’ll discuss them in this chapter.

After you have found an exception, or preferably before your software is distributed, you should
go through the code and debug it in order to find and repair the erroneous code. There are many different ways
to debug and repair code; we will go through some debugging methodologies in this chapter. In Python as well
as Java, the assert keyword can help out tremendously in this area. We’ll cover assert in depth here and learn the
different ways that it can be used to help you out and save time debugging those hard-to-find errors.

UNIT-III

1. Array is a collection of similar


A) Data type B) Variable C) Operator D) Experssion
2. Which is one of the symbol of array
A) {} B) () C) [] D) <>
3. Strings represent a sequence of
lOMoAR cPSD| 42403338

A) Variable B) Character C) Data type D) All the above


4. Which is one of the symbol not varaiable
A) C B) Money C) 10 D) &
5. JAVA does not supported
A) Multiple inheritance B) Multilevel inheritance C) Hybrid inheritance D) Single
inheritance
6. An interface is basically a kind of
A) Method B) Class C) Object D) Keyboard
7. What is a keyboard of extending interfaces
A) Extern B) Extend C) Extnd D) Extends
8. The interface item would inherit both the constants and
A) Code, Variable B) Code, Name C) Code, Method D) Code, Object
9. Which one of the keyboard of extending interfaces
A) Final, Static B) Final, Dynamic C) Final, Object D) Final, Method
10. Which class are inheritance used
A) Base class B) Semi class C) Super class D) Semi super class
11. What is a package?
A) Varity of classes B) Varity of interfaces C) a & b D) None of these
12. Expand API
A) Application programming interface B) Advanced programming interface C) Architecture
programming interface D) Artificial programming interface
13. Multithreading concept can be divided to the
A) Class B) Processes C) Method D) Object
14. How to create a thread in initial stage
A) Over() B) Start() C) Run() D) Stop()
15. How to execute the thread exceptions
A) Sleep() B) Start() C) Stop() D) Run()
16. Which is one of the error concept
A) Run-time B) Compile time C) a & b D) None of these
17. Exception can be performed by the
A) Compile time B) Run time C) a & b D) None of these
18. What is the concept of hit exception
A) Find the error B) Inform that an error C) Receive the error D) Corrective actions
19. What is the concept of throw exception
A) Find the error B) Inform that an error C) Receive the error D) Corrective actions
20. What is he concept of catch exception
A) Find the error B) Inform that an error C) Receive the error D) Corrective actions
5 MARKS
1. Explain the concepts of arrays?
2. Creating an array?
3. Write the short notes on strings?
lOMoAR cPSD| 42403338

4. Explain the details of string methods?


5. Explain the concept of multiple inheritances?
6. Defining interfaces
7. Implementing Interfaces
8. Explain the concept of packages?
9. Write the short notes Java API packages?
10. How to creating packages?
11. How to creating threats?
12. Explain to the concept of extending the threat class?
13. Explain to the concept of life cycle of threats?
14. Explain to the concept of threat priority?
15. Write the short notes of managing errors and exceptions?
16. Explain to the concept of types of errors?
17. Explain the details about the exception?
18. Write the syntax and concept of exception handling code?
19. Explain to the concept of using exceptions for debugging?
8 MARKS
1. Briefly explain to the array concept?
2. How to creating an array with sample program?
3. Explain to the concepts of strings and strings methods?
4. Briefly explain to the concepts of interfaces & how to implementing interfaces with sample program?
5. Explain to the concepts packages & how to creating packages with sample program?
6. Explain to the concepts of API packages with sample program?
7. How to creating a threats & Extending threats with sample program?
8. Briefly explain to the concept of threat life cycle & threat priority with sample program?
9. What is a exceptions? Explain to the types of errors with sample program?
10. Write the concept of exceptions for debugging with sample program?

UNIT - IV
1. APPLET PROGRAMMING:

INTRODUCTION
An applet is a Java program that runs in a Web browser. An applet can be a fully
functional Java application because it has the entire Java API at its disposal.
lOMoAR cPSD| 42403338

There are some important differences between an applet and a standalone Java
application, including the following:

• An applet is a Java class that extends the java.applet.Applet class.


• A main() method is not invoked on an applet, and an applet class will not define main().

• Applets are designed to be embedded within an HTML page.

• When a user views an HTML page that contains an applet, the code for the applet is downloaded to the
user's machine.

• A JVM is required to view an applet. The JVM can be either a plug-in of the Web browser or a separate
runtime environment.

• The JVM on the user's machine creates an instance of the applet class and invokes various methods
during the applet's lifetime.

• Applets have strict security rules that are enforced by the Web browser. The security of an applet is
often referred to as sandbox security, comparing the applet to a child playing in a sandbox with various
rules that must be followed.

• Other classes that the applet needs can be downloaded in a single Java Archive (JAR) file.

2. BUILDING APPLET CODE


To building the applet code two classes of java library are essential namely Applet and Graphics.
The Applet class is contained in java.applet package provides life and beehaviour to the applet through its
methods such as int(), start() and paint().
Unlike with applications, where java calls the main() method directly to initiate the execution of the
program, when an applet is loaded java automatically calls a series of Applet class methods for starting running
and stopping the applet code.
The Applet class therefore maintains the life cycle of an applet.
To display the result of the applet code, the paint() method of the Applet class is called up.
The output may be test, graphics, or sound.
The syntax of paint() method which requires a Graphic object as an argument, is defined as follows
public void paint(Graphics g)
This requires that the applet code imports the java.awt package that contain the Graphic class.
All output operations of an applet are performed using the methods defined in the graphics class.

The general format of applet code is as following:


import java.awt.*;
import java.applet.*;
.........................
.........................
public class applet classname extends Applet
{
.................................
lOMoAR cPSD| 42403338

................................ //statements
................................
public void paint(Graphics g)
{
..........................
..........................//Applet operations code
.........................
}
......................
.....................
}
BUILDING APPLET CODE
//HelloApplet.java
import java.applet.Applet;
import java.awt.*;
public class HelloApplet extends Applet
{
public void paint(Graphics g)
{
g.drawString ("Welcome to Applet Tutorial !",100, 100);
}
}
EMBEDDING APPLET IN HTML (WEB PAGE)
<HTML>
<HEAD>
<TITLE>
Hello World Applet
</TITLE>
</HEAD>
<body>
<h1>Hi, This is My First Java Applet on the Web!</h1>
<APPLET CODE="HelloApplet.class" width=500 height=400>
</APPLET>
</body>
</HTML>

3. APPLET LIFE CYCLE


lOMoAR cPSD| 42403338

LIFE CYCLE OF AN APPLET:

Four methods in the Applet class give you the framework on which you build any serious applet:

• init: This method is intended for whatever initialization is needed for your applet. It is called after the
param tags inside the applet tag have been processed.
• start: This method is automatically called after the browser calls the init method. It is also called
whenever the user returns to the page containing the applet after having gone off to other pages.

• stop: This method is automatically called when the user moves off the page on which the applet sits. It
can, therefore, be called repeatedly in the same applet.

• destroy: This method is only called when the browser shuts down normally. Because applets are meant
to live on an HTML page, you should not normally leave resources behind after a user leaves the page
that contains the applet.

• paint: Invoked immediately after the start() method, and also any time the applet needs to repaint itself
in the browser. The paint() method is actually inherited from the java.awt.
lOMoAR cPSD| 42403338

A "HELLO, WORLD" APPLET:


The following is a simple applet named HelloWorldApplet.java:

import java.applet.*;
import java.awt.*;

public class HelloWorldApplet extends Applet


{
public void paint (Graphics g)
{
g.drawString ("Hello World", 25, 50);
}
}

These import statements bring the classes into the scope of our applet class:

• java.applet.Applet.

• java.awt.Graphics.

Without those import statements, the Java compiler would not recognize the classes Applet and Graphics, which
the applet class refers to.

4. CREATING AN EXECUTABLE APPLET


Executable applet is nothing but the .class file of applet, which is obtained by compiling the
source code of the applet. Compiling the applet is exactly the smae as compiling an application using following
command.

javac appletname.java

The compiled output file called appletname.class should be placed in the smae directory as the source file.

5. DESIGNING A WEB PAGE


Java appleta are programs that reside on web page. A web page is basically made up of
text and HTML tags that can be interpreted by a web browser or an applet viewer. Like Java source code, it can
be prepared using any ASCII text editor. A web page is also called HTML page or HTML document. Web
pages are stored using a file extension .html such as my Applet.html. Such files are referred to as HTML files.
HTML files should be stored in the same directory as the compiled code of the applets.

A web page is marked by an opening HTML tag <HTML> and closing HTML tag </HTML>
and is divided into the following three major parts:

1) Comment Section
2) Head Section
3) Body Section
lOMoAR cPSD| 42403338

COMMENT SECTION
This is very first section of any web page containing the comments about the web page
functionality. It is important to include comments that tell us what is going on in the web page. A comment line
begins with <! And ends with a > and the web browsers will ignore the tesxt enclosed between them. The
comments are optional and can be included anywhere in the web page.

HEAD SECTION
This section contains title, heading and sub heading of the web page. The head section is defined
with a starting <Head> tag and closing </Head> tag.

<Head>
<Title> Welcome to Java Applet </Title>
</Head>

BODY SECTION
After the Head Section the body section comes. This is called as body section because the entire information
and behaviour of the web page is contained in it, It defines what the data placed and where on to the screen. It
describes the color, location, sound etc. of the data or information that is going to be placed in the web page.

<Body>
<Center>
<H1>
Welcome to Java >
</H1>
</Center>
<BR>
<APPLET - - ->
</APPLET>
</Body>

6.APPLET TAG
The <Applet...< tag supplies the name of the applet to be loaded and tells the browser how much
space the applet requires. The ellipsis in the tag <Applet...> indicates that it contains certain attributes that must
specified. The <Applet> tag given below specifies the minimum requirements to place the Hellojava applet on a
web page.

<Applet
code = Hellojava.class
width = 400
Height = 200 >
</Applet>
lOMoAR cPSD| 42403338

This HTML code tells the browser to load the compiled java applet Hellojava.class, which is in
the same directory as this HTML file. It also specifies the display area for the applet output as 400 pixels width
and 200 pixels height. We can make this display area appear in the center of screen by using the CENTER tags
as showsn below:

<CENTER>
<Applet>

</Applet>
</CENTER>

The applet tag discussed above specified the three things:

1) Name of the applet


2) Width of the applet (in pixels)
3) Height of the applet (in pixels)
ADDING APPLET TO HTML FILE
To execute an applet in a web browser, you need to write a short HTML text file that contains
the appropriate APPLET tag. Here is the HTML file that executes SimpleApplet:

<Applet code = Hellojava.class width = 400 Height = 200 >


</Applet>

The width and height attributes specify the dimensions of the display area used by the applet. After you create
this file, you can execute the HTML file called RunApp.html (say) on the command line.

c:\>appletviewer RunApp.html

RUNNING THE APPLET


To execute an applet with an applet viewer, you may also execute the HTML file in which it is
enclosed, eg.

c:\>appletviewer RunApp.html

Execute the applet the applet viewer, specifying the name of your applet's source file. The applet
viewer will encounter the applet tage within the comment and execute your applet.
lOMoAR cPSD| 42403338

FIRST JAVA APPLET PROGRAM

The Following will be saved with named FirstJavaApplet.java:

After creating FirstJavaApplet.java file now you need create FirstJavaApplet.html file as shown below:

After this you can comiple your java applet program as shown below:
lOMoAR cPSD| 42403338

"Running Applet"

"Output of FirstJavaApplet.class"
lOMoAR cPSD| 42403338

7. THE GRAPHICS CLASS


We will discuss about the Graphics class and its various methods in this article.

The Graphics class is an abstract class that provides the means to access different graphics
devices. It lets us draw images on the screen, display images, and so forth. It is an abstract class because
working with graphics requires detailed knowledge of the platform on which the program runs. The actual
work is done by concrete classes that are closely tied to a particular platform. Your Java Virtual Machine
vendor provides the necessary concrete classes for your environment. Once you have a Graphics object, you
can call all the methods of the Graphics class without caring about platform specific classes. We rarely need to
create a Graphics object yourself; its constructor is protected and is only called by the subclasses that extend
Graphics. A Graphics object is always available when you override a component's paint() and update()
methods. It is the sole parameter of the Component.paint() and Component.update() methods. We can also get
a graphics context of a Component by calling Component.getGraphics().

The Graphics class defines a number of drawing functions. Each shape can be drawn edge-only
or filled. Objects are drawn and filled in the currently selected graphics color, which is black by default. When
a graphics object is drawn that exceeds the dimensions of the window, output is automatically clipped.
DRAWING STRINGS

These methods let you draw text strings on the screen. The coordinates refer to the left end of the text's baseline.

DRAWING LINES

public abstract void drawLine (int x1, int y1, int x2, int y2):- The drawLine() method draws a
line on the graphics context in the current color that begins at startX,startY and ends at endX,endY. If (x1, y1)
and (x2, y2) are the same point, it will draw a point. There is no method specific to drawing a point.

The following example illustrates the above method:


Code:

import java.awt.*;
import java.applet.*;
/*
<applet code="Rectangles" width=300 height=200>
</applet>
*/

public class Lines extends Applet


{
public void init()
{
setBackground (Color.black);
setForeground(Color.green);
lOMoAR cPSD| 42403338

public void paint(Graphics g)


{
g.drawLine(0, 0, 100, 100);
g.drawLine(0, 100, 100, 0);
g.drawLine(40, 25, 250, 180);
g.drawLine(75, 90, 400, 400);
g.drawLine(20, 150, 400, 40); //line
g.drawLine(5, 290, 80, 19); //line
g.drawLine (5, 75, 5, 75); // point
g.drawLine (50, 5, 50, 5); // point
}
}
Output:-

DRAWING RECTANGLE

PUBLIC VOID DRAWRECT (INT X, INT Y, INT WIDTH, INT HEIGHT):-


The drawRect() method draws a rectangle on the drawing area in the current color from (x, y) to
(x+width, y+height). If width or height is negative, nothing is drawn.

PUBLIC ABSTRACT VOID FILLRECT (INT X, INT Y, INT WIDTH, INT HEIGHT):
The fillRect() method draws a filled rectangle on the drawing area in the current color from (x, y)
to (x+width-1, y+height-1). The filled rectangle is one pixel smaller to the right and bottom than requested. If
width or height is negative, nothing is drawn.

PUBLIC ABSTRACT VOID FILLROUNDRECT


lOMoAR cPSD| 42403338

The fillRoundRect() method is similar to


drawRoundRect() method except that it draws a filled rectangle on the drawing area in the current color from
(x, y) to (x+width-1, y+height-1). If width, height, arcWidth, and arcHeight are all equal, you get a filled circle.

The following example illustrates the above method:


Code:

import java.awt.*;
import java.applet.*;
/*
<applet code="Rectangles" width=300 height=200>
</applet>
*/
public class Rectangles extends Applet
{
public void init()
{
setBackground(Color.black);
setForeground(Color.green);
}

public void paint(Graphics g)


{
g.drawRect(10, 10, 60, 50);
g.fillRect(100, 10, 60, 50);
g.drawRoundRect(190, 10, 60, 50, 15, 15);
g.fillRoundRect(70, 90, 140, 100, 30, 40);
}
}
lOMoAR cPSD| 42403338

Output:-

DRAWING ELLIPSES AND CIRCLES AND OVALS

PUBLIC ABSTRACT VOID DRAWOVAL (INT X, INT Y, INT WIDTH, INT HEIGHT):-

The drawOval() method draws an oval in the current color within an invisible bounding rectangle
from (x, y) to (x+width, y+height). You cannot specify the oval's center point and radii. If width and height are
equal, you get a circle. If width or height is negative, nothing is drawn.

PUBLIC ABSTRACT VOID FILLOVAL (INT X, INT Y, INT WIDTH, INT HEIGHT):

The fillOval() method draws a filled oval in the current color within an invisible bounding
rectangle from (x, y) to (x+width-1, y+height-1). You cannot specify the oval's center point and radii. Notice
that the filled oval is one pixel smaller to the right and bottom than requested. If width or height is negative,
nothing is drawn.

Code:
import java.awt.*;
import java.applet.*;
/*
<applet code="Ovals" width=300 height=200>
</applet>
*/
public class Ovals extends Applet
lOMoAR cPSD| 42403338

{
public void init()
{
setBackground(Color.black);
setForeground(Color.green);
}

public void paint(Graphics g)


{
g.drawOval(10, 10, 50, 50);
g.fillOval(100, 10, 75, 50);
g.drawOval(190, 10, 90, 30);
g.fillOval(70, 90, 140, 100);
}
}
Output:-

DRAWING ARCS

PUBLIC ABSTRACT VOID DRAWARC (INT X, INT Y, INT WIDTH, INT HEIGHT, INT STARTANGLE,
INT ARCANGLE):-
The drawArc() method draws an arc in the current color within an invisible bounding rectangle
from (x,y) to (x+width, y+height). The arc starts at startAngle degrees and goes to startAngle + arcAngle
degrees. An angle of 0 degrees is at the 3 o'clock position; angles increase counter-clockwise. If arcAngle is
negative, drawing is in a clockwise direction. If width and height are equal and arcAngle is 360 degrees,
drawArc() draws a circle. If width or height is negative, nothing is drawn.
lOMoAR cPSD| 42403338

DRAWING POLYGONS

PUBLIC ABSTRACT VOID DRAWPOLYGON (INT XPOINTS[], INT YPOINTS[], INT


NUMPOINTS):-
The drawPolygon() method draws a path of numPoints nodes by taking one element at a time out
of xPoints and yPoints to make each point. The path is drawn in the current color. If either xPoints or yPoints
does not have numPoints elements, drawPolygon() throws a run-time exception
Code:

import java.awt.*;
import java.applet.*;
/*
<applet code="HourGlass" width=230 height=210>
</applet>
*/
public class HourGlass extends Applet
{
public void init()
{
setBackground(Color.black);
setForeground(Color.green);
}

public void paint(Graphics g)


{
int xpoints[] = {30, 200, 30, 200, 30};
int ypoints[] = {30, 30, 200, 200, 30};
int num = 5;
g.drawPolygon(xpoints, ypoints, num);
}
}
lOMoAR cPSD| 42403338

Output:-

USING CONTROL LOOPS IN APPLET.


1. draw 25 random sized ovals on random locations within the border - completed
2. draw a ball and make it move - completed
3. make the ball bounce - not done but I know how to do it

import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;

public class As4B extends Applet implements Runnable


{

public int x, y;
public int width = 854;
public int height = 480;
public int border = 20;
public Image offscreen;
public Graphics d;

public void init()


{
setSize(width,height);
Thread th = new Thread(this);
th.start();
offscreen = createImage(width,height);
lOMoAR cPSD| 42403338

d = offscreen.getGraphics();
}

public void run()


{
x = 100;
y = 100;
while(true)
{
x ++;
y ++;
repaint();
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}

}
public void paint(Graphics gfx)
{
d.setColor(java.awt.Color.black);
d.fillRect(0, 0, width, height);
d.setColor(java.awt.Color.green);
d.fillRect(0 + border, 0 + border, (width - (border * 2)), (height - (border* 2)));
genOval(25, d);

d.setColor(Color.gray);
d.fillOval(x, y, 50, 50);
gfx.drawImage(offscreen, 0, 0, this);

}
public int random(int low, int high)
{
int answer =(int)((Math.random()*(high-low))+ low);
return answer;
}
public void genOval(int amount, Graphics f)
{
int ranWidth, ranHeight, ranX, ranY, red, blue, green;
int i = 0;
while(i < 25)
{
green = random(0,255);
blue = random(0,255);
red = random(0,255);
lOMoAR cPSD| 42403338

f.setColor(new Color(red,green,blue));

ranWidth = random(30,400);
ranHeight = random(30,200);
ranX = random(0 + border, ((width - border)- (ranWidth)));
ranY = random(0 + border , ((height - border)- (ranHeight)));

f.fillOval(ranX, ranY, ranWidth, ranHeight);


i++;
}
}

public void update(Graphics gfx) {


paint(gfx);
}
}

UNIT-IV

1. Applet program are used to the ----------------


a. Internet computing b. Cloud Computing c. Grid Computing d. Green Computing
2. An applet developed by ---------------
a. Server applet b. Client Applet c. Local Applet d. None of the above
lOMoAR cPSD| 42403338

3. How to use applet--------------------


a. <APPLET< b. <APPLET> c. <APPLET? d. (APPLET)
4. The applet class which is contained in the ---------------- package?
a. java. applet b. java,applet c. java/applet d. java\applet
5. The Graphics object & applet as an argument ------------------------ ?
a.point() b.pint() c. pant() d.paint()
6.which is one of the initialization state ----------------- ?
a.int() b. init() c. initial() d.inti()
7. which is one of the dead state -------------- ?
a.start() b. stop() c. destroy() d. dead()
8. which is one of the display state -------------- ?
a.start() b. stop() c. point() d. paint()
9. what is the executable applet --------------- ?
a. .class b. .object c. .method d. .function
10. What is the concept of web page -----------------?
a. xml b.xds c.html d. none of the above
11. how to write the command line in web page ---------------- ?
a. <!> b. <?> c. <*> d. <&>
12. How to get the input from user ---------------- ?
a. (“1”) b. (“0”) c. (“in”) d. (“de”)\
13. The graphics object required -------------------------------?
a. paint() b. pont() c. math() d. point()
14. what purpose used for loops in applet ---------------- ?
a. circles b. triangle c. rectangle d. square
15. which is used for graphics object ------------------ ?
a. <g> b. (g) c . .g d. ,g
16. in html how to display the result ------------------------- ?
a. applet b. applet graphics c. applet viewer d. applet stream
17. which is one of supplies the user-defined parameters ---------------------------- ?
`a. <PARAM…….> b. <&PARAM…….> c. <$PARAM…….> d. <?PARAM ........ >
18. in the HTML any text starting with a----------------- ?
a. <!......... b. <!.............> c. <!............!.> d. b. <!. ...........?>
19. How to displaying the numerical values in graphics class -------------------------------- ?
a. drawstring() b.displaystring() c. getstring() d. outstreamstring

20. what is the method of string class ------------------ ?


a. <value of> b. ?value of? c. (value of) d. value of()
5 MARKS
1. Write the concept of applet programming?
2. Explain the concept of building applet code?
3. Explain the concept of applet life cycle?
lOMoAR cPSD| 42403338

4. Explain the concept of Initialization state?


5. Explain the concept of running state?
6. Explain the concept of idle or stopped state?
7. Explain the concept of dead state?
8. Explain the concept of display state?
9. Creating the executable applet?
10. How to designing a web page?
11. Explain the concept of command section?
12. Explain the concept of head section?
13. Explain the concept of body section?
14. Explain the concept of applet tag?
15. How to running the applet?
16. Explain the concept of the graphics glass
17. Using control loops in applets?

8 MARKS

1. Explain to the concepts of applet programming?


2. How to building applet programming?
3. Write the program on simple applet programming with algorithm?
4. Briefly explain to the concepts of applet life cycle?
5. How to creating an executable applet with sample program?
6. How to designing a web page with sample code?
7. Briefly explain to the concepts of applet tag with sample program?
8. How to running applet program with sample program?
9. Briefly explain to the concepts of the graphics class?
10. How to use in control loops in applet?

UNIT V
1. MANAGING INPUT/OUTPUT FILES IN JAVA:
INTRODUCTION
The java.io package contains nearly every class you might ever need to perform input and output
(I/O) in Java. All these streams represent an input source and an output destination. The stream in the java.io
lOMoAR cPSD| 42403338

package supports many data such as primitives, Object, localized characters, etc.
2. CONCEPTS OF STREAMS

STREAM

A stream can be defined as a sequence of data. there are two kinds of Streams

• InPutStream: The InputStream is used to read data from a source.


• OutPutStream: the OutputStream is used for writing data to a destination.

Java provides strong but flexible support for I/O related to Files and networks but this tutorial covers very basic
functionality related to streams and I/O. We would see most commonly used example one by one:

3. STREAM CLASSES
INTRODUCTION:
A stream can be defined as a sequence of data. The InputStream is used to read data from a
source and the OutputStream is used for writing data to a destination. InputStream and OutputStream are the
basic stream classes in Java.

All the other streams just add capabilities to the basics, like the ability to read a whole chunk of
data at once for performance reasons (BufferedInputStream) or convert from one kind of character set to Java's
native unicode (Reader), or say where the data is coming from (FileInputStream, SocketInputStream and
ByteArrayInputStream, etc.)

WHY WE NEED STREAM CLASSES?


To perform read and write operation on binary files we need a mechanism to read that binary
data on file/to write binary data (i.e. in the form of byte). These classes are capable to read and write one byte
on binary files. That’s why we use Stream Classes.
lOMoAR cPSD| 42403338

Figure 1: Stream Classes

STREAM CLASSES:

Hierarchy of classes for Input and Output streams.

Here Object is the sequence of character i.e. Stream.

1. FileInputStream and FileOutputStream Classes:

FILEINPUTSTREAM CLASS:

A FileInputStream is an InputStream to obtain bytes from a file. It is used for reading inputs of raw bytes such
as image data. It can read byte oriented data.

BYTE STREAM CLASSES


BYTE STREAMS
Java byte streams are used to perform input and output of 8-bit bytes. Though there are many
classes related to byte streams but the most frequently used classes are , FileInputStream and
FileOutputStream. Following is an example which makes use of these two classes to copy an input file into an
output file:
import java.io.*;

public class CopyFile {


public static void main(String args[]) throws IOException
{
FileInputStream in = null;
FileOutputStream out = null;

try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");

int c;
lOMoAR cPSD| 42403338

while ((c = in.read()) != -1) {


out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
Now let's have a file input.txt with the following content:
This is test for copy file.
As a next step, compile above program and execute it, which will result in creating output.txt file with the same
content as we have in input.txt. So let's put above code in CopyFile.java file and do the following:
$javac CopyFile.java
$java CopyFile

INPUT STREAM CLASSES


INTRODUCTION
The Java.io.InputStream class is the superclass of all classes representing an input stream of
bytes. Applications that need to define a subclass of InputStream must always provide a method that returns the
next byte of input.

CLASS DECLARATION

Following is the declaration for Java.io.InputStream class:

public abstract class InputStream


extends Object
implements Closeable
OUTPUT STREAM CLASSES
INTRODUCTION
The Java.io.OutputStream class is the superclass of all classes representing an output stream of
bytes. An output stream accepts output bytes and sends them to some sink.Applications that need to define a
subclass of OutputStream must always provide at least a method that writes one byte of output.

CLASS DECLARATION
Following is the declaration for Java.io.OutputStream class:

public abstract class OutputStream


extends Object
lOMoAR cPSD| 42403338

implements Closeable, Flushable


READER STREAM CLASSES

INTRODUCTION
The Java.io.InputStreamReader class is a bridge from byte streams to character
streams.It reads bytes and decodes them into characters using a specified charset.

CLASS DECLARATION
WRITER STREAM CLASSES
INTRODUCTION

The Java.io.Writer class is a abstract class for writing to character streams.

USING FILE CLASS

• Creating a file.
• Opening a file
• Closing a file
• Deleting a file
• Renaming the file
• Getting the name of a file
• Checking whether the file is writable
• Checking whether the 昀椀le is readable.
lOMoAR cPSD| 42403338

INPUT/OUTPUT EXCEPTION
EXCEPTION HANDLING
Is the mechanism to handle runtime malfunctions. We need to handle such exceptions to prevent
abrupt termination of program. The term exception means exceptional condition, it is a problem that may arise
during the execution of program. A bunch of things can lead to exceptions, including programmer error,
hardware failures, files that need to be opened cannot be found, resource exhaustion etc.

EXCEPTION
A Java Exception is an object that describes the exception that occurs in a program. When an
exceptional events occurs in java, an exception is said to be thrown. The code that's responsible for doing
something about the exception is called an exception handler.

EXCEPTION CLASS HIERARCHY


All exception types are subclasses of class Throwable, which is at the top of exception class
hierarchy.
lOMoAR cPSD| 42403338

• Exception class is for exceptional conditions that program should catch. This class is extended to create
user specific exception classes.
• RuntimeException is a subclass of Exception. Exceptions under this class are automatically defined for
programs.

EXCEPTION ARE CATEGORIZED INTO 3 CATEGORY.


• CHECKED EXCEPTION
The exception that can be predicted by the programmer.Example : File that need to be opened is
not found. These type of exceptions must be checked at compile time.
• UNCHECKED EXCEPTION
Unchecked exceptions are the class that extends RuntimeException. Unchecked exception are
ignored at compile time. Example : ArithmeticException, NullPointerException, Array Index out of
Bound exception. Unchecked exceptions are checked at runtime.
• ERROR
Errors are typically ignored in code because you can rarely do anything about an error.
Example : if stack overflow occurs, an error will arise. This type of error is not possible handle in code.

CREATION OF FILES
You can create an empty file with an initial set of attributes by using the createFile(Path,
FileAttribute<?>) method. For example, if, at the time of creation, you want a file to have a particular set of file
permissions, use the createFile method to do so. If you do not specify any attributes, the file is created with
default attributes. If the file already exists, createFile throws an exception.
lOMoAR cPSD| 42403338

In a single atomic operation, the createFile method checks for the existence of the file and
creates that file with the specified attributes, which makes the process more secure against malicious code.

The following code snippet creates a file with default attributes:

Path file = ...;


try {
// Create the empty file with default permissions, etc.
Files.createFile(file);
} catch (FileAlreadyExistsException x) {
System.err.format("file named %s" +
" already exists%n", file);
} catch (IOException x) {
// Some other sort of failure, such as permissions.
System.err.format("createFile error: %s%n", x);
}

POSIX File Permissions has an example that uses createFile(Path, FileAttribute<?>) to create a file with pre-set
permissions.

You can also create a new file by using the newOutputStream methods, as described in Creating and Writing a
File using Stream I/O. If you open a new output stream and close it immediately, an empty file is created.

CREATING TEMPORARY FILES

You can create a temporary file using one of the following createTempFile methods:

• createTempFile(Path, String, String, FileAttribute<?>)


• createTempFile(String, String, FileAttribute<?>)

The first method allows the code to specify a directory for the temporary file and the second method creates a
new file in the default temporary-file directory. Both methods allow you to specify a suffix for the filename and
the first method allows you to also specify a prefix. The following code snippet gives an example of the second
method:

try {
Path tempFile = Files.createTempFile(null, ".myapp");
System.out.format("The temporary file" +
" has been created: %s%n", tempFile)
;
} catch (IOException x) {
System.err.format("IOException: %s%n", x);
}

The result of running this file would be something like the following:

The temporary file has been created: /tmp/509668702974537184.myapp


lOMoAR cPSD| 42403338

The specific format of the temporary file name is platform specific.

RANDOM ACCESS FILES.


Random access files permit nonsequential, or random, access to a file's contents. To
access a file randomly, you open the file, seek a particular location, and read from or write to that file.

This functionality is possible with the SeekableByteChannel interface. The


SeekableByteChannel interface extends channel I/O with the notion of a current position. Methods enable you
to set or query the position, and you can then read the data from, or write the data to, that location. The API
consists of a few, easy to use, methods:

• position – Returns the channel's current position


• position(long) – Sets the channel's position
• read(ByteBuffer) – Reads bytes into the buffer from the channel
• write(ByteBuffer) – Writes bytes from the buffer to the channel
• truncate(long) – Truncates the file (or other entity) connected to the channel

Reading and Writing Files With Channel I/O shows that the Path.newByteChannel
methods return an instance of a SeekableByteChannel. On the default file system, you can use that channel as
is, or you can cast it to a FileChannel giving you access to more advanced features, such as mapping a region of
the file directly into memory for faster access, locking a region of the file, or reading and writing bytes from an
absolute location without affecting the channel's current position.

The following code snippet opens a file for both reading and writing by using one of the
newByteChannel methods. The SeekableByteChannel that is returned is cast to a FileChannel. Then, 12 bytes
are read from the beginning of the file, and the string "I was here!" is written at that location. The current
position in the file is moved to the end, and the 12 bytes from the beginning are appended. Finally, the string, "I
was here!" is appended, and the channel on the file is closed.

String s = "I was here!\n";


byte data[] = s.getBytes();
ByteBuffer out = ByteBuffer.wrap(data);

ByteBuffer copy = ByteBuffer.allocate(12);

try (FileChannel fc = (FileChannel.open(file, READ, WRITE))) {


// Read the first 12
// bytes of the file.
int nread;
do {
nread = fc.read(copy);
} while (nread != -1 && copy.hasRemaining());

// Write "I was here!" at the beginning of the file.


fc.position(0);
lOMoAR cPSD| 42403338

while (out.hasRemaining())
fc.write(out);
out.rewind();

// Move to the end of the file. Copy the first 12 bytes to


// the end of the file. Then write "I was here!" again.
long length = fc.size();
fc.position(length-1);
copy.flip();
while (copy.hasRemaining())
fc.write(copy);
while (out.hasRemaining())
fc.write(out);
} catch (IOException x) {
System.out.println("I/O Exception: " + x);
}

UNIT-V

1. The data stored in files is often called ----------------


a. Presistent data b. Present data c. Pre data d. Present data
2. What is the powerful tool for file processing------------------
a. Data b. Object c. Stream d. Method
3. The processing all types of data in stream class--------------------
a. java,io b. java.io c. java/io d. java *io
4. which is one of the used for clear the output stream-----------------------
a.flash() b. flats() c. fluesh() d. flush()
5. The random access file enables----------------
a. read bytes b. write bytes c. a & b d. mode bytes
6. The file operation signals that an end of the file------------------------
a. EOF Exception b. EOE Exception c. EOFF Exception d. EOEFF Exception
7. The file operations file could not be found --------------------
a.FileNoteFoundException b.FileNotFoundException
c.FileNotesFoundException d.FileNotFoundException
8. The warnings that I/O operations has been -------------------------
a. interruptedIOSExceptions b. interruptedIOExceptions
c. interruptedIORExceptions d. interruptedIODExceptions
lOMoAR cPSD| 42403338

9. The combine two (or) more input streams into --------------------------


a. Double stream b. Single output stream c. Single input stream d. Single
stream
10. What is the random access file object-------------------
a. “rand.dat” b. “rand,dat” c. “rand&dat” d. “rand%dat”
11. Expand FIS
a. File Input Stream b. File Inter Stream c. File In Stream d. File In Set
12. . Expand DIS
a. File Date Stream b. File Data Stream c. File Digital Stream d. File Data
Set
13. The stream tokenzier a subclass of ---------------
a.Class b. Method c. File d. Object
14.The string tokenzier class of -----------
a.java.token b.java.applet c.java.util d.java.utilizer
15. The writter class is an ------------------
a.base class b.abstractclass c. derived class d. packages
16. The output stream class support------------------
a.base class b.abstractclass c. derived class d. packages
17. DIS Extends
a. DIS b.DCs c. FDS d. FIS
18. What is a source in stream------------------
a. Input b. Output c. Class d. Object
19. What is a source in stream------------------
a. Input b. Output c. Class d. Object
20. how many sub classes handling charactrers in file------------------
a.One b. Two c. Three d. Four

5 MARKS
1. Write the concept of managing Input/Output files in java?
2. Write the details about concept of streams?
3. Explain the concept of stream classes?
4. Write the concept of byte stream classes?
5. Write the concept of input stream classes?
6. Write the concept of output stream classes?
7. Write the concept of character stream classes?
8. Explain the concept of reader stream classes?
9. Explain the concept of writer stream classes?
10. Write the short notes on Input/output exceptions?
11. How to creating a files?
12. Explain the concept of random access files?
lOMoAR cPSD| 42403338

8 MARKS
1. Briefly explain to the concepts of Input/output files in java with sample program?
2. Write the concepts of streams & stream classes & with sample program?
3. Briefly explain to the concepts of Input & Output stream classes with sample program?
4. Explain to the concepts of byte stream classes & character stream classes with sample program?
5. Write the concepts of Reader stream classes & Writer stream classes with sample program?
6. How to using file classes with sample program?
7. Briefly explain to the concepts Input & Output exception with syntax and sample program?
8. How to creating a files? Write the sample program with syntax?
9. Write to the notes on Random Access File?
10. Write the program on file operations with algorithm?

ANSWERS
UNIT-I

1. b. Object oriented programming


2. d. all the above
3. a. Data & Methods
4. c. Through methods
5. b. bottom-up approach
6. a. runtime entities
7. b. Data & Methods
8. d. Procedure calls.
9. c. a & b
lOMoAR cPSD| 42403338

10. d. all of the above


11. b. 1991, USA
12. a.2000
13. c. 2002
14. d. 2004
15. c. a & b
16. d. Global variable
17. d. all the above
18. a. Characters
19. c. 8 MB
20. a.templates

UNIT-II

1. a. Pointer
2. c. 15/10.5
3. d. all of the above
4. b.!!
5. c. =
6. a. ++
7. b. --
8. c. a & b
9. d. all of the above
10. a. instanceof
11. d. all of the above
12. b. ratio
13. a. <T>
14. d. switch
15. c. a & b
16. c. test expression
17. b. test condition
18. c. expression
19. b. condition
20. d. all of the above

UNIT-III
1. A) Data type
2. B) []
3. C) Character
4. D) &
5. A) Multiple inheritance
lOMoAR cPSD| 42403338

6. B) Class
7. D) Extends
8. B) Code, name
9. A) Final, static
10. C) Super class
11. C) a & b
12. A) Application programming interface
13. B) Processes
14. C) Run
15. A) Sleep
16. C) a & b
17. B) Run time
18. A) Find the problem
19. B) Inform that an error
20. C) Receive the error

UNIT-IV

1. a. Internet computing
2. c. Local Applet
3. b. <APPLET>
4. a. java. applet
5. d.paint()
6. b. init()
7. c. destroy()
8. d. paint()
9. a. .class
10. c. html
11. a. <!>
12. b. (“0”)
13. d. point()
14. a. circles
15. c . .g
16. c. applet viewer
17. <PARAM…….>
18. b. <!. ........... >
19. a. drawstring()
20. d. value of()

UNIT-V

1. a. Presistent data
lOMoAR cPSD| 42403338

2. c. Stream
3. b. java.io
4. d. flush()
5. c. a & b
6. a. EOF Exception
7. d. FileNotFoundException
8. b. interruptedIOExceptions
9. c. single input stream
10. a. “rand.dat”
11. a. File Input Stream
12. b. File Data Stream
13. d. Object
14. c .java.util
15. b. abstract class
16. a. base class
17. d. FIS
18. a. Input
19. b. Output
20. b. Two

REFERENCES:

WEBSITE:
www.javatpoint.com
www.w3schools.in
https://howtoprogramwithjava.com
java.about.com
www.javapractices.com
www.tutorialspoint.com
BOOKS:
1. E.Balagurusamy, “Programming with JAVA –A Primer”- Tata McGraw-Hill Publishing
Company Limited ,Seventh Reprint ,2008.
2. Patrick Naughton, “The JAVA Handbook”- Tata McGraw-Hill Publishing Company Limited, 2006.

You might also like