Java Material
Java Material
Java Material
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
Object means a real-world entity such as a pen, chair, table, computer, watch, etc. Object-
Oriented Programming is a methodology or paradigm to design a program using classes and
objects. It simplifies software development and maintenance by providing some concepts:
• Object
• Class
• Inheritance
• Polymorphism
• Abstraction
• Encapsulation
Apart from these concepts, there are some other terms which are used in Object-Oriented
design:
• Coupling
• Cohesion
• Association
• Aggregation
• Composition
Object
Any entity that has state and behavior is known as an object. For example, a chair, pen, table,
keyboard, bike, etc. It can be physical or logical.
An Object can be defined as an instance of a class. An object contains an address and takes up
some space in memory. Objects can communicate without knowing the details of each other's
data or code. The only necessary thing is the type of message accepted and the type of response
returned by the objects.
Example: A dog is an object because it has states like color, name, breed, etc. as well as
behaviors like wagging the tail, barking, eating, etc.
Object Definitions:
Class
A class can also be defined as a blueprint from which you can create an individual object. Class
doesn't consume any space.
• Fields
• Methods
• Constructors
• Blocks
• Nested class and interface
Inheritance
When one object acquires all the properties and behaviors of a parent object, it is known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
Polymorphism
Another example can be to speak something; for example, a cat speaks meow, dog barks woof,
etc.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For example phone
call, we don't know the internal processing.
Encapsulation
Binding (or wrapping) code and data together into a single unit are known as encapsulation. For
example, a capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class because all
the data members are private here.
Coupling
Coupling refers to the knowledge or information or dependency of another class. It arises when
classes are aware of each other. If a class has the details information of another class, there is
strong coupling. In Java, we use private, protected, and public modifiers to display the visibility
level of a class, method, and field. You can use interfaces for the weaker coupling because there
is no concrete implementation.
Cohesion
Cohesion refers to the level of a component which performs a single well-defined task. A single
well-defined task is done by a highly cohesive method. The weakly cohesive method will split
the task into separate parts. The java.io package is a highly cohesive package because it has I/O
related classes and interface. However, the java.util package is a weakly cohesive package
because it has unrelated classes and interfaces.
Association
Association represents the relationship between the objects. Here, one object can be associated
with one object or many objects. There can be four types of association between the objects:
• One to One
• One to Many
• Many to One, and
• Many to Many
Let's understand the relationship with real-time examples. For example, One country can have
one prime minister (one to one), and a prime minister can have many ministers (one to many).
Also, many MP's can have one prime minister (many to one), and many ministers can have many
departments (many to many).
Aggregation
Aggregation is a way to achieve Association. Aggregation represents the relationship where one
object contains other objects as a part of its state. It represents the weak relationship between
objects. It is also termed as a has-a relationship in Java. Like, inheritance represents the is-
a relationship. It is another way to reuse objects.
Composition
The composition is also a way to achieve Association. The composition represents the
relationship where one object contains other objects as a part of its state. There is a strong
relationship between the containing object and the dependent object. It is the state where
containing objects do not have an independent existence. If you delete the parent object, all the
child objects will be deleted automatically.
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.
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
•
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 programming 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
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.
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
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
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
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
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
SPECIAL OPERATORS
(Dot Operator) - To access instance variable
instanceof - Object reference Operator
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.
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.
• 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;
"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:
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
1 + ( Addition )
2 - ( Subtraction )
3 * ( Multiplication )
4 / (Division)
5 % (Modulus)
6 ++ (Increment)
7 -- ( Decrement )
OPERATOR DESCRIPTION
1 && (logical and)
2 || (logical or)
3 ! (logical not)
THE ASSIGNMENT OPERATORS:
1 =
2 +=
3 -=
4 *=
5 /=
6 %=
7 <<=
8 >>=
9 &=
10 ^=
11 |=
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;
}
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
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;
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
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:
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,
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:
6, DEFINING A CLASS
CLASSES IN JAVA:
void barking(){
}
void hungry(){
}
void sleeping(){
}
}
• Local variables
• Instance variables
• Class variables
7.METHOD DECLARATION
DEFINING METHODS
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.
8. CREATING OBJECTS
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.
• 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.
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.
3 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?
6 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?
Chapter - 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:
dataType[] arrayRefVar; // preferred way.
or
EXAMPLE:
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:
ARRAYLENGTH
EXAMPLE:
Following picture represents array myList. Here, myList holds ten double values and the indices
are from 0 to 9.
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.
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!"
4. STRING METHODS
STRING METHODS:
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.
void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
14
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
String replace(char oldChar, char newChar)
29
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.
static String valueOf(primitive data type x)
46
Returns the string representation of the passed data type argument.
5. INTERFACES
DECLARING INTERFACES:
EXAMPLE:
• 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 {
6. DEFINING INTERFACES
DEFINING AN INTERFACE
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.
• An implementation class itself can be abstract and if so interface methods need not be
implemented.
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.
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.
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:
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.
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
2
invoked on that 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.
SN METHODS WITH DESCRIPTION
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:
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.
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:
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:
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.
• 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.
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:
}
public class TestThread {
public static void main(String args[]) {
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.
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.
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
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:
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.
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,
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;
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.
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:
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.
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.
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.
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.
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
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>
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.
After creating FirstJavaApplet.java file now you need create FirstJavaApplet.html file as shown
below:
<!--
========================================================
File Name : FirstJavaApplet.html
WebSite : http://javaproglang.blogspot.in/
Facebook : https://www.facebook.com/AdvanceJavaProgramming
Created By : Bintu Chaudhary
========================================================
-->
<HTML>
<HEAD>
<TITLE>My First Java Applet Program</TITLE>
</HEAD>
<BODY>
<APPLET Code="FirstJavaApplet.class" Width=300 Height=200>
</APPLET>
</BODY>
</HTML>
After this you can comiple your java applet program as shown below:
"Running Applet"
"Output of FirstJavaApplet.class"
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.
import java.awt.*;
import java.applet.*;
/*
<applet code="Rectangles" width=300 height=200>
</applet>
*/
Output:-
DRAWING RECTANGLE
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
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);
}
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
{
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.
DRAWING POLYGONS
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);
}
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 int x, y;
public int width = 854;
public int height = 480;
public int border = 20;
public Image offscreen;
public Graphics d;
}
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);
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)));
6 MARKS
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 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:
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 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.*;
try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");
int c;
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
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
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:
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
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 file is readable.
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.
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.
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.
3 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?
6 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
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
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: