Java Material
Java Material
Java Material
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
CLASS
ABSTRACTION
ENCAPSULATION
INHERITANCE
POLYMORPHISM
OVERLOADING
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
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
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. }
1. “PACKAGES”:
2. “PUBLIC CLASS HELLOWORLD”:
3. COMMENTS SECTION:
4. “PUBLIC STATIC VOID MAIN (STRING [ ] ARGS)”:
5. SYSTEM.OUT.PRINTLN("HELLO WORLD FROM JAVA")
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
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
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.
• 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'
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.
"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:
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
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
UNIT – II
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:
1 + ( Addition )
2 - ( Subtraction )
3 * ( Multiplication )
4 / (Division)
5 % (Modulus)
6 ++ (Increment)
7 -- ( Decrement )
1 == (equal to)
OPERATOR DESCRIPTION
1 && (logical and)
2 || (logical or)
3 ! (logical not)
1 =
2 +=
3 -=
4 *=
5 /=
6 %=
7 <<=
8 >>=
9 &=
10 ^=
11 |=
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)
When you are assigning a larger type value to a variable of smaller type, then you need to perform explicit type
casting.
• 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.
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:
Here,
• a, b: formal parameters
Method definition consists of a method header and a method body. The same is shown below:
• 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:
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:
void barking(){
lOMoAR cPSD| 42403338
void hungry(){
}
void sleeping(){
}
}
• Local variables
• Instance variables
• Class variables
7.METHOD DECLARATION
DEFINING METHODS
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.
• 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{
.....
}
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
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:
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.
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
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
or
double[ ] myList;
2. CREATION OF ARRAYS
CREATING ARRAYS:
You can create an array by using the new operator with the following syntax:
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:
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:
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:
Whenever it encounters a string literal in your code, the compiler creates a String object with its
value in this case, "Hello world!'.
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
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:
"Hello, world!"
STRING METHODS:
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
• Interfaces appear in packages, and their corresponding bytecode file must be in a directory structure that
matches the package name.
• An interface cannot contain instance fields. The only fields that can appear in an interface must be
declared both static and final.
DECLARING INTERFACES:
The interface keyword is used to declare an interface. Here is a simple example to declare an
interface:
EXAMPLE:
{
//Any number of final, static fields
//Any number of abstract method declarations\
}
• 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.
EXAMPLE:
/* File name : Animal.java */
interface Animal {
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:
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.
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.
• 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.
• 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.
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.
Now, let us implement the above interface in the same package animals:
package animals;
$ 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
There are some important differences between an applet and a standalone Java application,
including the following:
• 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:
If this Thread object was instantiated using a separate Runnable target, the run() method is invoked on that
2 Runnable
object.
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.
EXAMPLE:
The following ThreadClassDemo program demonstrates some of these methods of the Thread class. Consider a
class DisplayMessage which implements Runnable:
Following is the main program which makes use of above defined classes:
{
Runnable hello = new DisplayMessage("Hello");
Thread thread1 = new Thread(hello);
thread1.setDaemon(true);
thread1.setName("hello");
System.out.println("Starting hello thread...");
thread1.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.
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:
void start( );
EXAMPLE:
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
• 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.
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
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:
STEP 2:
At second step you will instantiate a Thread object using the following constructor:
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:
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.
Some of these exceptions are caused by user error, others by programmer error, and others by physical
resources that have failed in some manner.
• 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
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;
}
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:
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:
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.
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
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
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:
• 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.
................................ //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>
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
import java.applet.*;
import java.awt.*;
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.
javac appletname.java
The compiled output file called appletname.class should be placed in the smae directory as the source file.
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 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
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
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
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.
import java.awt.*;
import java.applet.*;
/*
<applet code="Rectangles" width=300 height=200>
</applet>
*/
DRAWING RECTANGLE
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.
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);
}
Output:-
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);
}
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
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);
}
Output:-
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
public int x, y;
public int width = 854;
public int height = 480;
public int border = 20;
public Image offscreen;
public Graphics d;
d = offscreen.getGraphics();
}
}
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)));
UNIT-IV
8 MARKS
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
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.)
STREAM 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.
try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");
int c;
lOMoAR cPSD| 42403338
CLASS DECLARATION
CLASS DECLARATION
Following is the declaration for Java.io.OutputStream class:
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
• 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 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.
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.
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.
You can create a temporary file using one of the following createTempFile methods:
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:
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.
while (out.hasRemaining())
fc.write(out);
out.rewind();
UNIT-V
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
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.