Ii Bca Java
Ii Bca Java
Ii Bca Java
1
QUESTION PAPER PATTERN
TIME:3 Hours Max.Marks:75
2
syllabus
Subject Title PROGRAMMING IN JAVA
Subject Code 21UCA08
Type Core: Theory
Unit Contents
Introduction to OOPS: Paradigms of Programming Languages – Basic concepts of
Object Oriented Programming – Differences between Procedure Oriented
Programming and Object Oriented programming - Benefits of OOPs – Application
of OOPs. Java: History – Java features – Java Environment – JDK – API.
I Introduction to Java: Types of java program – Creating and Executing a Java
program – Java Tokens- Java Virtual Machine (JVM) – Command Line Arguments
–Comments in Java program.
Elements: Constants – Variables – Data types - Scope of variables – Type casting –
Operators: Special operators – Expressions – Evaluation of Expressions. Decision
making and branching statements- Decision making and Looping– break – labeled
II loop – continue Statement. Arrays: One Dimensional Array – Creating an array –
Array processing – Multidimensional Array – Vectors – ArrayList – Advantages of
Array List over Array Wrapper classes.
Class and objects: Defining a class – Methods – Creating objects – Accessing class
members – Constructors – Method overloading – Static members –Nesting of
Methods – this keyword – Command line input. Inheritance: Defining inheritance –
III types of inheritance– Overriding methods – Final variables and methods – Final
classes – Final methods - Abstract methods and classes – Visibility Control-
Interfaces: Defining interface – Extending interface - Implementing Interface -
Accessing interface variables. Strings: String Array – String Methods – String
Buffer Class.
Packages: Java API Packages – System Packages – Naming Conventions –Creating
& Accessing a Package – Adding Class to a Package – Hiding Classes. Exception
Handling: Limitations of Error handling – Advantages of Exception Handling -
Types of Errors – Basics of Exception Handling – try blocks – throwing an
IV exception – catching an exception – finally statement. Multithreading: Creating
Threads – Life of a Thread – Defining & Running Thread – Thread Methods –
Thread Priority – Synchronization –Implementing Runnable interface – Thread
Scheduling.
I/O Streams: File – Streams – Advantages - The stream classes – Byte streams –
Character streams. Applets: Introduction – Applet Life cycle – Creating &
Executing an Applet –Applet tags in HTML – Parameter tag – Aligning the display -
V Graphics Class: Drawing and filling lines – Rectangles – Polygon – Circles – Arcs –
Line Graphs – Drawing Bar charts AWT Components and Even Handlers: Abstract
window tool kit – Event Handlers – Event Listeners – AWT Controls and Event
Handling: Labels – Text Component – Action Event – Buttons – Check Boxes –
Item Event – Choice– Scrollbars – Layout Managers- Input Events – Menus.
Text Books 1. E. Balagurusamy, ―Programming with Java‖, TataMc-Graw Hill, 5th Edition.
2. Sagayaraj, Denis, Karthick and Gajalakshmi, ―Java Programming for Core and
advanced learners‖, Universities Press (INDIA) Private Limited 2018.
Reference Books Herbert Schildt, ―The complete reference Java‖, TataMc-Graw Hill, 7th Edition.
Website / Link 1. NPTEL & MOOC courses titled Java https://nptel.ac.in/courses/106105191/
3
2. https://www.geeksforgeeks.org/java
3. https://www.tutorialspoint.com/java/
4
COURSE OUTCOMES:
PROGRAM OUTCOME:
Use an integrated development environment to write, compile, run, and test simple object-oriented
Java programs.
Read and make elementary modifications to Java programs that solve real-world problems.
Validate input in a Java program.
OBJECTIVES:
5
UNIT-I
6
Data structure are designed such that they characteristic the object.
Methods that operate on the data of an object are tried together in the data structure.
Data is hidden and cannot be accessed by external functions.
Objects may communicate with each other through methods.
New data and methods can be easily added whenever necessary.
Follow bottom-up approach in program design.
Object-oriented programming is an approach that provides away of modularizing
programs by creating partitioned memory area for both data and functions that can
be used as templates for creating copies of such modules on demand.
The wrapping up of data and methods in to single unit called is known as encapsulation.
Data Encapsulation is the most striking features of class.
This insulation of the data from direct access by the program is called data hiding.
7
Inheritance:
Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented programming
system).
Inheritance is the process by which objects of one class acquire the properties of objects of
another class.
Inheritance supports the concepts of hierarchical classification.
Polymorphism
Polymorphism is another important OOP concept.
Polymorphism means the ability to take more than one form.
That a single function name can be used a handle different number and different types of
arguments.
8
Polymorphism plays an important role in allowing objects having different internal structures
share the same external.
Dynamic Binding:
Binding refers to the linking of a procedure call to the code to be executed in response to the
call.
Dynamic binding means that the code associated with a given procedure call is not know until
the time of the call at runtime.
Message Communication:
An object-oriented program consists of a set of object that communicates with each other.
The process of programming in an object oriented language, basic steps.
Creating object from class definition.
Establishing communication among objects.
A message for an object is a request for executing of a procedure and therefore will invoke a
method procedure.
Message passing involves specifying the name of an object the name of the method(message
and information to be sent.
9
Differences between Procedure Oriented Programming and Object Oriented
programming
4. Data In procedural programming, data moves In OOP, objects can move and
movement freely within the system from one communicate with each other
function to another. via member functions.
10
10. Importance It gives importance to functions over data. It gives importance to data over
functions.
11. Virtual class In procedural programming, there are no In OOP, there is an appearance
virtual classes. of virtual classes in inheritance.
13. Data hiding There is not any proper way for data There is a possibility of data
hiding. hiding.
What is Java?
11
Java is popular high-level, class-based object oriented programming language
originally developed by Sun Microsystems and released in 1995. Currently Java is owned by
Oracle and more than 3 billion devices run Java. Java runs on a variety of platforms, such as
Windows, Mac OS, and the various versions of UNIX. Java is used to develop Mobile apps,
Web apps, Desktop apps, Games and much more
Java History
Java is a high-level programming language originally developed by Sun Microsystems and
released in 1991.
Java runs on a variety of platforms, such as Windows, Mac OS, and the various versions of
UNIX. So java is platform independent.
Java was designed for the development of software for consumer electronic devices like TVs,
VCRs, toasters and such other electronic devices.
1990 A team of Sun Microsystems headed by “James Gosling” was decided to develop a
special software that can be used to manipulate consumer electronic devices.
1991 The team announced a new language named “oak”.
1992 The team demonstrated the application of their new language to control a list of home
applications.
1993 The team known as Green Project team came up with the idea of developing web
applets.
1994 The team developed a web browser called “HotJava” to locate and run applet programs
on internet.
1995 Oak was renamed Java.
1996 Sun releases Java Development Kit 1.0.
1997 Sun releases Java Development Kit 1.1.
1998 Sun releases the Java 2 with version 1.2.
1999 Sun releases standard edition (J2SE) and enterprise edition(J2EE).
2000 J2SE with SDK(software development kit) 1.3 was released.
2002 J2SE with SDK 1.4 was released.
2004 J2SE JDK 5.0 was released. This is known as J2SE 5.0.
FEATURES OF JAVA
15
Java environment includes a large number of development tools and hundreds of classes and
methods.
The development tools are part of the system known as Java Development Kit(JDK) and
the classes and methods are part of the Java Standard Library(JSL), also known as the
Application Programming Interface(API).
JAVA DEVELOPMENT KIT (JDK)
Java Development Kit comes with a collection of tools used for developing and running java
programs. They are
Applet viewer (for viewing java applets) Enables us to run Java applets.
Javac (java compiler) It translates Java source code to byte code files that the interpreter
can understand.
Java(java interpreter) Java interpreter, which runs applets and applications by reading and
interpreting bytecode files.
Javadoc(for creating HTML document) Creates HTML format documentation from source
code files.
Javap(java dissembler)Enables us to convert bytecode files into a program description.
Javah(for C header files) Produces header files for use with native codes.
Jdb(java debugger) It helps us to find errors in our programs.
APPLICATION PROGRAMMING INTERFACE (API)
The java standard library (or API) includes hundreds of classes and methods grouped into
several functional packages. Most commonly used packages are
Language support package: - A collection of classes and methods required for
implementing basic features of java.
Utilities package: - A collection of classes to provide utility functions such as date
and time functions.
Input/output packages: -A collection of classes required for Input/output
manipulation.
Networking packages: - A collection of classes for communicating with other
computers via internet.
AWT packages: - The Abstract window Tool Kit package contains class that
implements platform independent graphical interface.
Applet package: - This includes set of classes that allows us to create java applets.
Java Run time Environment (JRE)
16
It facilitates the execution of programs developed in java. It comprises of the
following:
Java Virtual machine (JVM): It is a program that interprets the intermediate java
byte code and generates the desired output. It is because if byte code and JVM
concepts that programs written in Java are highly portable.
Runtime class libraries: There are a set of core class libraries that are required for
the execution of java programs.
User interface toolkits: AWT and swing are examples of toolkits that support varied
input methods for the users to interact with application program.
Deployment technologies: JRE comprises the following key deployment
technologies:
Java plug-in: Enables the execution of a java applet on the browser.
Java Web start: Enables remote-deployment of an application.
SIMPLE JAVA PROGRAM
class SampleOne
{
public static void main (String args[])
{
System.out.println(“ Java is better than C++”);
}
}
Class declaration
17
Opening Brace
Every class definition in java begins with an opening brace “{“ and ends with a
matching closing brace “}”.
Every java application program must include the main() method. This the starting point for
the interpreter to begin the execution of the program.
A java application can have any number of classes but only one of them must include a
main method to initiate the execution.
Public : The keyword public is an access specifier that declares the main method as
unprotected and therefore making it accessible to all other classes.
Static : Declares this method as one that belongs to the entire class and not a part of any
object of the class. The main methods must always be declared as static since the interpreter
uses this method before any object are created.
Void: The void states that the main method does not return any value.
Since java is a true object oriented language, every method must be part of an object.
The println method is a member of the out object, which is a static data member of System
class.
Suggested
Documentation section
Optional
Package statement
Optional
Interface statements
Optional
Class Definitions
The documentation section comprises a set of comment lines giving the name of the
program, the author and other details.
19
Comments must explain why and what of classes and how of algorithms.
Java also uses a third style of comment /** ….*/ known as documentation comment.
This form of comment is used for generating documentation automatically.
Package Statement:
This statement declares a package name and informs the compiler that the classes
define here belong to this package. Example
Package student;
This package statement is optional.
Import Statements:
This is similar to the # include statement in C. Example
Import student. test;
Interface Statements:
An interface is like a class but includes a group of method declaration.
This is also an optional section and is used only when we wish to implement the
multiple inheritance features in the program.
Class Definitions:
A java program may contain multiple class definitions.
Classes are the primary and essential elements of a java program.
These classes are used to map the objects of real world problem.
Main method class:
Every java program requires a main method as its starting point.
The main method creates objects of various classes and establishes
communication between them.
On reaching the end of main, the program terminates and the control back to
the operating system.
JAVA TOKENS
A java program is basically a collection of classes.
A class is defined by a set of declaration statements and methods containing executable
statements.
Most statements contain expression, which describe the actions carried out on data.
Smallest individual units in a program are known as tokens.
The compiler recognizes them for building up expressions and statements.
20
In simple terms, a java program is a collection of tokens, comments and white spaces.
Java language includes five types of tokens.
They are
Reserved keywords
Identifiers
Literals
Operators
Separators
Java Character set
The smallest units of java language are the characters used to write java
tokens.
These characters are defined by the Unicode character set, an emerging
standard that tries to create characters for a large number of scripts
worldwide.
Reserved keywords
Java language has reserved 60 words as keywords.
These keywords combined with operators and separators according to
syntax, form definition of the java language.
Since keywords have specific meaning in java, we cannot use them as
name for variables, classes, methods and so on. All keywords are to be
written in lowercase letters. Some examples are byte, class,
do, extends, for, import etc.
Identifiers
They are used for naming classes, methods, variables, objects, labels,
packages and interfaces in a program.
Rules for naming an identifier
They can be of any length.
Uppercase and lowercase letter are distinct.
They can have alphabets, digits, underscore and dollar sign
characters.
They must not begin with digit.
Eg average, sum
Literals
21
Literals in java are a sequence of characters that represent constant values
to be stored in variables.
Java language specifies five major types of literals. They are
Integer literals
Floating-point literals
Character literals
String literals
Boolean literals
Operators
An operator is a symbol that takes one or more arguments and operators on
them to produce a result.
Separators
Separators are symbols used to indicate where groups of code are divided and
arranged.
() parantheses, {} braces, [] brackets, ; semicolon, , comma, . period.
JAVA STATEMENTS
Java statements are like natural languages.
A statement is an executable combination of tokens ending with a semicolon (;) mark.
Statements are executed in sequence in the order in which they appear.
Empty statement These do nothing and are used during program development as a
place holder.
Labeled statement Any statement begin with a label, such labels must not be
keywords, already declared local variables, or previously used labels in this module. Labels in java
are usedas the arguments of jump statement.
Expression statements Java has seven types of Expression statements. Assignment,
preincrement, pre-decrement, post-increment, post-decrement, method call and Allocation
Expression.
Selection statement These select one of the several control flows. They are if, if-else
and switch
Iteration statement These specify how and when looping will take place. They are
while, do and for.
Jump statement Jump statement pass control to the beginning or end of the current
block or to a labeled statement. They are break, continue, return and throw.
Synchronization statement These are used for handling issues with multi-threading.
Guarding statement Used for safe handling of code that may cause exception.
These statements use the keywords try, catch, and finally.
22
JAVA VIRTUAL MACHINE
All language compilers translate source code into machine code.
Java compiler produces an intermediate code known as byte code for a machine that does not
exist.
This machine is called the Java Virtual Machine.
The process of compiling a java program into byte code is referred to as virtual machine
code.
Process of Compilation
The java object framework (Java API) acts as the intermediary between the user programs
and the virtual machine which in turn acts as the intermediary between the operating system and
the java object framework
Real Machine
23
Operating System
Compiler Interpreter
User
Java Comments
The Java comments are the statements in a program that are not executed by the compiler and
interpreter.
o Comments are used to make the program more readable by adding the details of the code.
o It makes easy to maintain the code and to find the errors easily.
o The comments can be used to provide information or explanation about the variable,
method, class, or any statement.
o It can also be used to prevent the execution of program code while testing the alternative code.
The single-line comment is used to comment only one line of the code. It is the widely used and
easiest way of commenting the statements.
Single line comments starts with two forward slashes (//). Any text in front of // is not executed by
Java.
Syntax:
25
1. //This is single line comment
CommentExample1.java
Output:
10
The multi-line comment is used to comment multiple lines of code. It can be used to explain a
complex code snippet or to comment multiple lines of code at a time (as it will be difficult to use
single-line comments there).
Multi-line comments are placed between /* and */. Any text between /* and */ is not executed by
Java.
Syntax:
1. /*
2. This
3. is
4. multi line
5. comment
6. */
7. public class CommentExample2 {
8. public static void main(String[] args) {
9. /* Let's declare and
10. print variable in java. */
11. int i=10;
12. System.out.println(i);
13. /* float j = 5.9;
14. float k = 4.4;
26
15. System.out.println( j + k ); */
16. }
17. }
Documentation comments are usually used to write large programs for a project or software
application as it helps to create documentation API. These APIs are needed for reference, i.e., which
classes, methods, arguments, etc., are used in the code.
To create documentation API, we need to use the javadoc tool. The documentation comments are
placed between /** and */.
1. /**
2. *
3. *We can use various tags to depict the parameter
4. *or heading or author name
5. *We can also use HTML tags
6. *
7. */
QUESTIONS
One Marks Question
27
1. Who invented Java Programming?
a) Guido van Rossum
b) James Gosling
c) Dennis Ritchie
d) Bjarne Stroustrup
Answer: b
Answer: d
3. Which component is used to compile, debug and execute the java programs?
a) JRE
b) JIT
c) JDK
d) JVM
Answer: c
Answer: b
Answer: c
Answer: d
28
7. Which environment variable is used to set the java path?
a) MAVEN_Path
b) JavaPATH
c) JAVA
d) JAVA_HOME
Answer: d
Answer: c
Answer: b
Answer: d
11. What will be the output of the following Java code snippet?
1. class abc
2. {
3. public static void main(String args[])
4. {
5. if(args.length>0)
6. System.out.println(args.length);7.
}
8. }
a) The snippet compiles and runs but does not print anything
b) The snippet compiles, runs and prints 0
29
c) The snippet compiles, runs and prints 1
d) The snippet does not compile
Answer: a
12. What will be the output of the following Java program?
1. class variable_scope
2. {
3. public static void main(String args[])
4. {
5. int x;
6. x = 5;
7. {
8. int y = 6;
9. System.out.print(x + " " + y);
10. }
11. System.out.println(x + " " + y);
12. }
13. }
a) Compilation error
b) Runtime error
c) 5 6 5 6
d) 5 6 5
Answer: a
1. class increment {
2. public static void main(String args[])
3. {
4. int g = 3;
5. System.out.print(++g * 8);6.
}
7. }
a) 32
b) 33
c) 24
d) 25
Answer: a
1. class Output
2. {
3. public static void main(String args[])
4. {
30
5. int arr[] = {1, 2, 3, 4, 5};
6. for ( int i = 0; i < arr.length - 2; ++i)
7. System.out.println(arr[i] + " ");
8. }
9. }
a) 1 2 3 4 5
b) 1 2 3 4
c) 1 2
d) 1 2 3
18. Can we keep a different name for the java class name and java file name?
A. Yes
B. No
A. Heap memory
B. Stack memory
C. Both A and B
D. None of these
31
20. Multiline comment is created using .
A. //
B. /* */
C. <! ------>
D. All of these
A. main() method
B. The first line of code
C. Last line of code
D. main class
A. Yes
B. No
A. Yes
B. No
A. exep
B. excepHand
C. throw
D. All of these
27. Which of these packages contains the exception Stack Overflow in Java?
a) java.io
b) java.system
c) java.lang
32
d) java.util
Answer: c
28. Which of these statements is incorrect about Thread?
a) start() method is used to begin execution of the thread
b) run() method is used to begin execution of a thread before start() method in special cases
c) A thread can be formed by implementing Runnable interface only
d) A thread can be formed by a class that extends Thread class
Answer: b
Answer: b
5 Marks
1. What is the difference between C and C++?
2. Expand JDK and SDK.
3. Define JVM.
4. Define Tokens.
5. What do you mean by escape sequences?
6. Define casting a value.
7. What is the difference between print( ) and println( ) method?
10 Marks
1. Explain in detail about features of java.
2. Describe about Java program structure.
3. Explain in detail about Java statements.
4. Explain Command line arguments with suitable example.
5. What are the types of constants? Explain in detail.
6. Write short notes on Data types in java.
7. Explain in detail about variables.
8 . Explain in detail about Operators and Expressions in java.
***************Unit I completed****************
UNIT- II
CONSTANTS
Constants refers to fixed values that do not change during the execution of a program.
33
Constants
Integer Constants
Decimal integer
Octal integer
Hexadecimal integer
Decimal integers consist of a set of digits, 0 through 9, preceded by an optional
minus sign.
Embedded spaces, commas, and non-digit characters are not permitted between
digits.
Valid Invalid
1234 70.00
-789 $234
Examples
0345
0556
34
0X2 0X9F 0xbcd 0x
Real Constants
Numbers containing fractional parts are called real or floating point constants. Examples
are
These numbers are shown in decimal notation , having a whole number followed by
decimal point and the fractional part, which is an integer. That is
A real number may also be expressed in exponential or scientific notation. For example,
the value 215.45 may be written as 2.1545e2 in exponential notation. The general form
is
mantissa e exponent
The mantissa is either a real number expressed in decimal notation or an integer.
The letter e separating the mantissa and the exponent can be written in either lowercase
or uppercase. Examples of legal floating point constants are
a whole number
a decimal point
a fractional part
an exponent
Single character constants
A single character constant contains a single character enclosed within a pair of single quote marks.
Examples of character constants are:
„5‟ „X‟ „:‟ „ „
String constants
35
A string constant is sequence of characters enclosed between double quotes.
The characters may be alphabets, digits, special characters and blank spaces. Examples are:
“Hello” “1997”
Backslash character constants
Java supports some special backslash character constants that are used in output methods.
For example, the symbol „\n‟ stands a new line character.
They consist of two characters. These characters combinations are known as escape sequences.
Meaning
Constant
Backspace
„\b‟
Form feed
„\f‟
New line
„\n‟
Carriage return
„\r‟
Horizontal tab
„\t‟
Single quote
„\”
Double quote
„\”‟
„\\‟
Backslash
VARIABLES
A variable is an identifier that denotes a storage location used to store a data value.
Variable names may consist of alphabets, digits, the underscore( _ ) and dollar characters,
subject to the following conditions:
1. They must not begin with a digit.
2. Uppercase and lowercase are distinct.
3. It should not be a keyword.
4. White space is not allowed.
5. Variable names can be of any length.
Declaration of variables
The declaration statement defines the type of variable. The general form of declaration of a
variable is:
36
Type variable1, variable2............................................. variableN;
Variables are separated by commas. A declaration statement must end with semicolon. Some valid
declarations are:
int count;
float x, y;
Giving values to variables
A variable must be given a value after it has been declared it is used in an expression. This can
be achieved in two ways:
1. By using an assignment statement
2. By using a read statement
Assignment Statement
A simple method of giving value to a variable is through the assignment statement as follows:
initialvalue = 0;
finalvalue = 123;
We can also string assignment expression as shown below:
x = y = z = 0;
It is also possible to assign a value to a variable at the time of its declaration. The general form is as
follows:
37
print ( ) method // print and wait
println ( ) method // print a line and move the next line
The print ( ) method prints output on one line until a new line character is
encountered. For example, the statements
System.out.print (“Hello”);
System.out.print(“Java!”);
will display the words Hello Java! On one line and waits for displaying further information
on the same line.
The println ( ) method, by contrast, takes the information provided and displays it on
a line followed by a line feed. For example
System.out.println (“Hello”);
System.out.println(“Java!”);
will produce the following output:
Hello
Java!
DATA TYPES
Data types specify the size and type of values that can be stored.
Primitive(Intrinsic) Non-Primitive(Derived)
Integer Types
Integer types can hold whole numbers such as 123, -96, 5678. Java supports four types of
integers. They are byte, short, int, and long.
38
Type Size Minimum value Maximum value
Byte One byte -128 127
Short Two bytes -32,768 32,767
Int Four bytes -2,147,483,648 2,147,483,647
Long Eight bytes -9,223,372,036,854,775,808 9,223,372,036,854,775,807
Character Type
Java provides a character data type called char.
The char type assumes a size of 2 bytes but, basically, it can hold only a single character.
Boolean Type
It is used to test a particular condition during the execution of the program.
There are only two values that a boolean type can take: true or false.
Boolean type is denoted by the keyword boolean and uses only one bit of storage.
SCOPE OF VARIABLES
Java variables are actually classified into three types:
Instance variables
Class variables
39
Local variables
Instance and class variable are declared inside a class. Instance variables are created when
the objects are instantiated and they are associated with the objects.
Class variables are global to a class and belong to the entire set of objects that class creates.
Only one memory location is created for each class variable.
Variables declared and used inside methods are called local variables. They are not
available for use outside method definition.
TYPE CASTING
We often encounter situations where there is a need to store a value on one type into a variable of
another type.
In such situation, we must cast the value to be stored by proceeding it with the type name in
parentheses. The syntax is
Introduction:
Java supports a rich set of operators.
40
An operator is a symbol that is used for manipulate data and variables.
Operators are used in programs to manipulate data and variables.
Java operators are classified into number of categories.
Arithmetic operators
Relational operators
Logical operators
Assignment operators
Increment and decrement operators
Conditional operators
Bitwise operators
Special operators
ARITHMETIC OPERATORS
Arithmetic operators are used to construct mathematical expressions as in algebra
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo division
When one of the operands is real and the other is an integer, the expression is called
a mixed-mode expression.
42
If either operand is of the real type, then the other operand is converted to real and
the real arithmetic is performed.
E.g.: 15/10.0=1.5
15/10=1
RELATIONAL OPERATORS
Compares two quantities depending on their Operator Meaning
relation.
< is less than
Java supports six relational operators.
<= is less than or equal
to
A simple relational expression contains
> is greater than
only one relational operator and is of the
following form: >= is greater than or
equal to
LOGICAL OPERATORS
Java has three logical operators.
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
A logical operator returns either TRUE or FALSE values.
Truth Table
43
op-1 op-2 op-1 && op-1 || op-
op-2 2
Logical operator && and || are used to check compound condition (ie for combining two or
more relations)
When an expression combines two or more relational expressions then it is called logical
expression or a compound relational expression
Eg: if (age>55 && salary<1000)
if (mark1>40 && mark2 >40)
ASSIGNMENT OPERATORS
Used to assign the value of an expression to a variable.
Assignment operators are usually in the form “=”.
Shorthand form:
v op=exp;
v variable
exp expression
op java binary operator
The assignment statement v op = exp; is equivalent to v= v op (exp);
a=a+1 a+=1
a=a-1 a-=1
44
a=a*(n+1) a*=n+1
a=a/(n+1) a/=n+1
A=a % b a%=b
Advantages:
It has 3 advantages.
Easy to write.
Easy to read
Efficient code.
INCREMENT AND DECREMENT OPERATORS
Eg. a[i++]
Sample Program:
class Incrementoperator
{
public static void main(String args[ ])
{
int m=10,n=20;
System.out. println("m=" +m);
System.out. println("n="+n);
S ystem.out. println("++m="+++m);
System.out.println("n++="+n++);
Systern.out. println("m="+m);
System .out. println("n="+n);
45
}
}
Output
m=10
n=20
++m=11
n++=21
m=11
n=21
CONDITIONAL OPERATORS
The character pair ?: is used for conditional operator.
It is also called as ternary operator.
General Form
exp1 ? exp2: exp3
exp1, exp2, exp3 are expressions
The operator ?: works as follows
Eg a=10;
b=15
X= (a>b) ? a : b;
The output is X=15
BITWISE OPERATORS:
Bitwise operators are used to manipulate data at values of bit level.
These operators are used for testing the bits, or shifting them to the right or left.
Bitwise operators may not to float or double.
Operator Meaning
46
! Bitwise OR
^ Bitwise exclusive OR
~ One‟s complement
47
Java can handled any complex mathematical expressions.
Java does not have an operator for exponentiation. Some of the expressions are
Algebraic exp: Java exp:
ab-c a*b-c
(m+n)(x+y) (m+n)*(x+y)
ab/c a*b/c
3x2+2x+1 3*x*x+2*x+1
Evaluation of Expression:
Expressions are evaluated using an assignment statement of the form
Variable=expression;
Variable is any valid Java variable name . When the statement is encountered , the expression is
evaluated first and the result then replaces the previous value of the variable on the left hand side.
Eg: x= a*b-c;
y= a-b /c+d;
An arithmetic expression without any parentheses will be evaluated from left to right using
the rules of precedence of operators.
The two distinct priority levels of arithmetic operators in Java are,
1. High priority */%
2.Low priority + -
If the operands are of different types, the lower type is automatically converted to the higher
type before the operation proceeds.
The result is of the higher type.
If byte, short and int variables are used in expression, the result is always promoted to int,
to avoid overflow.
If a single long is used in expression, the whole expression is promoted to long.
Casting a value:
To convert an object or variable of one type to another is called casting a value.
The general form of a cast is
(type_name) expression
Example
X = (int) 7.5 7.5 is converted to integer by truncation.
48
Highest
The () [] .
Precedence ++ –– ~ !
of the Java * / %
Operators + –
>> >>> <<
> >= < <=
== !=
&
^
|
&&
||
?:
= op=
Lowest
JAVA EXPRESSIONS
A Java expression consists of variables, operators, literals, and method calls. To know more about
method calls, visit Java methods. For example,
int score;
Score=90;
Here, score = 90 is an e xpression that returns an int. Consider another example,
Double a=2.2,b=3.4,result;
Result=a+b-3.4;
Here, a + b - 3.4 is an expression.
If(number1==number2)
System.out.println(“Number 1 is larger than number 2”);
Arithmetic Expressions
Java does not have an operator for exponentiation. Some of the expressions are
49
Algebraic exp: Java exp:
ab-c a*b-c
(m+n)(x+y) (m+n)*(x+y)
ab/c a*b/c
3x2+2x+1 3*x*x+2*x+1
Evaluation of Expression:
Variable=expression;
Variable is any valid Java variable name . When the statement is encountered , the expression
is evaluated first and the result then replaces the previous value of the variable on the left hand side.
Eg: x= a*b-c;
y= a-b /c+d;
When a program breaks the sequential flow and jumps to another part of the code, it is called
branching.
When the branching is based on a particular condition, it is known as conditional
branching.
If branching takes place without any decision, it is known as unconditional branching.
The following statements are known as control or decision making statements.
if statement
switch statement
Conditional operator statemen
DECISION MAKING WITH IF STATEMENT
The if statement is a powerful decision making statement and is used to control the flow of
execution of statements.
General form
if (test expression)
50
The expression is first evaluated.
Depending on the value of the expression is true or false, control is transfer to a particular
statement.
The if statement are
1. simple if statement
2. if…else statement
3. Nested if…else statement
4. else if ladder
1. Simple If Statement
If the test expression is true the statement block will be executed; otherwise the
execution will jump to the statement-x
Statement block may be single statement or a group of statement.
System.out.println(marks);
2. The If…Else Statement
If the test expression is true, then the true-block statements are executed.
Otherwise, the false block statements are executed.
General form Example
if (degree = = “BCA”)
if (test expression) {
{ points = points+500;
True block statements; System.out.println(“Its BCA”);
} }
else else
{ {
False block statements; points = points+200;
} System.out.println(“Its BSC
Statement-X; CS”);
}
3. Nesting of if …else statement ….
51
Here if the condition-1 is false, the statement-3 will be executed; otherwise it
evaluates the condition-2.
If the condition-2 is true, then statement-1 will be executed; otherwise the statement
-2 will be evaluated and then control is transferred to the statement-x.
General Form Example
if (test condition1) if (gender == “female”)
if (test condition2) if (balance>5000)
{ {
True blockstatements-1; Bonus = 0.03 * balance;}
} else
else {
{ Bonus = 0.02 * balance;
False block statement-2; }
} else
else
{
4. The else if ladder {
False block statements-3; Bonus = 0.01 * balance;
5. Nesting of if …else statement
} }
Statement-x;
4. Else if ladder balance=balance + bonus;
Else if ladder is a chain of ifs in which the statement associated with each else is an if.
The condition is evaluated from the top to downwards.
As soon as the condition is true, then the statements associated with it are
executed and the control is transferred to the statement -x.
When all the n condition is false, then the final else containing the default-
statement will be executed.
52
It an multiway decision statement.
The switch statement tests the value of a given variable against a list of case values.
When a match is found, a block of statement associated with that case is executed.
The expression is an integer expression or character known as case labels.
Block1, block2 … are statements lists may contain zero or more statements.
No need to put braces around each block
Case labels end with a colon (:)
The break statement at the end of each block signal the end of a particular case
and causes an exit from the switch statement, transferring the control to the
statement -x following the switch.
The default is an option case; it will be executed if the value of the expression
does not match with any of the case values.
If not present, no action takes place when all matches fail and the control goes to
the statement –x.
Example1
switch(expression)
General form {
case ‘1’:
switch(expression) System.out.println(“Monday”);
{ break;
case value-1: case ‘2’:
block-1 System.out.println(“Tuesday”);
break; break;
case value-2: case ‘3’:
block-2 System.out.println(“Wednesday”);
break; break;
case value-3: case ‘4’:
block-3 System.out.println(“Thursday”);
break; break;
……….. ………………
………. ………………..
default:
default-block default:
break; System.out.println(“WRONG INPUT”);
} break;
statement-x; }
System.out.println(“ WELCOME TO THIS WEEK”);
…..
THE ? : OPERATOR
If (x<0)
Flag=0;
53 else
Flag=1;
It is a two-way decision making operator.
This operator is a combination of ? and : and takes three operands.
This operator is popularly known as the conditional operator.
INTRODUCTION
54
The simplest of all the looping structures in java is the while statement.
The while is an entry-controlled loop statement.
The test condition is evaluated and if the condition is true, then the body of the loop is
executed.
After execution of the body, the test condition is once again evaluated and if it is true, the
body is executed once again.
The execution of the body continues, until the test condition becomes false and the
control is transfer out of the loop.
On exit, the program continues with the statement immediately after the body of the loop.
THE DO STATEMENT
In do statement, the program proceeds to evaluate the body of the loop first.
At the end of the loop, the test condition in the while statement is evaluated.
If the condition is true, the program continues to evaluate the body of the loop once again.
The program continues to evaluate the body of the loop as long as the condition is true.
When the condition becomes false, the loop will be terminated and the control goes to the
statement that appears immediately after the while statement.
do
General form
Initialization;
Example
S
u 55
m
=
0
;
N
=
1
;
d
o
{
THE FOR STATEMENT
(1) Initialization of the control variables is done first, using assignment statements such as
i=1 and count=0. The variable i and count are known as loop-control variables.
(2) The value of the control variables is tested using the test condition. The test condition is
a relational expression, such as i<10 that determines when the loop will exit.
It the condition is true, the body of the loop is executed; otherwise the loop is
terminated and the execution continues with the statement that immediately
follows the loop.
(3) When the body of the loop is executed, the control is transferred back to the for statement
after evaluating the last statement in the loop.
Now the control variable is incremented using an assignment statement such as i=i+1
and the new value of the control variable is again tested to see whether it satisfies the
loop condition.
If the condition is satisfied, the body of the loop is again executed.
This process continues till the value of the control variable fails to satisfy the test
condition.
General form
for (initialization; test condition; increment)
{
Body of the loop
}
for (i=0;i<=10;i++) 56
{
System.out.println(i);
Addition features of for loop
p=1; valid
for(n=0; n<17; ++n)
m=5;
Can be written as for ( ; m!=100; )
{
for (p=1, n=0; n<17; ++n) valid System.out.println(m);
m = m + 5;
for (n=1, m=50; n<=m; n=n+1,m=m-1) valid }
A for loop which is present inside of another for loop is called nesting of for loop.
JUMPS IN LOOPS
Loops perform a set of operations repeatedly until the control variable fails to satisfy the test
condition.
Java permits a jump from one statement to the end or beginning of a loop as well as a jump
out of a loop.
57
Jumping out of a loop
58
A label is any valid java variable name.
To give a label to a loop, place the label before the loop with a colon at the end.
ARRAY
An array is a group of contiguous or related data items that share a common name.
E.g. name[10]
The individual values are called elements.
A list of items can be given one variable name using only one subscript called single
subscripted variable or one dimensional array.
For example, The values to the array elements 35, 40, 20, 57, 19 can be assigned as
follows:
59
number[0] = 35;
number[1] = 40;
number[2] = 20;
number[3] = 57;
number[4] = 19;
CREATING AN ARRAY
Arrays must be declared and created in the computer memory before they are used.
Form1 Form2
60
Initialization of Arrays
arrayname [subscript]=value;
Eg: number[0]=90;
number[1]=100;
……….
Arrays starts with a subscript 0 and ends with a value one less than the size specified.
Trying to access an array beyond its boundaries will generate an error message.
If size is not specified means compiler allocates enough space for all the elements specified
in the list
Array length
61
Eg : int myarray[][];
myarray=new int[3][4];
Example program:
class MulTable
System.out.println(“ “);
int i,j;
62
for ( j =10; j < COLUMNS; j++)
product [i] [ j] = i * j;
System.out.println(“ “ + product [ i] [ j ];
System.out.println(“ “);
VECTORS
We can add and delete objects from the list as and when required.
63
list.removeElementAt(n) Removes the item stored in the nth position
of the list
WRAPPER CLASS
Vectors cannot handle primitive data types like int, float, double and char.
This conversion is done by using the wrapper class contains in the java.lang package
64
Converting primitive numbers to object numbers using constructor
methods
65
str= Long.toString(l); Primitive long to string
66
Float f1=new float (num1) changing to object
float num1=Float.ValueOf(in.readLine());
int val=Integer.ParseInt(in.readLine());
*******************UNIT II COMPLETED*********************
67
c) java.lang
d) java.util
6. Which of these keywords are used for the block to be examined for exceptions?
a) check
b) throw
c) catch
d) try
7. Which one of the following is not an access modifier?
a) Protected
b) Void
c) Public
d) Private
8. What is the numerical range of a char data type in Java?
a) 0 to 256
b) -128 to 127
c) 0 to 65535
d) 0 to 32767
9. Which class provides system independent server side implementation?
a) Server
b) ServerReader
c) Socket
d) ServerSocket
10. Which class in Java is used to take input from the user?
A. Scanner
B. Input
C. Applier
D. None of these
11. Which class in Java is used to take input from the user?
A. Scanner
B. Input
C. Applier
D. None of these
A. next()
B. nextLine()
C. Both A. and B.
D. None of these
13. Which of the following is the correct syntax to create a variable in Java?
68
A. var name;
B. int name;
C. var name int;
D. All of these
A. Yes
B. No
A. Instance Variable
B. Local Variable
C. Static Variable
D. All of these
A. Hello
B. Bye
C. Error
D. All of these
A. Widening typecasting
B. Narrowing typecasting
69
C. Manual typecasting
D. All of these
A. Class
B. Method
C. Variable
D. All of these
A. Try-catch block
B. Class block
C. Method block
D. All of these
A. 1
B. No output
C. 8
D. 1357911
23. Can the Java program accept input from the command line?
70
A. Yes, using command-line arguments
B. Yes, by access command prompt
C. No
D. None of these
Answer: c
Answer: b
Answer: d
Answer: c
Answer: c
32. Which of these packages contains the exception Stack Overflow in Java?
a) java.io
b) java.system
c) java.lang
d) java.util
Answer: c
Answer: b
34. Which of these keywords are used for the block to be examined for exceptions?
a) check
b) throw
c) catch
d) try
Answer: d
72
b) Void
c) Public
d) Private
Answer: b
Answer: c
37. Which class provides system independent server side implementation?
a) Server
b) ServerReader
c) Socket
d) ServerSocket
Answer: d
39. Which of the following option leads to the portability and security of Java?
Answer: (a)
a. Dynamic
b. Architecture Neutral
c. Use of pointers
d. Object-oriented
73
5 Marks
1. Explain in detail about If statements.
2. Describe about switch statement.
3. Explain in detail about Looping statements with suitable examples.
4. Write short notes on Type Casting
5. Write short notes on Scope Variables.
6. Explain in detail about Abstract methods and classes.
7. Describe about Final variables and methods.
10 Marks
1. Explain in detail about Decision Making.
2 .Explain in detail about array.
74
UNIT III
INTRODUCTION
CLASS: “A class is a way of binding the data and associated methods in a single unit”
Any JAVA program if we want to develop then that should be developed with respective
class only i.e., without class there is no JAVA program.
Classes create objects and object uses methods to communicate between them.
Classes provide convenient method for packing together a group of logically related data
items and functions that work on them.
The data items are called fields and the functions are called methods.
DEFINING A CLASS
A class is a user-defined data type with a template that serves to define its properties.
Anything in square bracket is optional.
Classname and superclassname are valid java identifiers.
The keyword extends indicates that the properties of the superclassname class are extended
the classname class.
FIELDS DECLARATION
Data is encapsulated in a class by placing data fields inside the body of the class definition.
These variables are called instance variables because they are created whenever an object of
the class is instantiated.
Instance variables are also know as member variables.
75
Example
class Triangle
{
int length;
int height;
}
The class triangle contains two integer type instance variable, length
and height.
METHODS DECLARATION
CREATING OBJECTS
OBJECT: In order to store the data for the data members of the class, we must create an
object.
76
Instance (instance is a mechanism of allocating sufficient amount of memory space
for data members of a class) of a class is known as an object.
Class variable is known as an object.
Grouped item (grouped item is a variable which allows us to store more than one
value) is known as an object.
Value form of a class is known as an object.
Blue print of a class is known as an object.
Real world entities are called as objects.
Eg2: Triangle tri1 = new Triangle ( ); tri1 and tri2 are the objects of Triangle
class
77
ACCESSING CLASS MEMBERS
we can access class members using DOT(.) operator
Syntax:
Accessing variables Accessing method
class Square
{
int side;
void getdata(int s)
{
side=s;
}
int rectarea()
{
int area=side * side;
return(area);
}
}
class Squareaea
{
public static void main (String args[])
{
Square s1= new Square();
s1.getdata(5);
sqarea =s1.rectarea();
System.out.println(sqarea);
}
}
78
CONSTRUCTORS
Java supports a special type of method called a constructor that enables an object to
initialize itself when it is created.
Constructors have the same name as the class name.
They does not return any value and do not specify even void.
Constructors are automatically called during the creation of the objects.
EXAMPLE:
class Volume
{
int x,y,z;
Volume() // constructor
{
x=10;
Y=10;
Z=30;
}
int calvolume()
{
int vol=x*y*z;
return vol;
}
}
class Demovolume()
{
public static void main(String args[])
{
Volume volobj=new Volume; // creating object
int result=volobj.calvolume(); // calling method
System.out.println(“the volume is =”+result);
}
}
ADVANTAGES OF CONSTRUCTORS:
1. A constructor eliminates placing the default values.
2. A constructor eliminates calling the normal method implicitly.
RULES/PROPERTIES/CHARACTERISTICS of a constructor:
1. Constructor name must be similar to name of the class.
2. Constructor should not return any value even void also (if we write the return type for the
constructor then that constructor will be treated as ordinary method).
79
3. Constructors should not be static since constructors will be called each and every time
whenever an object is creating.
4. Constructor should not be private provided an object of one class is created in another
class
(constructor can be private provided an object of one class created in the same class).
5. Constructors will not be inherited at all.
6. Constructors are called automatically whenever an object is creating.
TYPES OF CONSTRUCTORS:
Based on creating objects in JAVA we have two types of constructors.
They are
1. Default/parameter less/no argument constructor and
2. Parameterized constructor.
1. DEFAULT CONSTRUCTOR
A default constructor is one which will not take any parameters.
Syntax: class Test
class <clsname> {
{ int a, b;
clsname () //default constructor Test ()
{ {
Block of statements; System.out.println ("I AM FROM DEFAULT
………………………………; CONSTRUCTOR...");
………………………………; a=10;b=20;
} System.out.println ("VALUE OF a = "+a);
………………………; System.out.println ("VALUE OF b = "+b);
………………………; }
}; };
class TestDemo
{
public static void main (String [] args)
{
Test t1=new Test ();
}
};
80
2. PARAMETERIZED CONSTRUCTORS
class Volume
{
int x,y,z;
return vol;
}
}
class Demovolume()
METHOD OVERLOADING
Methods that have the same name, but different parameter lists and different definitions are
called method overloading.
81
Method overloading is used when objects are required to perform similar tasks but using
different input parameters.
Java matches up the method name first and then the number and type of parameters to
decide which one of the definition to execute. This process is known as polymorphism.
class Calculatearea
{
int area()
{
int val=10*20*30;
return val;
}
int area(int m, int n)
{
int val=m*n;
return val;
}
int area(int l, int m, int n)
{
int val=l*m*n;
return val;
}
float area(float m, float n)
{
float val=m*n;
return val;
}
float area(int l, float m, int n)
{
float val=l*m*n;
return val;
}
}
class Demovolume()
{
public static void main(String args[])
{
Calculatearea calarea=new calculatearea();
int result1, result2, result3;
float result4, result5;
result1=calarea.area();
result2=calarea.area(10,20);
result3=calarea.area(100,200,300);
result4=calarea.area(10.2,20.2);
result5=calarea.area(10,20.2,10);
System.out.println(result1,result2,result3, result4,result5);
} STATIC MEMBE
}
82
It defines a member that is common to all the objects and accessed without using a particular
object.
That is the member belongs to the class as a whole rather than the objects created form the
class.
Static members can be defined as follows
static int count;
Static members are associated with the class itself rather than individual object.
Static variables and static methods are often referred to as class variables and class methods.
Static variables are used when we want to have a variable common to all instances of a class.
Eg: variable that keep a count of how many objects of a class have been created.
Static variables and static methods are called without using the objects.
Restriction of static methods
{return x*y;
{return x/y;
class Mathapplication
float a= mathoperation.mul(4.0,5.0);
float b=mathoperation.divide(4,2.0);
System.out.println(a,b);
For example, Math class of java library defines many static methods to perform math operations that can be
used in any program.
83
NESTING OF METHODS
A method can be called by using only its name by another method of the same class. This is
known as nesting of methods.
Example
class Nesting
int a, b, result;
Nesting(int x, int y)
a=x;
b=y;
void Process()
{ result = a+b;
display();
void display()
{ System.out.println(result); }
class nestingtest
nest.process();
}}
84
THIS KEYWORD
Example
Int x;
Publc Main(int x) {
This.x=x;
Sysytem.out.println(
“Value of x=”+myObj.x);
85
JAVA COMMAND LINE INPUT
The java command-line argument is an argument i.e. passed at the time of running the java
program.
The arguments passed from the console can be received in the java program and it can be used
as an input.
So, it provides a convenient way to check the behavior of the program for the different values.
You can pass N (1,2,3 and so on) numbers of arguments from the command prompt.
In this example, we are receiving only one argument and printing it.
To run this java program, you must pass at least one argument from the command prompt.
In this example, we are printing all the arguments passed from the command-line. For this purpose, we have
traversed the array using for loop.
86
1. compile by > javac A.java
2. run by > java A sonoo jaiswal 1 3 abc
INHERITANCE
When one class acquires the properties of another class it is known as inheritance.
( The mechanism of deriving a new class from an old one is called inheritance.)
A class that is inherited is called a super class or base class.
The class that does the inheriting is called a subclass or derived class.
Advantage of inheritance is that it allows reusability of coding.
Inheritance may take different forms. They are
1. Single inheritance
Single class is one in which there exists single base class and single derived class.
87
3. Hierarchical inheritance
Hierarchical inheritance is one in which there exits single base class and n number of
derived classes.
4. Multiple inheritance
Multiple inheritance is one in which there exists n number of base classes and single derived
classes.
Multiple inheritances are one supported by JAVA through classes but it is supported by
JAVA through the concept of interfaces.
Defining a subclass
88
variables declaration;
methods declaration;
The keyword extends signifies that the properties of the superclassname are extended to the
subclassname.
SINGLE INHERITANCE
When a single sub class extends the properties of a single super class, then it is known as
single level inheritance.
Example
class Room
int volume ()
{ {
return (Length*Breadth*Height);
int Length, Breadth;
}
Room (int x, int y) }
class inhert
{
{
Length=x; public static void main (String args[])
{
Breadth=y; Room1 obj=new Room1(14,12,10);
} int area1=obj.area ();
int volume1=obj.volume();
int area () System.out.println(“Area1 =”+area1);
{ System.out.println(“Volume =”+volume1);
return (Length*Breadth); }
}
}
}
class Room1 extends Room
{
int height;
Room1 (int x, int y, int z)
{
super (x, y);
Height=z;
}
}
89
SUBCLASS CONSTRUCTOR
A subclass constructor is used to construct the instance variables of both the subclass and the
super class.
The sub class constructor uses the keyword super to invoke the constructor method of the
super class.
The keyword super is used in following conditions.
Super may only be used within a subclass constructor method.
The call to super class constructor must appear as the first statement within the sub class
constructor.
The parameter in the super call must match the order and type of the instance variable declared
in the program.
MULTILEVEL INHERITANCE
Since java supports the concept of concept of inheritance it is extensively used in building
the class library.
Multilevel inheritance is used to build chain of classes.
Example
class Rectangle
class Circle extends Box
{
{
int L, W; circle (int i, int j, int k)
Rectangle (int i, int j) {
super (i, j, k);
{ System.out.println(“Area=”+(3.14*i*i));
L=i; }
}
W=j;
class mainclass
System.out.println(“Area =” +(L*W)); {
} public static void main(String args[])
{
} Circle obj=new Circle (10, 20, 30);
class Box extends Rectangle }
}
{
Box (int i, int j, int k)
{
super (i, j);
Output
System.out.println(“Volume=”+(i*j*k));
Area =200
}
} Volume=6000
90
HIERARCHICAL INHERITANCE
91
This is possible by defining a method in the sub class that has the same name, same arguments
and same return type as a method in the super class.
When the methods are called, the method defined in the sub class is invoked and executed
instead of the one in the super class. This is known as overriding.
Example
class Super
{ int x; void display ()
Super (int x) {
{ System.out.println(“Super x=”+x);
System.out.println(“Sub y=”+y);
this.x=x;
} }
} class overridetest
void display () {
{ public static void main (String args[])
{
System.out.println(“x=”+x);
Sub S1=new Sub (100, 200);
} S1.display ();
} }
}
class Sub extends Super
{ int y;
Sub (int x, int y)
{
super (x);
this.y=y;
}}
FINAL VARIABLES AND METHODS
It prevents the subclasses form overriding the member of the superclass.
Final variables and methods are declared as final using the keyword final as a modifier.
Example: size =100
final int SIZE = 100;
final void showstatus( ){….............. }
Making a method final ensures that the functionality defined in that method will never be
altered in any way.
The value of a final variable can never be changed.
92
FINAL CLASSES
A class that cannot be sub-classed is called a final class.
It prevents a class being further sub-classed for security reasons.
Any attempt to inherit these classes will cause an error.
FINALIZER METHODS
Initialization constructor method is used to initialize an object when it is declared.
This process is called initialization.
Finalizationfinalize method is just opposite to initialization, it automatically frees up
the memory resources used by the objects. This process is known as finalization.
It acts like a destructor.
The method can be added to any class.
Here, the keyword protected is a specifier that prevents access to finalize( ) by code defined
outside its class.
For example:
abstract class Op
{
abstract void sum ();
};
ABSTRACT METHODS
When a method is defined as final than that method is not re-defined in a subclass.
Java allows a method to be re-defined in a sub class and those methods are called abstract
methods.
When a class contains one or more abstract methods, then it should be declared as abstract class.
When a class is defined as abstract class, it must satisfy following conditions
We can‟t use abstract classes to instantiate objects directly. For example
94
Op s = new Op( )
is illegal because Op is an abstract class.
The abstract methods of an abstract class must be defined in its sub class.
We can‟t declare abstract constructors or abstract static methods.
Final allows the methods not redefine in the subclass.
Abstract method must always be redefined in a subclass, thus making overriding
compulsory.
This is done using the modifier keyword abstract in the method definition.
When a class contains one or more abstract methods, it should also be declared abstract.
Example
abstract class shape
{
………..
…………
abstract void draw();
…………
………..
}
RULES:
We cannot use abstract classes to instantiate objects directly.
The abstract methods of an abstract class must be defined in its subclass.
We cannot declare abstract constructors or abstract static method.
General form
<access specifier> <static> void method-name (object …arguments)
{
}
In the above syntax The method contains an argument called varargs in which
95
Object is the type of an argument
Ellipsis (…) is the key to varargs
Argument is the name of the variable.
For eg: Public void sample(String username, String password, String mail)
Can be written as Public void sample (String …var_name)
Here var_name is the variable name that specifies that we can pass any number of
String arguments to the sample method.
Example program
Class exampleprg
{
Exampleprg(String… person)
{
for (String name: person)
{
System.out.println(“hello” + name);
}
}
public static void main(String ars[])
{
exampleprg (“ram”, “siva”, “suriya”);
}
}
VISIBILITY CONTROL
The modifiers are also known as access modifiers.
Java provides three types of visibility modifiers: public, private and protected.
Public Access:
To declare the variable or method as public, it is visible to the entire class in which it is
defined.
Example:
public int number;
public void sum ( ) {… ..................}
Friendly Access:
When no access modifier is specified, the number defaults to a limited version of public
accessibility known as “friendly” level of access.
96
The difference between the “public” and “friendly” access is that the public modifier makes
fields visible in all classes.
While friendly access makes fields visible only in the same package, but not in other
package.
Protected Access:
The protected modifier makes the fields visible not only to all classes and subclasses in
the same package but also to subclasses in other packages.
Non-subclasses in other packages cannot access the “protected” members.
Private Access:
Private fields are accessible only with their own class.
They cannot be inherited by subclasses and therefore not accessible in subclasses.
A method declared as private behaves like a method declared as final.
Private protected Access:
A field can be declared with two keywords private and protected together like:
private protected int codeNumber;
This gives a visibility level in between the “protected” access and “private” access.
Rules:
1. Use public if the field is to be visible everywhere.
2. Use protected if the field is to be visible everywhere in the current package and also
subclasses in other packages.
3. Use “default” if the field is to be visible everywhere in the current package only.
4. Use private protected if the field is to be visible only in subclasses, regardless of
packages.
5. Use private if the field is not to be visible anywhere except in its own class.
INTERFACES
INTRODUCTION
97
An interface is a construct which contains the collection of purely undefined
methods or an interface is a collection of purely abstract methods.
DEFINING INTERFACES
interface <InterfaceName>
Example
interface Item
{
{
variablesstatic final int code = 1001;
declaration;
void display();
}
methods declaration;
All variables are declared as constants. Methods declaration will contain only a list of methods
without any body statements.
EXTENDING INTERFACES
For example, we can put all the constants in one interface and the methods in the other.
98
interface ItemConstants
{
The interface Item will inherit both the constants code and name into it.
IMPLEMENTING INTERFACES
99
class mainpgm
{
interface interfaceA public static void main(String args[])
{ {
final int m=10; ClassA objA=new classA();
} objA.show();
class ClassA implements interfaceA }
{ }
void show()
{
System.out.println(m);
}
}
100
STRINGS
In java strings are class objects and implemented using two classes; String and StringBuffer.
A java string is an instantiated object of the String class. Strings may be declared and created
as follows:
General form
String stringname;
Stringname = new String(“string”);
Eg
String firstname;
firstname=new String(“anil”);
Or
String firstname=new String(“anil”);
String arrays
item[0]=”soap”;
item[1]=”biscuits”;
item[2]=”powder”;
101
String methods
s2=s1.trim(); Remove white space at the beginning and end of the String s1
s1.indexOf(„x‟) Gives the position of the first occurrence of „x‟ in the string s1
s1.indexOf(„x‟,‟n‟); Gives the position „x‟ that occurs after nth position in the string
s1
102
s1.compareTo(s2) Returns negative if s1<s2, positive if s1>s2, zero if s1 and s2
equal.
In stringbuffer class we can insert characters and substrings in the middle of a string, or
append another string to the end.
Methods Task
Example program
class stringmanipulation
{
public static void main(String args[])
{
StringBuffer str=new StringBuffer(“object language”);
System.out.println(“original string:”+ str);
// obtain string length
Systme.out.println(“length of string:” +str.lenght());
// accessing characters in a string
for (int i=0; i<str.length();i++)
{
int p=i+1;
System.out.println(“character at position: “+ p + “ is” + str.charAt( i));
104
}
// inserting a string in the middle
105
String astring=new String(str.toString());
int pos=astring.indexOf(“ language”);
str. insert(pos, “oriented”);
System.out.println(“modified string: “+str);
// modifying characters
str.setcharAt(6,‟-„);
System.out.println(“string now: ” + str);
// append a string at the end
str.append (“improve security.”);
System.out.println(“appending string:” +str);
}
}
One Mark
1. Which of these keywords is used to define interfaces in Java?
a) interface
b) Interface
c) intf
d) Intf
2. Which of these can be used to fully abstract a class from its implementation?
a) Objects
b) Packages
c) Interfaces
d) None of the Mentioned
5. Which of the following is the correct way of implementing an interface salary by class
manager?
a) class manager extends salary {}
b) class manager implements salary {}
c) class manager imports salary {}
d) none of the mentioned
7. Which of these is a mechanism for naming and visibility control of a class and its content?
a) Object
b) Packages
c) Interfaces
d) None of the Mentioned.
8. Which of this access specifies can be used for a class so that its members can be accessed by a
different class in the same package?
a) Public
b) Protected
c) No Modifier
d) All of the mentioned
9. Which of these access specifiers can be used for a class so that its members can be accessed by a
different class in the different package?
a) Public
b) Protected
c) Private
d) No Modifier
10. Which of the following is the correct way of importing an entire package „pkg‟?
a) import pkg.
b) Import pkg.
c) import pkg.*
d) Import pkg.*
11. Which of the following package stores all the standard java classes?
a) lang
b) java
c) util
d) java.packages
12. Which of these operators is used to allocate memory to array variable in Java?
a) malloc
b) alloc
c) new
d) new malloc
107
13. Which of these is an incorrect array declaration?
a) int arr[] = new int[5]
b) int [] arr = new int[5]
c) int arr[] = new int[5]
d) int arr[] = int [5] new
intarr[]=newint[5];
System.out.print(arr);
a) 0
b) value stored in arr[0]
c) 00000
d) Class name@ hashcode in hexadecimal form
108
c) Every string is an object of class String
d) Java defines a peer class of String, called StringBuffer, which allows string to be altered
22. What will be the output of the following Java program?
1. classstring_demo
2. {
3. publicstaticvoidmain(Stringargs[])
4. {
5. String obj ="I"+"like"+"Java";
6. System.out.println(obj);
7. }
8. }
a) I
b) like
c) Java
d) IlikeJava
Answer: a
28. When does method overloading is determined?
a) At run time
b) At compile time
c) At coding time
d) At execution time
109
Answer: b
Answer: d
30. Which concept of Java is a way of converting real world objects in terms of class?
a) Polymorphism
b) Encapsulation
c) Abstraction
d) Inheritance
Answer: c
31. Which concept of Java is achieved by combining methods and attribute into a class?
a) Encapsulation
b) Inheritance
c) Polymorphism
d) Abstraction
Answer: a
32. What is it called if an object has its own lifecycle and there is no owner?
a) Aggregation
b) Composition
c) Encapsulation
d) Association
Answer: d
33. What is it called where child object gets killed if parent object is killed?
a) Aggregation
b) Composition
c) Encapsulation
d) Association
Answer: b
34. What is it called where object has its own lifecycle and child object cannot belong to another
parent object?
a) Aggregation
b) Composition
c) Encapsulation
d) Association
110
Answer: a
35. Method overriding is combination of inheritance and polymorphism?
a) True
b) false
Answer: a
36. What is the default encoding for an OutputStreamWriter?
a. UTF-8
b. Default encoding of the host platform
c. UTF-12
d. None of the above
37. What is the return type of the hashCode() method in the Object class?
a. Object
b. int
c. long
d. void
38. Evaluate the following Java expression, if x=3, y=5, and z=10:
++z + y - y + z + x++
a. 24
b. 23
c. 20
d. 25
Answer: (d) 25
39. Which of the following tool is used to generate API documentation in HTML format from
doc comments in source code?
a. javap tool
b. javaw command
c. Javadoc tool
d. javah command
111
5 Marks
UNIT IV
PACKAGES
INTRODUCTION
112
In java we have two types of packages they are
I)predefined or built-in or core packages and
II)user or secondary or custom defined packages.
BENEFITS:
The classes contained in the packages of other programs can be easily reused.
In packages, classes can be unique compared with classes in other packages.
That is two classes in two different packages can have the same name.
They may be referred by their fully qualified name, comprising the package name and the
class name.
Packages provide a way to "hide" classes thus preventing other programs or packages from
accessing classes that are meant for internal use only.
Packages also provide a way for separating "design" form "coding".
Packages Contents
java.util Language utility classes such as vectors, hash tables, random number,
date etc.
113
1. Using the fully qualified class name. (Using the package name containing the
class and then appending the class name by using the dot operator.)
E.g. java.awt.Color
Best and easiest one to access the class
Used only once, not possible to access other classes of the package.
2. Using the import statement, appear at the top of the file. Imported package class
can be accessed anywhere in the program
Or
Import packagename.*
These are known as import statements and must appear at the top of the file, before any
class declarations, import is a keyword.
The first statement allows the specified class in the specified package to be imported. For
example, the statement
import java.awt.Color;
imports the class Color and therefore the class name can now be directly used in the program.
The second statement imports every class contained in the specified package. For example, the
statement
import java.awt.*;
will bring all classes of java.awt package.
NAMING CONVENTIONS
CREATING PACKAGES
First declare the name of the package using the package keyword followed by a package
name.
This must be the first statement in a java source file.
Example
package firstpackage; // package declaration
public class FirstClass // class definition
{
…….
……. // body of class
}
Steps:
package packagename;
Define the class that is to be put in the package and declare it public.
Create a subdirectory under the directory where the main source files are stored.
Store the listing as the classname.java file in the subdirectory created.
Compile the file. This creates .class file in the subdirectory.
115
ACCESSING A PACKAGE
Example 1
Example 2
116
package p1;
public class X // public class, available outside
{
// body of X
}
class Y // not public, hidden
{
// body of Y
}
Here the class Y which is not declared public is hidden from outside of the package p1.
This class can be seen and used only by other classed in the same package.
Consider the following code, which imports the package p1 that contains classes X and Y:
import p1. *;
X objectX; // ok; class X is available here.
Y objectY; // not ok: Y is not available.
Java compiler generate an error message because the class Y is not declared as public.
STATIC IMPORT
The static import declaration is similar to that of import.
The import statement to import classes from packages and use them without qualifying the
package.
The static import statement to import static members from classes and use them without
qualifying the class name
Syntax:
import static package-name. subpackage-name. class-name . staticmember-name;
(or)
import static package-name. subpackage-name. class-name.*;
Example:
public interface Salary_increment
{
public static final double Manager=0.5;
public static final double Clerk=0.25;
}
To access the interface, we can import the interface using the static import statement as
follows:
import static employee. employee_details. Salary_increment;
class Salary_hike
117
{
public static void main( String args[ ])
{
double manager_salary=Manager*Manager_current_salary;
double clerk_salary=Clerk*Clerk_current_salary;
………..
……………
}
}
We can use the static member in the code without qualifying the class name or interface
name.
Also, the static feature eliminates the redundancy of using the qualified class name with the
static member name and increases the readability of the program.
INTRODUCTION
Rarely does a program run successfully as its very first attempt. It is common to make
mistakes while developing as well as typing a program.
A mistake might lead on to an error causing to program to produce unexpected results.
Errors are the wrongs that can make a program go wrong.
An error may produce an incorrect output or may terminate the execution of the program
abruptly or even cause the system to crash.
It is therefore important to detect and manage properly all the possible error conditions in
the program so that the program will not terminate or crash during execution.
TYPES OF ERRORS
Errors are of two types. They are compile time errors and run time errors.
Compile time errors are those which are occurring because of poor understanding
of the language.
Run time errors are those which are occurring in a program when the user inputs
invalid data.
118
The run time errors must be always converted by the JAVA programmer into user
friendly messages by using the concept of exceptional handling.
COMPILE-TIME ERRORS
All syntax errors will be detected and displayed by the Java compiler and therefore these
errors are known as compile-time errors.
Whenever the compiler displays an error, it will not create the .class file.
It is therefore necessary that we fix all the errors before we can successfully compile ad
run the program.
Most of the compile-time errors due too typing mistakes. Typographical errors are
hard to find.
We may have to check the code word by word, or even character by character.
The most common problems are:
Missing semicolons
Missing brackets in classes and methods
Misspelling of identifiers and keywords
Missing double quotes in strings
Use of undeclared variables.
Incompatible types in assignments/initialization
Bad references to objects
Use of = in place of = = operator
RUN-TIME ERRORS
Sometimes, a program may compile successfully creating the .class file but may not run
properly.
Such programs may produce wrong results due to wrong logic or may terminate due to
errors such as stack overflow.
Most common run-time errors are:
119
Dividing an integer by zero
Accessing an element that is out of bounds of an array
Trying to store a value into an array of an incompatible class or
type
Trying to cast an instance of a class to one of its subclasses.
Passing a parameter that is not in a valid range or value for a method.
Trying to illegally change the state of a thread
Attempting to use a negative size for an array
Using a null object reference as a legitimate object reference to access a
method or a variable.
Converting invalid string to a number
Accessing a character that is out of bounds of a string
Example
class Example
{
public static void main(String args[])
{
int d=0;
int a = 42/d;
}
}
When the Java run-time system detects the attempt to divide by zero, it constructs a
new exception object and then throws this exception. This causes the execution of example to
stop, because once an exception has been thrown, it must be caught by an exception handler and
dealt with immediately. In this example, we haven‟t supplied any exception handlers of our own,
so the exception is caught by the default handler provided by the Java run-time system.
EXCEPTIONS
An exception is a condition that is caused by a runtime error in the program.
Exceptional handling is a mechanism of converting system error messages into user friendly
messages.
120
The purpose of exception handling mechanism is to provide a means to detect and report an
“exceptional circumstance” so that appropriate action can be taken.
The mechanism suggests incorporation of a separate error handling code that performs the
following tasks:
121
SecurityException Caused when an applet tries to perform an
action not allowed by the browser‟s
security settings.
Checked exceptions: These exceptions are explicitly handled in the code itself with the
help of try-catch blocks. Checked exceptions are extended from java.lang.Exception class.
Unchecked exceptions: These exceptions are not essentially handled in the program code;
instead the JVM handles such exceptions. Unchecked exceptions are extended from the
java.lang.RuntimeException class.
The basic concept of exception handling are throwing an exception and catching it.
try block
catch block
Exception handler
Statement that handles the exception
Java uses a keyword try to preface of a block of code that is likely to cause an error
condition and “throw” an exception.
A catch block defined by the keyword catch “ catches” the exception “thrown” by
thee try block and handles it appropriately.
The catch block is added immediately after the try block.
122
The following example illustrates the use of simple try and catch statements.
………………..
………………….
try
{
statement; // generates an exception
}
catch (Exception-type e)
{
statement; // processes the exception
}
………………….
………………………
Example
class Example
OUT PUT
{
public static void main(String args[]) Division by zero
{
int a=10; y=1
int b= 5;
int c=5;
int x, y;
try
{
x = a / (b-c)
}
catch( ArithmeticException e)
{
System.out.println(“Division by zero”);
}
y= a / (b+c);
System.out.println(“y=”+y);
}
}
Example
class Multicatch
{
public static void main(String args[])
{
int a[ ] = (5,10);
int b = 5;
try
{
int x = a[2] / b – a[1];
}
catch(ArithmeticException e)
{
124
System.out.println(“Division by zero”);
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(“Array Index error”);
}
catch(ArrayStoreException e)
{
System.out.println(“Wrong data type”);
}
int y = a[1] / a[0];
System.out.println(“y = ” + y);
}
}
Output:
Array Index error
y =2
USING FINALLY STATEMENT
Java supports another statement known as finally statement that can be used to handle an
exception that is not caught by any of the previous statement.
finally block can be used to handle any exception generated within a try block.
It may be added immediately after the try block or after the last catch block shown as
follows.
125
try try
{ {
--- ---
--- ---
} }
finally catch(…. )
{ {
} --- --
}
….
….
finally
{
---
---
}
when a finally block is defined, this is guaranteed to execute, regardless of whether or not an
exception is thrown.
As a result, we can use it to perform certain house-keeping operations such as closing files
and releasing system resources.
Example
class FinallyDemo
Output
{
inside procA
static void proA( )
procA’s finally
{
try
{
System.out.println(“Inside ProcA”);
}
finally
{
System.out.println(“ProA‟s finally”);
}
}
public static void main( String args[] )
{
procA( );
}
}
126
THROWING OUR OWN EXCEPTIONS
There may be when we would like to throw our own exceptions. We can do this by using
the keyword throw as follows:
throw new Throwabl‟e subclass;
Example:
import java.lang.Exception;
class MyException extends Exception
{
MyException (String message)
{
super(message);
}
}
class TestMyException
{
public static void main(String args[])
{
int x=5, y= 1000;
try
{
float z = (float) x / (float) y;
if (z < 0.01)
{
throw new Myexception (“Number is too small”);
}
}
catch ( MyException e)
{
System.out.println(“Caught my exception”);
System.out.println(e.getMessage());
}
finally
127
{
System.out.println(“I am always here”);
}
}
}
Output:
Caught my exception
Number is too small
I am always here
MULTITHREADED PROGRAMMING
INTRODUCTION
A flow of control is known as thread.
If a program contains multiple flow of controls for achieving concurrent execution then
that program is known as multi threaded program.
A program is said to be a multi threaded program if and only if in which there exist „n‟
number of sub-programs there exist a separate flow of control.
All such flow of controls are executing concurrently such flow of controls are known as
threads and such type of applications or programs is called multi threaded programs.
A thread is similar to a program that has a single flow of control. It has a beginning a
body, and an end, and executes commands sequentially.
Switching Switching
128
CREATING THREADS
The run( ) method should be invoked by an object of the concerned thread. This can be
achieved by creating the thread and initiating it with the help of another thread method
called start( ).
A NEW THREAD CAN BE CREATED IN TWO WAYS.
1. By creating a thread class : Define a class that extends thread class and override its run( )
method with the code required by the thread.
2. By converting a class to a thread: Define a class that implements Runnable interface. The
Runnable interface has only one method, run( ) , that is to be defined in the method with
the code to be executed by the thread.
The approach to be used depends on what the class we are creating requires.
If it requires to extend another class, then we have no choice but to implement the Runnable
interface, since Java classes cannot have two superclasses.
EXTENDING THE THREAD CLASS
We can make our class Runnable as a thread by extending the class java.lang.Thread. This
gives us access to all the thread methods directly. It includes the following steps:
1. Declare the class as extending the Thread class.
129
2. Implement the run( ) method that is responsible for executing the sequence of code
that the thread will execute.
3. Create a thread object and call the start( ) method to initiate the thread execution.
To actually create and run on instance of the thread class, we must write the following
MyThread aThread = new MyThread( );
The second line calls the start( ) method causing the thread to move into the runnable state.
130
Then the Java runtime will schedule the thread to run by invoking its run( ) method. Now,
the thread is said to be in the running state.
An example of using the Thread class
Output
From thread A:i=1
From thread A:i=2
From thread B:i=1
From thread B:i=2
From thread A:i=3
Exit from A
From thread B:i=3
Exit from B
131
The main thread dies at the end of its main method. However, before it dies, it creates and
starts all the two threads A and B. Note that the output from the threads are not specially
sequential.
STOPPING AND BLOCKING THE THREAD
Stopping a Thread
Whenever we want to stop a thread from running further, we may do so by calling its stop( )
method, like:
aThread.stop( );
This statement causes the thread to move to the dead state. The stop( ) method may be used
when the premature death of a thread is desired.
Blocking a Thread
A thread can also be temporarily suspended or blocked from entering into the runnable and
subsequently running state by using either of the following thread methods:
sleep( ) // blocked for a specified time
The thread will return to the runnable state when the specified time is elapsed in the case of
sleep( ), the resume( ) method is invoked in the case of suspend( ) and the notify( ) method
is called in the case of wait( ).
LIFE CYCLE OF A THREAD
During the life time of a thread, there are many states it can enters. They include:
1. Newborn state
2. Runnable state
3. Running state
4. Blocked state
5. Dead state(Terminated)
132
Newborn
start
stop
Running Runnable
Dead
Active Thread
stop
Killed thread
Blocked
Idle thread
NEWBORN STATE
When we create a thread object, the thread is born and is said to be in newborn state. The
thread is not yet scheduled for running. At this state, we can do only one of the following
things with it:
Schedule it for running using start( ) method
Kill it using stop( ) method
If scheduled, it moves to the runnable state. If we attemps to use any other method at this
stage, an exception will be thrown.
RUNNABLE STATE
The runnable state means that the thread is ready for execution and is waiting for the
availability of the processor. That is, the thread has joined the queue of threads that are
waiting for execution.
133
If all threads have equal priority, then they are given time slots for execution in round robin
fashion, i.e., first-come, first-serve manner.
This process of assigning time to threads is known as time-slicing.
However, if we want a thread to relinquish control to another thread of equal priority before
its turn comes, we can do so by using the yield( ) method.
Yield
RUNNING STATE
Running means that the processor has given its time to the thread for its execution.
The thread runs until it relinquish control on its own or it is preempted by a higher priority
thread.
A running thread may relinquish its control in one of the following situations.
1 .It has been suspended using suspend( ) method. A suspended thread can be revived by using the
resume( ) method. This approach is useful when we want to suspend a thread for some time due to
certain reason, but do not want to kill it.
. suspend
● ●
resume
2. It has been made to sleep. We can put a thread to sleep for a specified time period using
the method sleep( time) where time is in milliseconds. This means that the thread is out
134
of queue during this time period. The thread re-enters the runnable state as soon as this
time period is elapsed.
Sleep ( t )
● ● After( t)
3.It has been told to wait until some event occurs. This is done using the wait( ) method. The thread
can be scheduled to run again using the notify( ) method.
Wait
notify
● ●
BLOCKED STATE
The thread is said to be blocked when it is prevented from entering into the runnable state
and subsequently the running state.
This happens when the thread is suspended, sleeping, or waiting in order to satisfy certain
requirements. A blocked thread is considered “ not runnable” but not dead and therefore
qualified to run again.
DEAD STATE
Every thread has a life cycle.
A running thread ends its life when it has completed executing its run( ) method.
It is a natural death. However, we can kill it by sending the stop message to it at any state
thus causing premature death to it.
A thread can be killed as soon as it is born, or while it is running, or even when it is in “ not
runnable “ condition.
135
USING THREAD METHODS
Example
class A extends Thread
{
public void run( )
{
for(int i=1; i< 5;i++)
{
if (i == 1 ) yield( );
System.out.println(“\n From Thread A:i=”+i);
}
System.out.println(“Exit from A”);
}
}
class B extends Thread
{
public void run( )
{
for(int j=1 ;j<=5;j++)
{
System.out.println(“\n From Thread B:j=”+j);
if (j==3 )
stop( );
}
System.out.println(“Exit from B”);
}
}
class C extends Thread
{
public void run( )
{
for(int k=1; k<=5;k++)
{
System.out.println(“\t From Thread C:k=”+k);
if (k === 1 )
try
{
sleep(1000);
}
catch( Exception e)
{
}
136
}
System.out.println(“Exit from C”);
}
}
class ThreadMethods
{
public static void main(String[] args)
{
A threadA =new A( );
B threadB =new B( );
C threadC =new C( );
System.out.println(“Start thread A”);
threadA.start( );
System.out.println(“Start thread B”);
threadB.start( );
System.out.println(“Start thread C”);
threadC.start( );
System.out.println(“End of main thread”);
}
}
Output
Start thread A
Start thread B
Start thread C
From Thread B:j=1
From Thread B:j=2
From Thread A:i=1
From Thread A:i=2
End of main thread
From Thread C:k=1
From Thread B:j=3
From Thread A:i=3
From Thread A:i=4
From Thread A:i=5
Exit from A
From Thread C:k=2
From Thread C:k=3
From Thread C:k=4
From Thread C:k=5
Exit from C
137
THREAD EXCEPTIONS
Note that the call to sleep( ) method is enclosed in a try block and followed by a catch block.
This is necessary because the sleep( ) method throws an exception, which should be caught.
If we fail to catch the exception, program will not compile.
Java run system will throw IllegalThreadStateException whenever we attempt to invoke a
method that a thread cannot handle in the given state.
For example, a sleeping thread cannot deal with the resume( ) method because a sleeping
thread cannot receive any instructions. The same is true with the suspend( ) method when it
is used on a blocked ( not runnable ) thread.
Whenever we call a thread method that is likely to throw an exception, we have to supply an
appropriate exception handler to catch it.
THREAD PRIORITY
In Java, each thread is assigned a priority, which affects the order in which it is scheduled
for running.
The threads of the same priority are given equal treatment by the Java scheduler and,
therefore they share the processor on a first-come,first-serve basis. Java permits us to set the
priority of a thread using the setPriority( ) method as follows:
ThreadName.setPriority( int number );
The number is an integer value to which the thread‟s priority is set. The thread class defines
several priority constants:
MIN_PRIORITY = 1
NORM_PRIORITY=5
MAX_PRIORITY = 10
The number may assume one of these constants or any value between 1 and 10. Note that
the default setting is NORM_PRIORITY.
By assigning priorities to threads, we can ensure that they are given the attention they
deserve. Whenever multiple threads are ready for execution, the Java system chooses the
highest priority thread and execute it.
Remember that the highest priority thread always preempts any lower priority threads.
Example
class A extends Thread
{
138
public void run( )
{
System.out.println(“Thread` A Started”);
for(int i=1;i<=3;i++)
System.out.println(“\t From thread A:i=”+i);
System.out.println(“Exit from A”);
}
}
class B extends Thread
{
public void run( )
{
System.out.println(“Thread B Started”);
for(int i=1;i<=3;i++)
System.out.println(“\t From thread B:j=”+j);
System.out.println(“Exit from B”);
}
}
class C extends Thread
{
public void run( )
{
System.out.println(“Thread C Started”);
for(int i=1;i<=3;i++)
System.out.println(“\t From thread C:i=”+i);
System.out.println(“Exit from C”);
}
}
class ThreadPriority
{
public static void main(String args[])
{
A threadA = new A( );
B threadB = new B( );
139
C threadC = new C( );
threadC.setPriority( Thread.MAX_PRIORITY);
threadB.setPriority(threadA.getPriority( )+1);
threadA.setPriority( Thread.MIN_PRIORITY);
System.out.println(“Start thread A”);
threadA.start( );
System.out.println(“Start thread B”);
threadB.start( );
System.out.println(“Start thread C”);
threadC.start( );
System.out.println(“End of main thread”);
}
}
Output
Start thread A
Start thread B
Start thread C
Thread B Started
From thread B:j=1
From thread B:j=2
Thread C Started
From thread C:k=1
From thread C:k=2
From thread C:k=3
Exit from C
End of main thread
From thread B:j=3
Exit from B
Thread A Started
From thread A:i=1
From thread A:i=2
From thread A:i=3
Exit from A
140
SYNCHRONIZATION
In the above examples, we have seen threads that use their own data and methods provided
inside their run( ) method.
What happens when they try to use data and methods outside themselves. On such
occasions, they may compete for the same resources and may lead to serious problems.
For example, one thread may try to send a record from a file while another is still writing to
the same file.
Depending on the situation, we may get strange results. Java enables us to overcome this
problem using a technique known as synchronization.
In case of Java, the keyword synchronized helps to solve such problems by keeping a watch
an such locations. For example, the method that will read information from a file and the
method that will update the same file may be declared as synchronized.
Example
synchronized void update( )
{
---- // code here is synchronized
}
When we declare a method synchronized, Java creates a “monitor” and hands it over to the
thread that calls the method first time.
As long as the thread holds the monitor, no other thread can enter the synchronized section
of code.
A monitor is like a key and the thread that holds the key can only open the lock.
It is also possible to mark a block of code as synchronized as shown below:
synchronized ( lock-object )
{
---- // code here is synchronized
}
Whenever a thread has completed its work by using synchronized method, it will hand over
the monitor to the next thread that is ready to use the same resource.
An interesting situation may occur when two or more threads are waiting to gain control of a
resource.
141
Due to some reason, the condition on which the waiting threads rely on gain control does
not happen.
This result in what is known as deadlock. For example, assume that the thread A must
access method1 before it can release method2, but the threadB cannot release method1 until
it gets hold on method2.
Because these are mutually exclusive conditions, a deadlock occurs. The code below
illustrate this:
ThreadA
synchronized method2( )
{
synchronized method1( )
{
…………………
}
}
ThreadB
synchronized method1( )
{
synchronized method2( )
{
………………………….
}
}
IMPLEMENTING THE RUNNABLE INTERFACE
To create thread using the Runnable interface, we must perform the steps listed below:
1. Declare the class as implementing the Runnable interface.
2. Implement the run( ) method.
3. Create a thread by defining an object that is instantiated from this “runnable” class as
the target of the thread.
4. Call the thread‟s start( ) method to run the thread.
If the direct reference to the thread threadX is not required, then we may use a shortcut as
shown below:
new Thread( new X( ) ).start( );
142
Example
class X implements Runnable
{
public void run( )
{
for(int i=1;i<3;i++)
{
System.out.println(“\t ThreadX:”+ i);
}
System.out.println(“End of thread X”);
}
}
class RunnableTest
{
public static void main(String[] args)
{
X runnable = new X( );
Thread threadX = new Thread( runnable );
threadX.start( );
System.out.println(“End of main thread”);
}
}
Output
End of main Thread
ThreadX:1
ThreadX:2
End of ThreadX
INTER-THREAD COMMUNICATION
Inter-thread communication can be defined as the exchange of messages between two or
more threads.
The transfer of messages takes place before or after the change of state of a thread.
For example, an active thread may notify to another suspended thread just before switching
to the suspend state.
Java implements inter-thread communication with the help of following three methods.
notify(): Resumes the first thread that went into the sleep mode. The object class
declaration of
notify() method is shown below:
143
notifyall(): Resumes all the threads that are in sleep mode. The execution of these threads
happens as per priority. The object class declaration of notifyall() method is shown below:
Wait(): sends the calling thread into the sleep mode. This thread can now be activated only by
notify() or notifyall() methods. The object class declaration of wait() method is shown
below:
All the above methods are declared in the root class, i.e., Object. Since, the methods are
declared as final they cannot be overridden. All the three methods throw
InterruptedException.
One Mark
1. What is the default encoding for an OutputStreamWriter?
e. UTF-8
f. Default encoding of the host platform
g. UTF-12
h. None of the above
2. What is the return type of the hashCode() method in the Object class?
e. Object
f. int
g. long
h. void
++z + y - y + z + x++
e. 24
144
f. 23
g. 20
h. 25
Answer: (d) 25
4. Which
of the following tool is used to generate API documentation in HTML format from
doc comments in source code?
e. javap tool
f. javaw command
g. Javadoc tool
h. javah command
Answer: b
Answer: d
7. Which of this package is used for handling security related issues in a program?
a) java.security
b) java.lang.security
c) java.awt.image
d) java.io.security
View Answer
Answer: a
8. Which of these class allows us to get real time data about private and protected member of a
class?
a) java.io
b) GetInformation
c) ReflectPermission
d) MembersPermission
145
Answer: c
8Which of this package is used for invoking a method remotely?
a) java.rmi
b) java.awt
c) java.util
d) java.applet
Answer: a
9. Which of these functions is called to display the output of an applet?
a) display()
b) paint()
c) displayApplet()
d) PrintApplet()
View Answer
Answer: b
10. Which of these methods can be used to output a string in an applet?
a) display()
b) print()
c) drawString()
d) transient()
Answer: c
Answer: b
12. Which of these modifiers can be used for a variable so that it can be accessed from any
thread or parts of a program?
a) transient
b) volatile
c) global
d) No modifier is needed
View Answer
Answer: b
13. Which of these operators can be used to get run time information about an object?
a) getInfo
b) Info
c) instanceof
d) getinfoof
146
Answer: c
14. When does Exceptions in Java arises in code sequence?
a) Run Time
b) Compilation Time
c) Can Occur Any Time
d) None of the mentioned
Answer: a
Answer: c
16. Which of these keywords must be used to monitor for exceptions?
a) try
b) finally
c) throw
d) catch
Answer: a
17. Which of these keywords must be used to handle the exception thrown by try block in some
rational manner?
a) try
b) finally
c) throw
d) catch
Answer: d
147
c) Process and Thread based
d) None of the mentioned
20. Thread priority in Java is?
a) Integer
b) Float
c) double
d) long
21. What will happen if two thread of the same priority are called to be processed simultaneously?
a) Anyone will be executed first lexographically
b) Both of them will be executed simultaneously
c) None of them will be executed
d) It is dependent on the operating system
22. Which of these statements is incorrect?
a) By multithreading CPU idle time is minimized, and we can take maximum use of it
b) By multitasking CPU idle time is minimized, and we can take maximum use of it
c) Two thread in Java can have the same priority
d) A thread can exist only in two states, running and blocked
23. Which of these functions is called to display the output of an applet?
a) display()
b) paint()
c) displayApplet()
d) PrintApplet()
24. Which of these methods can be used to output a string in an applet?
a) display()
b) print()
c) drawString()
d) transient()
25. Which of these methods is a part of Abstract Window Toolkit (AWT) ?
a) display()
b) paint()
c) drawString()
d) transient()
26. Which of these modifiers can be used for a variable so that it can be accessed from any thread or
parts of a program?
a) transient
b) volatile
c) global
d) No modifier is needed
27. Which of these operators can be used to get run time information about an object?
a) getInfo
b) Info
148
c) instanceof
d) getinfoof
5 Marks
1. How will you extend the thread class?
2. Explain about thread priority.
3. What are the two types of errors? Explain in detail.
4. Explain about Naming convention.
5. Discuss about Types of Errors.
10 Marks
6. Explain in detail about Life cycle of Thread.
7. Describe in detail about inter thread communication.
8. Describe in detail about Exception Handling: Limitations of Error handling.
**************UNIT IV COMPLETED***************
149
UNIT V
INTRODUCTION
A file is a collection of records placed in a particular area on the disk.
A record is composed of several fields is a group of characters.
Characters in java are Unicode characters composed of two bytes, each byte
containing eight binary digits, 1 or 0.
Storing and managing data using files is known as file processing which includes
tasks such as creating files, updating files and manipulation of data.
Java supports many powerful features for managing input and output of data using
files.
The process of reading and writing objects is called object serialization.
CONCEPT OF STREAMS
In file processing, input refers to the flow of data into a program and output means the flow of
data out of a program.
Input to a program may come from the keyboard, the mouse, the memory, the disk, a network,
or another program.
150
Output from a program may go to the screen, the printer, the memory, the disk, or another
program.
The java.io package contains a large number of stream classes that provide capabilities for
processing all types of data.
These classes may be categorized into two groups based on the data type on which they
operate.
1. Byte stream classes that provide support for handling I/O operations on bytes.
2. Character stream classes that provide support for managing I/O operations on characters.
151
Classification of java stream classes
BYTE STREAM CLASSES
Byte stream classes have been designed to provide functional features for creating and
manipulating streams and files for reading and writing bytes.
Since the streams are unidirectional, they can transmit bytes in only one direction.
Java provides two kinds of byte stream classes:
Input stream classes
Output stream classes
Input stream classes
Input stream classes that are used to read 8-bit bytes include a super class known as
Inputstream and a number of subclasses for supporting various input-related functions. The
following figure shows the hierarchy of input stream classes.
The Inputstream class defines methods for performing input functions such as
Reading bytes
Closing streams
Making positions in streams
Skipping ahead in a stream
152
Finding the number of bytes in a stream
The OutputStream includes methods that are designed to perform the following tasks:
Writing bytes
Closing streams
Flushing streams
OuputStream Methods
153
The DataOutputStream, a counterpart of DataInputStream, implements the interface
DataOutput and, therefore, implements the following methods contained in DataOutput
interface.
154
Hierarchy of writer stream classes
APPLET PROGRAMMING
INTRODUCTION
Applets are small java program that are primarily used in internet computing. They
can be transferred over the internet from one computer to another and run using the applet
viewer or any web browser that support the java program.
An applet can perform arithmetic operations, play sounds, display graphics, accept user input
, create animation and play interactive games.
Java applications are generally run from a command-line prompt using JDK. Applets are run
on any browser supporting Java.
For an applet to run it must be included in a web page using HTML pages.
When a browser loads a web page including an applet, the browser downloads the applet from
the web server and runs it on the web owner‟s system.
Java interpreter is not required specifically for doing so it is already built-in the browser.
Local Applet:
An applet which is developed locally and stored in the local system is known as the local
applet When the web page is trying to find the local applet.
155
It does' need to use the internet and therefore the local system does not require the internet
connection. It simply searches the directories in the local system and locates and load the
specified applet.
In order to locate and load the local applet we must know the applet address on the web page.
This address is known as the URL uniform resource locator. and must be specified in the
applet HTML document as the value of the code base attribute.
o Remote Applet:
It is stored on a remote computer which is connected to the net. If connected with the net,
we can download the remote applet onto our system.
We can utilize it via the internet.
URL:
157
java.lang.object
java.awt.component
java.awt.container
java.awt.pannel
java.applet.Applet
APPLET LIFE CYCLE
Every java applet inherit a set a default behavior from the Applet class. As the result applet
is loaded,it undergoes a series of changes in its state as shown in the above figure the applet states
will be
* Born or initialization state
* Running state
* Idle state
* Dead or destroyed state
Dead End
Destroyed
Exit of Browser
Initialization State:
It is achieved by calling init() method of the applet class. We can perform the
functions like
Create objects needed by the applet
Set up initial values
158
Load images or fonts
Setup colors
This method occurs only once
Syntax:
……..(Action)
Running state:
Applet enter the running state when the system calls the start() method of the applet class.
This occurs automatically after the applet is initialized.
Starting can also if the applet is already in the idle stopped state. The start() method may
be called by more than one time.
public void start()
{
………(Action)
}
An applet becomes idle when it is stopped from running. Stopping occurs automatically
when we leave the page containing the currently running applet.
We can also do so by calling the stop() method explicitly. If we use the thread to run the
applet that we must use the stop() method to terminate the thread.
We can achieve by overridding the stop() method.
public void stop()
{
…………….(Action)
}
Dead State
159
An applet is said to be dead when it is removed from the memory. This occurs
automatically by invoking the destroy() method.
When we quit the browser. Like the initialization destroying stage occur only once in
the applet life cycle.
public void destroy()
{
...........(Action)
}
Display State
Applet moves to the display state whenever it has to perform some output operation on
the screen. This happens immediately after the applet enters into the running state.
The paint() method is called to accomplish this task. Almost every applet will have a
paint() method like other method in the life cycle.
public void paint(Graphics g)
{
……….(Display statements)
}
CREATING AN EXECUTABLE APPLET
Let us consider the HelloJava applet created. This applet has been stored in a file called
HelloJava.java. Here are the steps required for compiling the HelloJava applet.
1. Move to the directory containing the source code and type the following command
javac HelloJava.java
2. The compiled o/p file called HelloJava.class is placed in the same directory as the source.
3. If any error message is received ,then we must check for errors correct them and compile
the applet again.
DESIGINING A WEB PAGE
A webpage is basically made up of text and HTML tags. It is also known as HTML page
or document.
A webpage is marked by an opening HTML tag <HTML> and a closing tag</HTML>
It is divided into three major sections.
1. Comment section(optional)
2. Head section(optional)
3. Body section
160
HTML tags format:
<HTML>
<!
……………………………. Comment Section
>
<HEAD>
Title tag Head Section
</HEAD>
<BODY>
Applet tag Body Section
</BODY>
</HTML>
1. Comment Section:
This section contains comments about the web page.
It tells what is going on the web page.
The comment line begins with <! And ends with >
2. Head Section:
This session contains the title for the web page.
Starting<HEAD> and ending with </HEAD>
<HEAD>
<TITLE> WELCOME TO JAVA APPLETS</TITLE>
</HEAD>
3.Body Section:
This section contains the entire information about the web page
<BODY>
<CENTER>
<H1> APPLETS</H1>
<BR>
</CENTER>
161
<APPLET
CODE= “HELLO.CLASS”
WIDTH=300
HEIGHT=200>
</APPLET>
</BODY>
APPLET TAG
The <APPLET…> tag supplies the name of the applet to be loaded and tells the
browser how much space the applet requires.
Example:
<APPLET
CODE=helloJava.class
WIDTH = 400
HEIGHT = 200>
</APPLET>
Note that <APPLET> tag discussed above specifies three things:
1. Name of the applet.
2. Width of the applet.(in pixels)
3. Height of the applet.(in pixels)
162
HEIGHT=200>
</APPLET>
</BODY>
</HTML>
We must name this file as HelloJava.html and save it in the same directory as the compiled applet.
RUNNING THE APPLET
HelloJava.java
HelloJava.class
HelloJava.html
AppletViewer:Hellojava.class
Applet
Hello Java
APPLET TAGS
appletloader.started
<APPLET
[CODEBASE = codebase_URL]
CODE = AppletFileName.class
[ALT = alternate_text]
163
[NAME = applet_instance_name]
WIDTH = pixels
HEIGHT = pixels
[ALIGN = alignment]
[VSPACE = pixels]
[HSPACE = pixels]
>
……….
</APPLET>
Attribute Meaning
CODE = Specifies the name of the applet to be laoded.
AppletFileName.class
CODEBASE = codebase_URL Specifies the URL of the directory in which the applet resides.
WIDTH = pixels These attributes specify the width and height of the space on
HEIGHT = pixels the HTML page that will be reserved for the applet.
NAME = A name for the applet may optionally be specified.
applet_instance_name
ALIGN = alignment This optional attribute specifies where on the page the applet
will appear. Possible values for alignment are:TOP, BOTTOM,
LEFT, RIGHT, MIDDLE ETC.
HSPACE = pixels This attribute specifies the amount of horizontal blank space
the browser should leave surrounding the applet.
164
VSPACE = pixels This attribute specifies the amount of vertical blank space the
browser should leave surrounding the applet.
ALT = alternate_text Non-java browsers will display this text where the applet would
normally go. This attribute is optional.
PASSING PARAMETERS TO APPLETS
import java.awt.*;
import java.applet.*;
String str;
str= getParameter(“string”);
if (str == null)
str = “Java”;
165
str = “Hello” + str;
<HTML>
<HEAD>
</HEAD>
<BODY>
WIDTH = 400
VALUE = “Applet!”>
</APPLET>
</BODY>
</HTML>
Save this file as HelloJavaParam.html and then run the applet using the applet viewer as
follows:
166
Appletviewer HelloJavaParam.html
AppletViewer:HelloJavaParam.class
Applet
Hello Applet!
APPLET TAGS
appletloader.started
Now, remove the <PARAM> tag from the HTML file and then run the applet again. The
result will be as shown below
AppletViewer:HelloJavaParam.class
Applet
Hello Java
APPLET TAGS
appletloader.started
We can align the output of the applet using the ALIGN attribute. This attribute can have
one of the nine values:
For example ALGN = LEFT will display the output at the left margin of the page.
Example:
<HTML>
<HEAD>
</HEAD>
167
<BODY>
WIDTH = 400
HEIGHT = 200
</APPLET>
</BODY>
</HTML>
Tag Function
<HTML> … Indicates starting & ending of a HTML file
</HTML>
168
<H1> … </H1> It contains the heading tag, where 1 to 7 are its
size
…..
H1 Largest Font
<H7> …… </H7>
H7 Smallest Font
<A… > …. </A> Indicates the Anchor tag (i.e) Hyper reference
169
In applets, we can display numerical values by first converting them into strings and
then using the drawstring() method of Graphics class.
We can do this easily by calling the ValueOf() method of String class.
import java.awt.*;
import java.applet.*;
public class NumValues extends Applet
{
public void paint (Graphics g)
{
int value1 = 10;
int value2= 20;
int sum = value1 + value2;
String s = “sum:” + String.valueOf(sum);
g.drawString(s, 100, 100);
}
}
<html>
<applet
Code = Numvalues.class
Width = 300
Height = 300 >
</applet>
</html>
Output:
AppletViewer:Numvalues.class
Applet
Sum: 30
170
Once text fields are created for receiving input, we can type the
values in the fields and edit them.
Next step is to retrieve the items from the fields
Example:
import java.awt.*;
import java.applet.*;
public class UserIn extends Applet;
{
TextField text1,text2;
public void init()
{
text1=new TextField(8);
text2=new TextField(8);
add(text1);
add(text2);
text1.settext(“0”);
text2.settext(“0”);
}
public void paint (Graphics g)
{
int x=0,y=0,z=0;
String s1,s2,s;
g.drawstring :Input a number in each box”,10,50);
try
{
s1=text1.gettext();
x=integer,parseINT(S1);
s2=text2.getText();
y=Integer.parseint(s2);
}
171
catch (Exception ex){ }
z=x+y;
s=String.valueof(z);
g.drawstring(“The sum is”, 10,75);
g.drawstring(s, 100,75);
}
public Boolean action (Event event, object object)
{
repaint();
return true;
}
}
Run the applet UserIn using the following steps:
1.Type and save the program(.java file)
2.Compile the applet(.class file)
code =userIn.class
width = 300
height = 200>
</applet>
</html> Applet Viewer:UserIn.class
4.Use the appletviewer to display the result. Applet
123 215
172
INTRODUCTION
One of the most important features of Java is its ability to draw graphics.
We can write java applets that draw lines, figures of different shapes, images, and text in different
fonts and styles.
We can also incorporate different colours in display.
Every applet has its own area of the screen known as canvas, where it creates its display.
A Java applet draws graphical image inside its space using the coordinate system.
Java‟s coordinate system has the origin(0,0) in the upper-left corner.
Positive x values are to the right, and positive y values are to the bottom.
The values of coordinates x and y are in pixels.
THE GRAPHICS CLASS
Java‟s graphics class includes methods for drawing many different types of shapes.
To draw a shape on the screen , we may call one of the methods available in the Graphics class.
The following are the most commonly used methods in Graphics class.
Drawing methods of the graphics class
Method Description
clearRect( ) Erases a rectangular area of the canvas.
copyArea( ) Copies a rectangular area of the canvas to another area.
drawArc( ) Draws a hollow arc.
drawLine( ) Draws a straight line.
drawOval( ) Draws a hollow oval.
drawPolygon( ) Draws a hollow polygon.
drawRect( ) Draws a hollow rectangle.
drawRoundRect( ) Draws a hollow rectangle with rounded corners.
drawstring( ) Displays a text string.
fillArc( ) Draws a filled arc.
fillOval( ) Draws a filled oval.
fillPolygon( ) Draws a filled polygon
fillRect( ) Draws a filled rectangle.
frillRoundRect( ) Draws a filled rectangle with rounded corners.
getcolor( ) Retrieves the current drawing colour.
173
getFont( ) Retrieves the currently used font.
getFontMetrics( ) Retrieves information about the current font.
setColor( ) Sets the drawing colour.
setFont( ) Sets the font.
Example:
<html>
<body>
<applet code=graphics_methods.class width = 200 height=200>
</applet>
</body>
</html>
import java.awt.*;
import java.applet.*;
public class graphics_methods extends Applet
{
public void paint(Graphics GA)
{
GA.drawRect(160,5,60,60);
GA.drawLine(380,100,200,180);
GAdrawOval(10,120,155,95);
}
}
AppletViewer graphics_methods.class
Applet
174
The simplest shape we can draw with Graphics class is a line.
175
The drawline() method takes two pair of coordinates (x1,y1) and (x2,y2).
Ex:
g.drawLine(10,10,50,50);
Ex:
g.drawRect(10,60,40,30)
Ex:
g.fillRect(60,10,30,80)
Example:
import java.awt.*;
import java.Applet.*;
g.drawLine(10,10,50,50);
g.drawRect(10,60,40,30);
<Applet
Code = LineRect.class
176
Width = 250
Height = 200>
</Applet>
AppletViewer:Linerect.class
Applet
appletloader.started
Height
Width
Ex:
import java.awt.*;
import java.applet.*;
</Applet>*/
177
public class cir extends Applet
{
public void paint(Graphics g)
{
g.drawOval(20,20,200,120);
g.setColor(color.Green);
g.fillOval(70,30,100,100);
}
AppletViewer:oval.class
Applet
DRAWING ARCS
appletloader.started
DRAWING ARCS
import java.awt.*;
import java.applet.*;
178
g.fillOval(68, 81, 10, 10);
g.fillOval(121, 81, 10, 10);
g.drawOval(85, 100, 30, 30);
g.fillArc(60, 125, 80, 40, 180, 180);
g.drawOval(25, 92, 15, 30);
g.drawOval(160, 92, 15, 30);
}
}
DRAWING POLYGONS
179
Ex:
import java.awt.*;
import java.applet.*;
import java.awt.*;
import java.applet.*;
public class TableGraph extends Applet
{
Example:
import java.awt.*;
import java.applet.*;
public class ControlLoop extends Applet
{
public void paint(Graphics g)
{
for (int i=0;i<=4;i++)
{
if(i%2)==0
g.drawOval(120, i*60+10, 50, 50);
181
else
g.fillOval(120, 1*60+10, 50, 50);
}
}
} AppletViewer.controlLo
op.class
Applet
Applets can be designed to display bar charts, which are commonly used in
comparative analysis of data.
The table below shows the annual turnover of a company during the period 1991
– 1994.
These values may be placed in a HTML file as PARAM attributes and then used
in applet for displaying a bar chart.
181
public void init()
{
try
{
n=integer.parsInt (getParameter(“columns”));
label=new String[n];
value = new int [n];
label[0]=getParameter (“label1”);
label[1]=getParameter (“label2”);
label[2]=getParameter (“label3);
label[3]=getParameter (“label4”);
value [0] =Integer.parseInt (getParameter (“c1”));
value [1] =Integer.parseInt (getParameter (“c2”));
value [2] =Integer.parseInt (getParameter (“c3”));
value [3] =Integer.parseInt (getParameter (“c4”));
}
catch (NumberFormatException e)
{
}
}
public void paint (Graphics g)
{
for ( int i=0;i<n;i++)
{
g.setcolor(color.red);
g.drawstring(label [i],20,i*50+30);
g.fillRect(50,i*50+10, value [i],40);
}
}
}
<html>
<applet
Code = BarChart.class
Width = 300
Height = 250>
<PARAM NAME = “columns” VALUE = “4”>
<PARAM NAME = “c1” VALUE =”110”>
<PARAM NAME = “c2” VALUE =”150”>
<PARAM NAME = “c3” VALUE =”100”>
<PARAM NAME = “c4” VALUE =”170”>
<PARAM NAME = “label1” VALUE =”91”>
<PARAM NAME = “label2” VALUE =”92”>
<PARAM NAME = “label3” VALUE =”93”>
<PARAM NAME = “label4” VALUE =”94”>
182
</applet>
</html>
AppletViewer.BarChart.class
Applet
91
92
93
94
appletloader.started
EVENT HANDLING
Action Event is triggered whenever a user interface element is activated, such as selection
of a menu item.
Item Event is triggered at the selection or deselection of an itemized or list element, such as
check box.
TextEvent is triggered when a text field is modified.
WindowEvent is triggered whenever a window-related operation is performed, such as
closing or activating a window.
KeyEvent is triggered whenever a key is pressed on the keyboard.
Event Sources
The registration of a listener object with an event ensures that on occurrence of
the event, the corresponding listener object is notified for taking appropriate
action.
Following is the syntax for registering a listener for an event.
The event listener object contains methods for receiving and processing event
notifications sent by the source object.
These methods are implemented from the corresponding listener interface
contained in the java.awt.event package.
Event Classes
All the events in java corresponding event classes associated with them.
Each of these classes is derived from one single super class, i.e.,
EventObject.
It is contained in the java.util.package.
The EventObject class contains the following two important methods for
handling events:
getSource(): Returns the event source.
toString(): Returns a string containing information about the event
source.
Action Event is triggered whenever a user interface element is activated, such as selection
of a menu item.
Item Event is triggered at the selection or deselection of an itemized or list element, such as
check box.
TextEvent is triggered when a text field is modified.
WindowEvent is triggered whenever a window-related operation is performed, such as
closing or activating a window.
KeyEvent is triggered whenever a key is pressed on the keyboard.
Event Sources
The registration of a listener object with an event ensures that on occurrence of
the event, the corresponding listener object is notified for taking appropriate
action.
Following is the syntax for registering a listener for an event.
Event Listeners
The event listener object contains methods for receiving and processing event
notifications sent by the source object.
These methods are implemented from the corresponding listener interface
contained in the java.awt.event package.
Event Classes
All the events in java corresponding event classes associated with them.
184
Each of these classes is derived from one single super class, i.e.,
EventObject.
It is contained in the java.util.package.
The EventObject class contains the following two important methods for
handling events:
getSource(): Returns the event source.
toString(): Returns a string containing information about the event
source.
The java.awt.event package provides many event classes and Listener interfaces for event handling.
ActionEvent ActionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
185
FocusEvent FocusListener
What is an Event?
Change in the state of an object is known as event i.e. event describes the change in state of
source. Events are generated as result of user interaction with the graphical user interface components.
For example, clicking on a button, moving the mouse, entering a character through keyboard,selecting
an item from list, scrolling the page are the activities that causes an event to happen.
Types of Event
Foreground Events - Those events which require the direct interaction of user.They are
generated as consequences of a person interacting with the graphical components in Graphical
User Interface. For example, clicking on a button, moving the mouse, entering a character
through keyboard,selecting an item from list, scrolling the page etc.
Background Events - Those events that require the interaction of end user are known as
background events. Operating system interrupts, hardware or software failure, timer expires,
an operation completion are the example of background events.
Registration Methods
186
For registering the component with the Listener, many classes provide the registration methods. For
example:
o Button
o public void addActionListener(ActionListener a){}
o MenuItem
o public void addActionListener(ActionListener a){}
o TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
o TextArea
o public void addTextListener(TextListener a){}
o Checkbox
o public void addItemListener(ItemListener a){}
o Choice
o public void addItemListener(ItemListener a){}
o List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}
Layout Manager
The layout manager automatically positions all the components within the container. If we do not
use layout manager then also the components are positioned by the default layout manager. It is
possible to layout the controls by hand but it becomes very difficult because of the following two
reasons.
Java provide us with various layout manager to position the controls. The properties like
size,shape and arrangement varies from one layout manager to other layout manager. When the size
of the applet or the application window changes the size, shape and arrangement of the components
also changes in response i.e. the layout managers adapt to the dimensions of appletviewer or the
application window.
187
The layout manager is associated with every Container object. Each layout manager is an object of
the class that implements the LayoutManager interface.
1 LayoutManager
2 LayoutManager2
Following is the list of commonly used controls while designed GUI using AWT.
1 BorderLayout
The borderlayout arranges the components to fit in the five regions: east, west, north, south
and center.
2 CardLayout
The CardLayout object treats each component in the container as a card. Only one card is
visible at a time.
188
3 FlowLayout
The FlowLayout is the default layout.It layouts the components in a directional flow.
4 GridLayout
5 GridBagLayout
This is the most flexible layout manager class.The object of GridBagLayout aligns the
component vertically,horizontally or along their baseline without requiring the
components of same size.
MENUS
As we know that every top-level window has a menu bar associated with it. This menu bar consist of
various menu choices available to the end user. Further each choice contains list of options which is
called drop down menus. Menu and MenuItem controls are subclass of MenuComponent class.
Menu Hiearchy
Menu Controls
1 MenuComponent
2 MenuBar
189
3 MenuItem
The items in the menu must belong to the MenuItem or any of its subclass.
4 Menu
The Menu object is a pull-down menu component which is displayed from the menu
bar.
5 CheckboxMenuItem
6 PopupMenu
ONE MARK
1. Which of these stream contains the classes which can work on character stream?
a) InputStream
b) OutputStream
c) Character Stream
190
d) All of the mentioned
Answer: c
2. Which of these class is used to read characters in a file?
a) FileReader
b) FileWriter
c) FileInputStream
d) InputStreamReader
Answer: a
3. Which of these method of FileReader class is used to read characters from a file?
a) read()
b) scanf()
c) get()
d) getInteger()
Answer: a
Explanation: None.
4. Which of these class can be used to implement the input stream that uses a character array
as the source?
a) BufferedReader
b) FileReader
c) CharArrayReader
d) FileArrayReader
Answer: c
5. Which of these classes can return more than one character to be returned to input stream?
a) BufferedReader
b) Bufferedwriter
c) PushbachReader
d) CharArrayReader
Answer: c
6. What will be the output of the following Java program?
1. import java.io.*;
2. class Chararrayinput
3. {
4. public static void main(String[] args)
5. {
6. String obj = "abcdef";
7. int length = obj.length();
8. char c[] = new char[length];
9. obj.getChars(0,length,c,0);
10. CharArrayReader input1 = new CharArrayReader(c);
11. CharArrayReader input2 = new CharArrayReader(c, 0, 3);
12. int i;
13. try
14. {
15. while ((i = input1.read()) != -1)
16. {
191
17. System.out.print((char)i);
18. }
19. }
20. catch (IOException e)
21. {
22. // TODO Auto-generated catch block
23. e.printStackTrace();
24. }
25. }
26. }
a) abc
b) abcd
c) abcde
d) abcdef
Answer: d
Explanation: None.
Output:
$ javac Chararrayinput.java
$ java Chararrayinput
abcdef
7. What will be the output of the following Java program?
1. import java.io.*;
2. class Chararrayinput
3. {
4. public static void main(String[] args)
5. {
6. String obj = "abcdef";
7. int length = obj.length();
8. char c[] = new char[length];
9. obj.getChars(0, length, c, 0);
10. CharArrayReader input1 = new CharArrayReader(c);
11. CharArrayReader input2 = new CharArrayReader(c, 0, 3);
12. int i;
13. try
14. {
15. while ((i = input2.read()) != -1)
16. {
17. System.out.print((char)i);
18. }
19. }
20. catch (IOException e)
21. {
22. // TODO Auto-generated catch block
23. e.printStackTrace();
24. }
192
25. }
26. }
a) abc
b) abcd
c) abcde
d) abcdef
Answer: a
Explanation: None.
Output:
$ javac Chararrayinput.java
$ java Chararrayinput
abc
8. What will be the output of the following Java program?
1. import java.io.*;
2. class Chararrayinput
3. {
4. public static void main(String[] args)
5. {
6. String obj = "abcdefgh";
7. int length = obj.length();
8. char c[] = new char[length];
9. obj.getChars(0, length, c, 0);
10. CharArrayReader input1 = new CharArrayReader(c);
11. CharArrayReader input2 = new CharArrayReader(c, 1, 4);
12. int i;
13. int j;
14. try
15. {
16. while ((i = input1.read()) == (j = input2.read()))
17. {
18. System.out.print((char)i);
19. }
20. }
21. catch (IOException e)
22. {
23. // TODO Auto-generated catch block
24. e.printStackTrace();
25. }
26. }
27. }
a) abc
b) abcd
c) abcde
d) none of the mentioned
Answer: d
193
9. Which of these functions is called to display the output of an applet?
a) display()
b) paint()
c) displayApplet()
d) PrintApplet()
Answer: b
10. Which of these methods can be used to output a string in an applet?
a) display()
b) print()
c) drawString()
d) transient()
Answer: c
11. Which of these methods is a part of Abstract Window Toolkit (AWT) ?
a) display()
b) paint()
c) drawString()
d) transient()
Answer: b
12. Which of these modifiers can be used for a variable so that it can be accessed from any
thread or parts of a program?
a) transient
b) volatile
c) global
d) No modifier is needed
Answer: b
13. Which of these operators can be used to get run time information about an object?
a) getInfo
b) Info
c) instanceof
d) getinfoof
Answer: c
13. What is the Message is displayed in the applet made by the following Java program?
1. import java.awt.*;
2. import java.applet.*;
3. public class myapplet extends Applet
4. {
5. public void paint(Graphics g)
6. {
7. g.drawString("A Simple Applet", 20, 20);
8. }
9. }
a) A Simple Applet
b) A Simple Applet 20 20
c) Compilation Error
d) Runtime Error
194
Answer: a
Output:
A Simple Applet
(Output comes in a new java application)
14. What is the length of the application box made by the following Java program?
1. import java.awt.*;
2. import java.applet.*;
3. public class myapplet extends Applet
4. {
5. public void paint(Graphics g)
6. {
7. g.drawString("A Simple Applet", 20, 20);
8. }
9. }
a) 20
b) 50
c) 100
d) System dependent
Answer: a
15. What is the length of the application box made the following Java program?
1. import java.awt.*;
2. import java.applet.*;
3. public class myapplet extends Applet
4. {
5. Graphic g;
6. g.drawString("A Simple Applet", 20, 20);
7. }
a) 20
b) Default value
c) Compilation Error
d) Runtime Error
Answer: c
16. What will be the output of the following Java program?
1. import java.io.*;
2. class Chararrayinput
3. {
4. public static void main(String[] args)
5. {
6. String obj = "abcdefgh";
7. int length = obj.length();
8. char c[] = new char[length];
9. obj.getChars(0, length, c, 0);
10. CharArrayReader input1 = new CharArrayReader(c);
11. CharArrayReader input2 = new CharArrayReader(c, 1, 4);
195
12. int i;
13. int j;
14. try
15. {
16. while((i = input1.read()) == (j = input2.read()))
17. {
18. System.out.print((char)i);
19. }
20. }
21. catch (IOException e)
22. {
23. e.printStackTrace();
24. }
25. }
26. }
a) abc
b) abcd
c) abcde
d) none of the mentioned
Answer: d
17. Which of these package is used for text formatting in Java programming language?
a) java.text
b) java.awt
c) java.awt.text
d) java.io
Answer: a
18. Which of this class can be used to format dates and times?
a) Date
b) SimpleDate
c) DateFormat
d) textFormat
Answer: c
19. Which of these method returns an instance of DateFormat that can format time
information?
a) getTime()
b) getTimeInstance()
c) getTimeDateinstance()
d) getDateFormatinstance()
Answer: b
20. Which of these class allows us to define our own formatting pattern for dates and time?
a) DefinedDateFormat
b) SimpleDateFormat
c) ComplexDateFormat
d) UsersDateFormat
Answer: b
196
21. Which of these formatting strings of SimpleDateFormat class is used to print AM or PM in
time?
a) a
b) b
c) c
d) d
Answer: a
22. Which of these formatting strings of SimpleDateFormat class is used to print week of the
year?
a) w
b) W
c) s
d) S
Answer: a
23. What will be the output of the following Java program?
1. import java.text.*;
2. import java.util.*;
3. class Date_formatting
4. {
5. public static void main(String args[])
6. {
7. Date date = new Date();
8. SimpleDateFormat sdf;
9. sdf = new SimpleDateFormat("mm:hh:ss");
10. System.out.print(sdf.format(date));
11. }
12. }
Note : The program is executed at 3 hour 55 minutes and 4 sec (24 hours time).
a) 3:55:4
b) 3.55.4
c) 55:03:04
d) 03:55:04
Answer: c
Output:
$ javac Date_formatting.java
$ java Date_formatting
55:03:04
24. What will be the output of the following Java program?
1. import java.text.*;
2. import java.util.*;
3. class Date_formatting
4. {
5. public static void main(String args[])
197
6. {
7. Date date = new Date();
8. SimpleDateFormat sdf;
9. sdf = new SimpleDateFormat("hh:mm:ss");
10. System.out.print(sdf.format(date));
11. }
12. }
Note : The program is executed at 3 hour 55 minutes and 4 sec (24 hours time).
a) 3:55:4
b) 3.55.4
c) 55:03:04
d) 03:55:04
Answer: d
Output:
$ javac Date_formatting.java
$ java Date_formatting
03:55:04
25. What will be the output of the following Java program?
1. import java.text.*;
2. import java.util.*;
3. class Date_formatting
4. {
5. public static void main(String args[])
6. {
7. Date date = new Date();
8. SimpleDateFormat sdf;
9. sdf = new SimpleDateFormat("E MMM dd yyyy");
10. System.out.print(sdf.format(date));
11. }
12. }
Note: The program is executed at 3 hour 55 minutes and 4 sec on Monday, 15 July(24 hours
time).
a) Mon Jul 15 2013
b) Jul 15 2013
c) 55:03:04 Mon Jul 15 2013
d) 03:55:04 Jul 15 2013
Answer: a
Output:
$ javac Date_formatting.java
$ java Date_formatting
Mon Jul 15 2013
26. What will be the output of the following Java program?
1. import java.text.*;
198
2. import java.util.*;
3. class Date_formatting
4. {
5. public static void main(String args[])
6. {
7. Date date = new Date();
8. SimpleDateFormat sdf;
9. sdf = new SimpleDateFormat("z");
10. System.out.print(sdf.format(date));
11. }
12. }
Note : The program is executed at 3 hour 55 minutes and 4 sec on Monday, 15 July(24 hours
time).
a) z b) Jul c) Mond) PDT
Answer: d
5 Marks
1. How will you draw lines and rectangles using graphics class method?
2. Explain about control loops in applets.
3. Write short notes on stream classes.
4. Explain about types of byte stream classes.
5. Describe about reader and writer stream classes.
6. What are the uses of file class?
7. Write in detail about label and textboxes
10 Marks
8. Explain in detail about random access files.
9. Write short notes on Applet tags in file.
10.Write any two methods of graphics class
************UNIT V COMPLETED**********
199