Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Ii Bca Java

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

DON BOSCO ARTS & SCIENCE COLLEGE

DEPARTMENT OF COMPUTER SCIENCE

Title of the Subject CORE - III: Programming in Java


Paper Code 21UCA05
Year & Class II BCA
Batch 2023-2024
Semester EVEN - IV

1
QUESTION PAPER PATTERN
TIME:3 Hours Max.Marks:75

PART – A (15*1=15 MARKS)


Answer all the questions

Three questions from each unit (Multiple Choice Questions)

PART – B (2*5=10 MARKS)


Answer any two questions

One question from each unit

PART – C (5*10=50 MARKS)


Answer all the questions

One question from each unit (Either or Type)

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:

 Study all the Basic Statements in java Programming.


 Practice the usage of branching and looping statements.
 Apply Packages and Interfaces.
 Analysis the use of graphics tools in JAVA.

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:

1. To understand the concepts of Object Oriented Programming.


2. To learn about the control structures , class with attributes and methods used in java.

5
UNIT-I

Fundamental of Object-Oriented Programming


 One Characteristic that is constant in software industry today is the “change”.
 Change is one of the most critical aspects of software development and management.
 Most important among them are main ability, reusability, security, portability, security, and
integrity and user friendliness of software products.
 The advent of languages such as “C” structured programming becomes very popular and was
the paradigm of the 1980‟s.
 Structured programming proved to be a powerful tool that enabled programmer to write
moderately complex program fairly easily.
 Even the structured approach failed to show the desired results in terms bug-free, easy – to
maintain and reusable programs.
 Object oriented programming is an approach to program organization and development,
which attempts to eliminate some of the pitfalls of conventional programming methods by
incorporating the best of structured programming features with several new concepts.
 All language are suitable to implement the oops concept easily.
 Language that support OOPS features include small talk, objective C,C++, Ada and object
Pascal..
 C++ an extension of c language is most popular OOP language today
 Java a pure Object-oriented language is one of the recent language added to this list, the latest
one being c#.

Object-Oriented Paradigm Programming Languages


 The major objective of object-oriented approach is the eliminate some of the flaws
encountered in the procedure approach.
 OOPS treats data as critical elements in the program development and does not allow it to
flow free around the system.

 OOPs allow us to decompose a problem into number of entries called objects.


 The data of an object can be accessed only by the methods associated with that object.
 Emphasis is on data rather that procedure.
 Programs are divided into what are know as object

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.

Basic concepts of object-oriented programming


 As mentioned earlier object-oriented is a term which is interpreted differently people.
 It therefore necessary to understand some of the concepts used extensively in object-
oriented programming.

Object and Classes:


 Object is the basic run time entities are an object-oriented system.
 They may represent a person, place, a bank account, a table of data or any item that the
program my handle.
 Java is an object-oriented programming language.
 Everything in Java is associated with classes and objects, along with its attributes and
methods. For example: in real life, a car is an object. The car has attributes, such as weight
and color, and methods, such as drive and brake.
 A Class is like an object constructor, or a "blueprint" for creating objects.

Data Abstraction & Encapsulation

 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.

Terms used in Inheritance


o Class: A class is a group of objects which have common properties. It is a template or
blueprint from which objects are created.
o Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a
derived class, extended class, or child class.
o Super Class/Parent Class: Super class is the class from where a subclass inherits the
features. It is also called a base class or a parent class.
o Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse
the fields and methods of the existing class when you create a new class. You can use the
same fields and methods already defined in the previous class

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

S.no. On the Procedural Programming Object-oriented


basis of programming

1. Definition It is a programming language that is Object-oriented programming


derived from structure programming and is a computer programming
based upon the concept of calling design philosophy or
procedures. It follows a step-by-step methodology that organizes/
approach in order to break down a task models software design around
into a set of variables and routines via a data or objects rather than
sequence of instructions. functions and logic.

2. Security It is less secure than OOPs. Data hiding is possible in


object-oriented programming
due to abstraction. So, it is more
secure than procedural
programming.

3. Approach It follows a top-down approach. It follows a bottom-up


approach.

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.

5. Orientation It is structure/procedure-oriented. It is object-oriented.

6. Access There are no access modifiers in The access modifiers in OOP


modifiers procedural programming. are named as private, public,
and protected.

7. Inheritance Procedural programming does not have There is a feature of inheritance


the concept of inheritance. in object-oriented
programming.

8. Code There is no code reusability present in It offers code reusability by


reusability procedural programming. using the feature of inheritance.

9. Overloading Overloading is not possible in procedural In OOP, there is a concept of


programming. function overloading and
operator overloading.

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.

12. Complex It is not appropriate for complex It is appropriate for complex


problems problems. problems.

13. Data hiding There is not any proper way for data There is a possibility of data
hiding. hiding.

14. Program In Procedural programming, a program is In OOP, a program is divided


division divided into small programs that are into small parts that are referred
referred to as functions. to as objects.

15. Examples Examples of Procedural programming The examples of object-


include C, Fortran, Pascal, and VB. oriented programming are -
.NET, C#, Python, Java,
VB.NET, and C++.
Benefits of Object Oriented Programming:
 Inheritance we can eliminate redundant code and extend the use of existing classes.
 We can build programs from the standard working modules.
 The principle of data hiding helps the programmer to build secure programs.
 It is possible to have multiple objects to coexist without any inheritance.
 It is possible to map objects in the problem domain to those objects in the programs
 It is easy to partition the work in a project based on objects.
 Object oriented system can be easily upgraded from small to large system.
 Message passing techniques for communication.
 Software complexity can be easily managed.

Application of Object Oriented Programming.


 Real business system are often much more complex and contain many object complicated
attributes and methods.
o Real time system.
o Simulation and modeling.
o Object-oriented databases.
o Hypertext hyper media and expertext.
o AI and experts system.
o Neural Network and parallel programming
o Decision support and office automation systems.
o CM/CAD/CAD system.

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

1. Compiled and interpreted. 6. Platform - independent and portable.


2. Object oriented 7. Robust and secure
3. Distributed 8. Familiar, simple and small
4. Multithreaded and Interactive 9. High performance
12
5. Dynamic and Extensible
Compiled and interpreted
 Java is a two-stage system that is both complied and interpreted language.
 First java compiler translates source code into byte code instructions.
 The byte codes are not machine instructions.
 Second stage java interpreter generates machine code that can be directly executed by the
machine that running the java program.
Platform Independent and Portable
 The most significant contribution of java over other language is its portability.
 Java programs can be easily moved from one computer system to another, anywhere and
anytime.
 Changes and Upgrades in operating systems, processors and system resources will not force
any changes in Java programs. This is the reason why java has become a popular language
for programming on Internet, which interconnects different kinds of systems worldwide.
 We can download a java applet from a remote computer on to our local system through
Internet and execute it locally.
 Java ensures portability in two ways. First java compiler generates Byte code instructions that
can be implemented on any machine. Secondly, the sizes of the primitive data types are
machine independent.
Object Oriented:
 Java is truly object-oriented language. Almost everything in Java is an object.
 All program code and data reside within objects and classes.
 Java comes with an extensive set off classes, arranged in packages that we can use in
our programs by inheritance.
 The object model in java is simple and easy to extend.
Robust and Secure:
 Java is a robust language. It provides many safeguards to ensure reliable code. It has strict
compile time and runtime checking for data types.
 It is designed as garbage collected language relieving the programmers virtually all memory
management problems.
 Java also incorporates the concept of exception handling which captures series errors and
eliminates risk of crashing the system.
 The absence of pointers in java ensures that programs cannot gain access to memory locations
13
without proper authorization.
Distributed:
 Java is designed as a distributed language for creating applications on networks. It has the
ability to share both data and programs.
 Java applications can open and access remote objects on internet as easily as they can do in a
local system.
 This enables multiple programmers at multiple remote locations to collaborate and work
together on a single project.
Simple, Small and Familiar:
 Java is a small and simple language. Many features of C and C++ that are either redundant or
sources of unreliable code are not part of java.
 For example java does not use pointers, preprocessor header files, goto statement and
overloading and multiple inheritance and many others.
Multithreaded and Interactive:
 Multithreaded means handling multiple tasks simultaneously. Java supports multithreaded
programs. This means that we need not wait for the application to finish one task before
beginning another.
 For example we can listen to an audio clip while scrolling a page and at the same time
download an applet from a distant computer.
 This feature greatly improves the interactive performance of graphical applications.
High performance
 Java performance is impressive for an interpreted language, mainly due to the use of
intermediate byte code. According to sun, java speed is comparable to the native C/C++.
 Java architecture is also designed to reduce overheads during runtime. Further, the
incorporation of multithreading enhances the overall execution speed of java programs.
Dynamic and Extensible
 Java is a dynamic language.
 It is capable of dynamically linking in new class libraries, methods, and objects.
 Java program support functions written in other languages such as C and C++. These functions
are known as native methods.

Java differs from C and C++


Differences between java and C:
14
 Java does not include the C statement keywords sizeof and typedef.
 Java does not contain data types struct and union.
 Java does not define the type modifiers keywords auto,extern,register,signed and
unsigned.
 Java does not support an explicit pointer type.
 Java does not have a preprocessor and we cannot use # define, # include and # ifdef
statements.
 Java requires that the functions with no arguments must be declared with empty parenthesis
and not with the void keyword as done in C.
 Java adds new operators such as instanceof and >>>.
 Java adds labeled break and continue statements.
Differences between java and C++:

 Java does not support operator overloading.


 Java does not have template classes as in C++.
 Java does not support multiple inheritance of classes. This can be accomplished by a new
feature called as “interface “.
 Java does not support global variables.
 Java does not use pointers.
 Java has replaced the destructor function with a finalize( ) function.
 There are no header files in java.
JAVA AND INTERNET
 Java is strongly associated with the internet because the first application program written in
java was Hot java.
 It is a web browser to run applet on internet.
 Internet users can use java to create applet programs & run them locally using a “java enabled
browser” such as Hot java.
 The ability of java applets to hitch a ride on the information super high way has made java a
unique programming language for the internet.
 Due to this, java is popularly known as internet language.

JAVA DEVELOPMENT ENVIRONMENT

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

Simple java program

class SampleOne
{
public static void main (String args[])
{
System.out.println(“ Java is better than C++”);
}
}

Class declaration

The first line

 Class SampleOne declares a class, java is a true object-oriented language and


therefore, everything must be placed inside a class.
 class is a keyword and declares that a new class definition follows.
 SampleOne is a java identifier that specifies the name of the class to be defined.

17
Opening Brace

 Every class definition in java begins with an opening brace “{“ and ends with a
matching closing brace “}”.

The main line

 The third line

public static void main (String args[])

 The above line defines a method named main.

 This is similar to the main() function in C/C++.

 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.

 The line contains a number of keywords public, static and void.

 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.

The output line

 The only executable statement in the program is

System.out.println(“Java is better than C++”);


 This is similar to printf() statement of C or cout<< construct of C++.

 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.

 This line prints the string “java is better than C++.”


18
An application with two classes

class Room Class RoomArea


{ {
float length; public static void main(String args[])
float breadth; {
void getdata(float a, float b)
float area;
{
Room room1=new Room();
length=a;
room1.getdata(14,10);
breadth=b;
area=room1.length * room1.breadth;
}
System.out.println(“area=” + area);
}
}
}

JAVA PROGRAM STRUCTURE


GENERAL STRUCTURE OF A JAVA PROGRAM

 Suggested
Documentation section
Optional
Package statement

Import statements Optional

Optional
Interface statements
Optional
Class Definitions

Main method Class Essential


{
Main method Definition
}
Documentation section:

 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.

Java implements several types of statements, they are

 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.

Java program Java compiler Virtual machine

SOURCE CODE BYTE CODE

Process of Compilation

 The virtual machine code is not machine specific.


 The machine specific code (machine code) is generated by the java interpreter by acting as a
intermediary between the virtual machine and the real machine.

Byte code Java interpreter Machine code

VIRTUAL MACHINE REAL MACHINE

Process of converting bytecode into machine code

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

Java Virtual Machine

Java Object Framework (API)

Compiler Interpreter

User Application Programs

User

Layers of interactions for Java programs

COMMAND LINE ARGUMENTS


Command line arguments are parameters that are supplied to the application program at the
time of invoking it for execution.
Class ComLineTest
{
Public static void main( String args[ ])
{
int count, i= 0;
String string;
count = args.length;
System.out.println(“ Number of arguments = “ + count);
while (i< count)
{
string = args[i];
i=i+1;
System.out.println( i + “:” + “Java is” + string + “!”);
}
24
}}
Compile and run the program with the command line as follows:
Java ComLineTest Simple Object_Oriented Distributed Robust Secure Portable
Multithreaded Dynamic During the execution, the command line arguments Simple,
Object_Oriented , etc. are passed to the program through the array args. That is the element args[0]
contains Simple,args[1] contains Object_Oriented , and so on. These elements are accessed using
the loop variable I as an index like
name = args[i]
The index i is incremented using a while loop until all the arguments are accessed. The number if
arguments is obtained by statement
count = args.length;

Java Comments
The Java comments are the statements in a program that are not executed by the compiler and
interpreter.

Why do we use comments in a code?

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.

Types of Java Comments


There are three types of comments in Java.

1. Single Line Comment


2. Multi Line Comment
3. Documentation Comment

1) Java Single Line Comment

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

Let's use single line comment in a Java program.

CommentExample1.java

1. public class CommentExample1 {


2. public static void main(String[] args) {
3. int i=10; // i is a variable with value 10
4. System.out.println(i); //printing the variable i
5. }
6. }

Output:

10

2) Java Multi Line Comment

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. }

3) Java Documentation Comment

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

2. Which statement is true about Java?


a) Java is a sequence-dependent programming language
b) Java is a code dependent programming language
c) Java is a platform-dependent programming language
d) Java is a platform-independent programming language

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

4. Which one of the following is not a Java feature?


a) Object-oriented
b) Use of pointers
c) Portable
d) Dynamic and Extensible

Answer: b

5. Which of these cannot be used for a variable name in Java?


a) identifier & keyword
b) identifier
c) keyword
d) none of the mentioned

Answer: c

6. What is the extension of java code files?


a) .js
b) .txt
c) .class
d) .java

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

8. Which of the following is not an OOPS concept in Java?


a) Polymorphism
b) Inheritance
c) Compilation
d) Encapsulation

Answer: c

9. What is not the use of “this” keyword in Java?


a) Referring to the instance variable when a local variable has the same name
b) Passing itself to the method of the same class
c) Passing itself to another method
d) Calling another constructor in constructor chaining

Answer: b

10. What will be the error in the following Java code?


byte b = 50;
b = b * 50;
a) b cannot contain value 50
b) b cannot contain value 100, limited by its range
c) No error in this code
d) * operator has converted b * 50 into int, which can not be converted to byte without casting

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

13. What will be the output of the following Java code?

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

14. What will be the output of the following Java program?

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

14. Which exception is thrown when java is out of memory?


a) MemoryError
b) OutOfMemoryError
c) MemoryOutOfBoundsException
d) MemoryFullException
Answer: b

15 . JDK stands for .

A. Java development kit


B. Java deployment kit
C. JavaScript deployment kit
D. None of these

16. JRE stands for .

A. Java run ecosystem


B. JDK runtime Environment
C. Java Runtime Environment
D. None of these

17. What makes the Java platform independent?

A. Advanced programming language


B. It uses bytecode for execution
C. Class compilation
D. All of these

18. Can we keep a different name for the java class name and java file name?

A. Yes
B. No

19. What are the types of memory allocated in memory in java?

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

21. What is the entry point of a program in Java?

A. main() method
B. The first line of code
C. Last line of code
D. main class

22. Can we write a program without a main method in Java?

A. Yes
B. No

23. Can the main() method be overloaded in Java?

A. Yes
B. No

24. Which keyword in java is used for exception handling?

A. exep
B. excepHand
C. throw
D. All of these

25. Which of the following is a superclass of every class in Java?


a) ArrayList
b) Abstract class
c) Object class
d) String
Answer: c

26. Which of the below is not a Java Profiler?


a) JProfiler
b) Eclipse Profiler
c) JVM
d) JConsole
Answer: c

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

29. Which one of the following is not an access modifier?


a) Protected
b) Void
c) Public
d) Private

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

Numeric Constants Character Constants

Integer constants Real constants Character constants String constants

 Integer Constants

It refers to a sequence of digits. There are 3 types of integers, namely

 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

 An octal integer constant consists of any combination of digits from set 0


through 7, with a leading 0.

Examples

0345
0556

 A sequence of digits preceded by 0x or 0X is considered as hexadecimal integer.


 They include alphabets A through F or a through f.
 A letter A through F represents the numbers 10 through 15. Following are the examples
of valid hexadecimal integers.

34
0X2 0X9F 0xbcd 0x

 Real Constants
 Numbers containing fractional parts are called real or floating point constants. Examples
are

0.087 -0.98 456.78

 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

213. .98 -.71

are all valid real numbers.

 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 exponent is an Integer with an optional plus or minus sign.

 The letter e separating the mantissa and the exponent can be written in either lowercase
or uppercase. Examples of legal floating point constants are

0.65e4 12e-2 1.5e+5


A floating point constant may comprise four parts:

 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:

For example: variablename = value;

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:

type variablename = value;


Examples:
int finalvalue = 123;
char yes = „x‟;
 Read Statement
 We may also give values to variables interactively through the keyword using the readline( )
method.
 The readline( ) method reads the input from the keyboard as a string which is then converted to
the corresponding data type using the data type wrapper classes.
 Getting values of variables
Java supports two output methods that can be used to send the results to the screen.

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.

Data types in Java

Primitive(Intrinsic) Non-Primitive(Derived)

Numeric Non- numeric Classes Arrays

Integer Floating- Character Boolean


Interface
point

 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

 Floating Point Types


 Floating point type contains fractional parts such as 26.78 and -7.890.
 The float type values are single-precision numbers while the double types represent double-
precision numbers.
 Floating point numbers are treated as double-precision quantities. We must append f or F to the
numbers. Example:
1.23f
7.67567e5F
 Double-precision types are used when we need greater precision in storage of floating point numbers.
Floating point data types support a special value known as Not-a-Number (NaN).
 It is used to represent the result of operations such as dividing by zero, where an actual number is not
produced.
Type Size Minimum value Maximum value
Float 4 bytes 3.4e-038 1.7e+0.38
double 8 bytes 3.4e-038 1.7e+308

 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

type variable1 = (type) variable2;


The process of converting one data type to another is called casting. Examples:
int m= 50;
byte n = (byte)m;
Four integer types can be cast to any other type except Boolean. Casting into a smaller type may
result in loss of data. Similarly, the float and double can be cast to any other type except Boolean.
From To
byte short, char, int, long, float, double
short int, long, float, double
char int, long, float, double
int long, float, double
long float, double
float Double
Casts that results in no loss of information

OPERATORS AND EXPRESSIONS

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

Ex: a-b a+b a*b a/b a%b


 Here a and b may be variable or constants. They are also known as operands
 -, +, *, /, % are called operators.
i) Integer arithmetic
 When both the operands in a single arithmetic expression such as a + b are integer,
the expression is called an “integer expression” and the operation is called as
“integer arithmetic”.
 Integer arithmetic always gives an integer value.
E.g.: a=14, b=4
41
a+b=18
a-b=10
a*b=56
a/b=3(decimal part truncated)
a%b=2(reminder of integer division)
 For modulo division, the sign of the result is always the sign of the first
operand.
-14%3 = -2 14 % -3 = 2
ii) Real arithmetic

 An arithmetic operation involving only real operand is called “real arithmetic”.


 A real operand may assume values either in decimal or exponential notation.
Sample program:
import java.io. *;
class floatpoint
{
public static void main(String args[])
{
float a=20.5, b=6.4;
System .out.println("a="+a);
System.out.println("b="+b );
System.out.println("a+b="+( a-b));
System.out.println("a-b="+( a-b ));
System.out.println("a*b="+( a*b));
System.out.println("a/b="+( a/b);
System.out.println("a%b="+( a%b));
}
}

Mixed mode arithmetic

 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

ae-1 relational operator ae-2 == is equal to


!= is not equal to
 Where ae-1 and ae-2 are arithmetic
expressions.
Eg: Expression value
4.5<=10 True
4.5>=10 False

 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

True True True True

True False False True

False True False True

False False False false

 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);

Statement with simple assignment operator Shorthand operator

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

Eg: Z+=Y+1 which is equal to Z=Z+(Y+1)

Advantages:

It has 3 advantages.

 Easy to write.
 Easy to read
 Efficient code.
 INCREMENT AND DECREMENT OPERATORS

 They are also called unary operator.

++  Increment operator, add 1 to the operand

--  Decrement operator, subtract 1 to the operand

 They may also used to increment subscripted variables

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

 Expression1 is evaluated first, if its is true then the expression2 is evaluated.

 If expression 1 is false, expression3 is evaluated.

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

& Bitwise AND

46
! Bitwise OR

^ Bitwise exclusive OR

~ One‟s complement

<< Shift left

>> Shift right

>>> Shift right with zero fill

Eg: 5 = 0000 0101


A=5
>>A // 1000 0010
<<A // 0000 1010
 SPECIAL OPERATORS
 Java supports special operators
 Instance of operator
 Dot operator (or) member selection operator (.)
 Instance of operator:
 Instance of operator is an object reference operator.
 Allow us to determine whether the object belongs to a particular class or not.
 Return true, if the object on the left-hand side is an instance of the class given on the right-
hand side.
E.g. person instanceof student
 Is true if the object person belongs to class student; otherwise it is false.
 Dot operator
 The dot operator (.) is used to access the instance variables and methods of class objects.

Person1.age // reference to the variable age


Person1.salary() // reference to the method salary()
It is also used to access classes and sub packages from a package.
 Arithmetic Expressions
 An arithmetic expression is a combination of variables constants and operators arranged as per the
syntax of the language.

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;

 Precedence of Arithmetic operators:

 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 + -

 Type conversions in Expressions:

Automatic Type conversion:

 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.

Operator Precedence and Associativity:

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

 An arithmetic expression is a combination of variables constants and operators arranged as


per the syntax of the language.
 Java can handled any complex mathematical 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:

 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;

DECISION MAKING AND BRANCHING

 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.

General form Example


if (test expression)
if (category == SPORTS)
{
statement-block; {
}
statement-x; marks = marks + bonus_marks;

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.

General form Example


If (condition-1) If (marks>79)
statement-1; grade=”honors”;
else if (condition-2) else if (marks>79)
statement -2; grade=”first”;
else if (condition-3) else if (marks>79)
statement -3; grade=”second”;
….. else if (marks>79)
….. grade=”third”;
else if (condition n) else
statement -n; grade=”fail”; // Default-stmt
else System.out.println(“grade=”+grade);
default-statement;
The Sw itch Statement

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.

Conditional expression ? Expression1 : expression2;

DECISION MAKING AND LOOPING

INTRODUCTION

 The process of repeatedly executing a block of statement is known as looping.


 The statements in the block may be executed any number of times, from zero to infinite
number.
 If a loop continues forever, it is called an infinite loop.
 A program loop consist of two segments, one known as the body of the loop and other
known as the control statements.
 The control statements test certain conditions and then direct the repeated execution of the
statements contained in the body of the loop.
 A looping process in general consists of following steps:
 Setting and initialization of a counter
 Execution of the statements in the loop
 Test for a specified condition for execution of the loop
 Incrementing the counter

 Java language provides three looping statements for loop operations.


 The while statement
 The do statement
 The for statement

THE WHILE STATEMENT

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.

General form Example


Sum=0;
Initialization; N=1;
while (N<=10)
{
while (test condition) sum=sum + N;
{ N=N+1;
Body of the loop }
} System.out.println(“sum’”+sum);

Here the body of the loop is executed 10 times for


n=1,2..10.

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

 For loop is an entry-controlled loop.


 The execution of the for statement is as follows:

(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
}

Simple example-2 sum = sum + n;

for (n=1; n<=10; n++)


{
Simple example-1

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 }

 for (i=1; i<20 && sum <100; ++i) valid

 for (m=5; m!=100; m=m+5)valid

Nesting of for loops

 A for loop which is present inside of another for loop is called nesting of for loop.

for (i=1;i<=10;i++) for (i=1;i<=10;i++)


{
……………. {
…………….
for (j=1; j<=10; j++)
for (j=1; j ! = 5; ++j)
{…………. {
…………..
} System.out.println(i,j);
…………
}
}
……….. }

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

 Exit from a loop can be accomplished by using the break statement.


 Break can also be used within while, do and for loops.
 When break statement is encountered inside a loop, the loop is immediately exited and the
program continues with the statement immediately following the loop.
 In nested loop, the break would only exit from the loop containing it.
 The break will exit only a single loop.

while(…….) do (……) for(……)


 { {
{  ….. …..
…… ……
…..

……. for(…….)
if (condition) {
if
(condition)
break; ….
break;
…… ….. …..
…..
 ….. if (condition)
} ……… }while (….) break;
 ……..
…….
 …….
}// for second for
 …..
…..
} // for first for
Skipping a part of a loop
 Continue statement skips a part of a loop.
 The continue statement; cause the loop to be continued with the next iteration after skipping
any statement in between.
 The continue statement tells the compiler “skip the following statements and continue
with the next iteration”.
EXAMPLE EXAMPLE
EXAMPLE do(…….) for(…….)
{ {
while (test condition)
…… ……
{
…… if (condition) if (condition)
if (condition) continue; continue;
continue; ……. …….
……. }while(test condition); …….
……. }
} LABELLED LOOPS

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.

Format1: Format 2: A block of statements can


be labeled as shown below:
loop1 : for(…..) block1:
{
{ ……..
……… ………
……… block2:
} {
………
}
……….
……….
}

ARRAY
 An array is a group of contiguous or related data items that share a common name.

 A particular value in an array is indicated by writing a number called index number or


subscript in brackets after the array name

E.g. name[10]
 The individual values are called elements.

ONE- DIMENSIONAL ARRAYS

 A list of items can be given one variable name using only one subscript called single
subscripted variable or one dimensional array.

Eg: int number[]=new int[5];

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.

Creation of an array involves three steps:

 Declaring the array


 Creating memory locations
 Putting values into the memory locations.
Declaration of arrays
Arrays can be declared in two forms

Form1 Form2

type arrayname[]; type[] arrayname;

Creating memory locations

 After declaring an array, we need to create memory.

 Java allows creating arrays using new operator.

arrayname = new type [size];

Eg: number=new int[5];

Combining declaration and creation

 It is also possible to combine the two steps- declaration and creation

 Int number[]=new int[5];

60
Initialization of Arrays

 Putting values into the array is known as initialization.

 This process is done using the array subscript.

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.

Initializing list of values to an array

 Values are separated by commas and surrounded by curly braces.

type arrayname[]={ list of values};

 If size is not specified means compiler allocates enough space for all the elements specified
in the list

Eg: int number[]={23,45,56,67}

Array length

 Access the length of the array using length keyword.

Eg: int assize= a.length();

Eg: int size[][]=new int[3][10];

 Here length of size.length() 3

 Length of size[i].length() 10;

TWO DIMENSIONAL ARRAYS

By using two dimensional arrays we can store table of values.

61
Eg : int myarray[][];

myarray=new int[3][4];

Or int myarray[][]=new int[3][4]

Example program:

class MulTable

final static int ROWS = 0;

final static int columns = 20;

public static void main(String args [ ])

int product [ ] [ ] = new int [ ROWS ] [COLUMNS];

int row, column;

System.out.println(“ MULTIPLICATION TABLE”);

System.out.println(“ “);

int i,j;

for ( i =10; i < ROWS; i++)

62
for ( j =10; j < COLUMNS; j++)

product [i] [ j] = i * j;

System.out.println(“ “ + product [ i] [ j ];

System.out.println(“ “);

VECTORS

 Vector class contain in java.util package.


 Vector class is used to create a generic dynamic array known as vector that can hold objects
of any type and any number.
 It is heterogeneous data not homogenous.
Created like
 Vector intvect=new vector(); // declared without size
 Vector list=new vector(3); // declared with size
Advantages
 It is convenient to use vectors to store objects.
 A vector can be used to store a list of objects that may vary in size.

 We can add and delete objects from the list as and when required.

Methods Task performed

list.addElement(item) Adds the item specified to the list at the end

list.elementAt(10) Gives the name of the 10th object

list.size() Gives the number of objects present.

list.removeElement(item) Removes the specified item from the list.

63
list.removeElementAt(n) Removes the item stored in the nth position
of the list

list.removeAllElements() removes all the elements in the list

list.copy Into(array) copies all items from list to array

list.insertElementAt(item, Inserts the item at nth position


n)

Example program Command line input and output are:


import java.util . *;
class LanguageVector C :\> java Languagevector Ada Basic
{ C++ FORTRAN Java
public static void main(String args[])
Output:
{
Vector list=new Vector(); List of languages
int length=args.length;
for (int i=0; i<length; i++) Ada
{
list.addElement(args[i]); Basic
} COBOL
list.insertElementAt(“COBOL”,2);
int size=list.size(); C++
String listarray[]=new String(size);
List.copyInto(listArray); FORTRAN
System.out.println(“List of languages”);
Java
for (int i=0; i<length; i++)
{
System.out.println(“listArray[i]”);
}
}
}

WRAPPER CLASS

 Vectors cannot handle primitive data types like int, float, double and char.

 Primitive data types converted into object types.

 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

Constructor calling Conversion action

Integer Intval=new Integer(i); Primitive integer to Integer object

Float Floatval=new Float(f); Primitive float to Float object

Double Doubleval=new Double(d); Primitive double to Double object

Long Longval = new Long(l) Primitive long to Long object

Converting object numbers to primitive number using typeValue() method

Method calling Conversion Action

int i= Intval.intValue(); Object to primitive integer

float f = Floatval.floatValue(); Object to primitive float

long l= Longval.longValue(); Object to primitive long

double d=Doubleval.doubleValue(); Object to primitive double

Converting numbers to string using toString() method

Method calling Conversion Action

str= Integer.toString(i); Primitive integer to string

str= Float.toString(f); Primitive float to string

str= Double.toString(d); Primitive double to string

65
str= Long.toString(l); Primitive long to string

Converting string objects to numeric objects using the static method


ValueOf()

Method calling Conversion Action

DoubleVal=Double.ValueOf(str); Converts string to Double object

FloatVal=Float.ValueOf(str); Converts string to Flaot object

IntVal=Integer.ValueOf(str); Converts string to Integer object

LongVal=Long.ValueOf(str); Converts string to Long object

Converting numeric string to primitive numbers using parsing method

Method calling Conversion action

int i = Integer.parseInt(str); Converts string to primitive integer

long i = Long.parseLong(str); Converts string to primitive long

E.g. for Primitive to object

float num1=0.3F;  primitive data type

66
Float f1=new float (num1) changing to object

E.g. for converting string to numeric object

float num1=Float.ValueOf(in.readLine());

int val=Integer.ParseInt(in.readLine());

E.g.: object to primitive

float num1=0.3F;  primitive data type

Float f1=new float (num1) changing primitive to


object

num1=f1.floatValue(); changing object to primitive

*******************UNIT II COMPLETED*********************

One Mark Question

1. Which of these are selection statements in Java?


a) break
b) continue
c) for()
d) if()
2.
Which of these keywords is used to define interfaces in Java?
a) intf
b) Intf
c) interface
d) Interface
3. Which of the following is a super class of every class in Java?
a) Array List
b) Abstract class
c) Object class
d) String
4. Which of the below is not a Java Profiler?
a) JProfiler
b) Eclipse Profiler
c) JVM
d) JConsole
5. Which of these packages contains the exception Stack Overflow in Java?
a) java.io
b) java.system

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

12. Method used to take a string as input in Java?

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

14. Is string mutable in Java?

A. Yes
B. No

15. Which of these is a type of variable in Java?

A. Instance Variable
B. Local Variable
C. Static Variable
D. All of these

16. What will be the output of following Java code?

public class Main {


public static void main(String[] args) {
String str = "Hello";
str = "Bye";
System.out.println(str);
}
}

A. Hello
B. Bye
C. Error
D. All of these

17. What is type casting in Java?

A. It is converting type of a variable from one type to another


B. Casting variable to the class
C. Creating a new variable
D. All of these

18. Which type of casting is lossy in Java?

A. Widening typecasting
B. Narrowing typecasting

69
C. Manual typecasting
D. All of these

19. Which of the following can be declared as final in java?

A. Class
B. Method
C. Variable
D. All of these

20. Finally block is attached to?

A. Try-catch block
B. Class block
C. Method block
D. All of these

21. The break statement in Java is used to .

A. Terminates from the loop immediately


B. Terminates from the program immediately
C. Skips the current iteration
D. All of these

22. What will be the output of following Java code?

public class Main {


public static void main(String arg[]) {
int i;
for (i = 1; i <= 12; i += 2) {
if (i == 8) {
System.out.println(i);
break;
}
}
}
}

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

24. Array in java is .

A. Collection of similar elements


B. Collection of elements of different types
C. The data type of consisting of characters
D. None of these

25. Which of these is the correct method to create an array in java?

A. int[] arr = {1, 3, 5};


B. int[] arr;
C. arr = new int[] {3, 1, 8};
D. int arr[] = {1, 4, 6};
E. All of these

26. What is the extension of compiled java classes?


a) .txt
b) .js
c) .class
d) .java

Answer: c

27. Which exception is thrown when java is out of memory?


a) Memory Error
b) Out Of Memory Error
c) Memory Out Of Bounds Exception
d) Memory Full Exception

Answer: b

28. Which of these are selection statements in Java?


a) break
b) continue
c) for()
d) if()

Answer: d

29. Which of these keywords is used to define interfaces in Java?


a) intf
71
b) Intf
c) interface
d) Interface

Answer: c

30. Which of the following is a superclass of every class in Java?


a) ArrayList
b) Abstract class
c) Object class
d) String
Answer: c

31. Which of the below is not a Java Profiler?


a) JProfiler
b) Eclipse Profiler
c) JVM
d) JConsole

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

33. 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
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

35. Which one of the following is not an access modifier?


a) Protected

72
b) Void
c) Public
d) Private

Answer: b

36. 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

Answer: c
37. Which class provides system independent server side implementation?
a) Server
b) ServerReader
c) Socket
d) ServerSocket

Answer: d

38 Which of the following is true about servlets?


a) Servlets can use the full functionality of the Java class libraries
b) Servlets execute within the address space of web server, platform independent and uses the
functionality of java class libraries
c) Servlets execute within the address space of web server
d) Servlets are platform-independent because they are written in java
Answer: b

39. Which of the following option leads to the portability and security of Java?

a. Bytecode is executed by JVM


b. The applet makes the Java code secure and portable
c. Use of exception handling
d. Dynamic binding between objects

Answer: (a)

40. Which of the following is not a Java features?

a. Dynamic
b. Architecture Neutral
c. Use of pointers
d. Object-oriented

Answer: (c) Use of pointers

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

CLASSES, OBJECTS AND METHODS

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.

The basic form of a class definition is Example1 Example2


class classname [extends superclassname] class empty class sample
{ { {
[fields declaration;] int i,j;
[method declaration;] } void getdata();
} }

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

 Method declarations have four basic parts:

 The name of the method (method name)


 The type of the value the method returns (type)
 A list of parameters (parameter- list)
 The body of the method

The general form of the method declaration example


is class Triangle
type methodname (parameter -list) {
{ int length;
method-body; int height;
} void getdata(int x, int y)
{
length=x;
height=y;
}
}

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.

 Creating an object is also referred to as instantiating an object.


 Objects in java are created using the new operator.
 The new operator creates an object of the specified class and returns a reference to that
object.
 Every time the class is instantiated, a new copy of each of them is created.
Eg:

Triangle Tri1; // declare

Tri1=new Triangle ( ) // instantiate

 The first statement declares a variable to hold the object reference


 The second one actually assigns the object reference to the variable.
 The variable tri1 is now an object of the rectangle class

Eg1: Triangle tri1 = new Triangle ( );  valid

Eg2: Triangle tri1 = new Triangle ( );  tri1 and tri2 are the objects of Triangle
class

Triangle tri2 = new Triangle ( );

Eg3: Triangle tri1 = new Triangle ( );

Triangle tri2 = tri1;

77
ACCESSING CLASS MEMBERS
 we can access class members using DOT(.) operator

Syntax:
Accessing variables Accessing method

objectname. variablename = value; E.g.


objectname.methodname(parameter-list); Tri1.length=10; Tri1.getdata (10, 20);
Tri1.height=20;

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;

Volume(int l, int m, int n ) // parameterized constructor


{ x=l;
y=m;
z=n;
}
Public int calvolume()
{
int vol=x*y*z;

return vol;
}
}
class Demovolume()

public static void main(String args[])


{ Volume volobj=new Volume(100, 200, 300); // creating object
int result=volobj.calvolume(); // calling method
System.out.println(“the volume is =”+result);
}}

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 int max(int x, int y);

 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

 They can call only other static methods.


 They can only access static data.
 They cannot refer to this or super in anyway.
class mathoperation

static float mul(float x, float y) // static method

{return x*y;

static float divide(float x, float y) // static method

{return x/y;

class Mathapplication

{ public static void main(String args[])

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

public static void main(String args[])

{ Nesting nest=new Nesting(10,20);

nest.process();

}}

84
THIS KEYWORD

 The this keyword refers to the current object in a method or constructor.


o The most common use of the this keyword is to eliminate the confusion between
class attributes and parameters with the same name (because a class attribute is
shadowed by a method or constructor parameter). If you omit the keyword in the
example above, the output would be "0" instead of "5".

this can also be used to:

 Invoke current class constructor


 Invoke current class method
 Return the current class object
 Pass an argument in the method call
 Pass an argument in the constructor call

Example

Using this with a class attribute (x):

Public class Main {

Int x;

// Constructor with a parameter

Publc Main(int x) {

This.x=x;

//Call the constructor

Public static void main(String[] args) {

Main myObj = new Main(5);

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.

Simple example of command-line argument in java


1. class CommandLineExample{
2. public static void main(String args[]){
3. System.out.println("Your first argument is: "+args[0]);
4. }
5. }
1. compile by > javac CommandLineExample.java
2. run by > java CommandLineExample sonoo
3. Output: Your first argument is: sonoo

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.

Example of command-line argument that prints all the values


1. class A{
2. public static void main(String args[]){
3.
4. for(int i=0;i<args.length;i++)
5. System.out.println(args[i]);
6.
7. }
8. }

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

 Single inheritance (one super class, one sub class)


 Multiple inheritance (several super classes)
 Hierarchical inheritance (one super class and many sub classes)
 Multilevel inheritance(derived from a derived class)

1. Single inheritance
 Single class is one in which there exists single base class and single derived class.

2. Multi level inheritance


 Multi level inheritance is one which there exist single base class, single derived class and n
number of intermediate base classes.
 An intermediate base class is one, in one contest it acts as bass class and in another context
it acts as 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

 A subclass is defined as follows:


class subclassname extends superclassname

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

 When a finally of classes is created in hierarchical model then it is called as hierarchicaal


inheritance.
Example
class A
{ class mainclass
{
int a, b; public static void main(String args [])
void input() {
{ A obja=new A();
B objb=new B();
a=10;
C objc=new C();
b=20; obja.input();
System.out.println(“a=”+a+”b=”+b); objb.a=10;
objb.b=20;
}
objb.addtion();
} objc.a=10;
class B extends A objc.b=20;
{ objc.product();
}
void addition ()
{
System.out.println(“a+b=”+(a+b));
}
}
class C extends A
{ void product ()
{
System.out.println(“a*b=”+(a*b));
}}
OVERRIDING METHODS
 A method defined in a super class is inherited by its sub class and is used by the objects created
by the sub class.
 There may be occasions when we want an object to respond to the same method is called.

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.

final class Aclass


{
}
Final class Bclass extend someclass
{
}

FINALIZER METHODS
 Initialization constructor method is used to initialize an object when it is declared.
This process is called initialization.
 Finalizationfinalize 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.

The finalize( ) method has this general form:

protected void finalize( )

// finalization code here

Here, the keyword protected is a specifier that prevents access to finalize( ) by code defined
outside its class.

ABSTRACT METHODS AND CLASSES


 In JAVA we have two types of classes.
They are
1. concrete classes and
2. abstract classes.
93
 A concrete class is one which contains fully defined methods. Defined methods are also
known as implemented or concrete methods. With respect to concrete class, we can create
an object of that class directly.
 An abstract class is one which contains some defined methods and some undefined methods.
Undefined methods are also known as unimplemented or abstract methods. Abstract method is one
which does not contain any definition. To make the method as abstract we have to use a keyword
called abstract before the function declaration.

For example:
abstract class Op
{
abstract void sum ();
};

Syntax for ABSTRACT CLASS:

abstract class <clsname>


{
Abstract return_type method_name (method parameters if
any);
};

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.

METHODS WITH VARARGS


 Varargs represents variable length arguments in methods.
 It makes that java code simple and flexible.

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

 Interfaces are basically used to develop user defined data types.


 With respect to interfaces we can achieve the concept of multiple inheritances.
 With interfaces we can achieve the concept of polymorphism, dynamic binding and
hence we can improve the performance of a JAVA program in turns of memory
space and execution time.

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;

 Here, interface is the keyword.


 Interface name represent a JAVA valid variable name.
Variables are declared as follows:
static final type VariableName = Value;

All variables are declared as constants. Methods declaration will contain only a list of methods
without any body statements.

return-type methodName1 (parameter_list);

EXTENDING INTERFACES

 Interface can also be extended.


 An interface can be sub-interfaced from other interfaces.
 The new interface will inherit all the member of the super-interface.
 Interface can be extended using the keyword extends.

interface name2 extends name1


{
Body of name2

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

 Implement the interface using implements keyword.

General form1 General form2


class classname implements class classname extends supperclass implements
interfacename interface1,interface2,………..
{ {
body of classname body of classname
} }

ACCESSING INTERFACE VARIABLES

 Interface declares a set of constant values.


 The constant values will be available to any class that implements the interface.
Example

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);
}
}

Example 1 class InterfaceTest


interface Area
{ {
final static float pi=3.14F;
float compute (flaot x, float y); public static void main(String args[])
} {
class Rectangle implements Area Rectangle rect =new Rectangle();
{ Circle cir=new Circle();
public float compute(float x, float y) Area area;
area = rect;
{
return (x*y); System.out.println(area.compute(10,20));
} area = cir;
} System.out.println(area.compute(10,0));
}
class Circle implements Area }
{
public float compute(float x, float y)
{
return (pi*x*x);}
}
}

100
STRINGS

 String represents a sequence of characters.

 String can be represented in two ways in java

 Using character array

 Using string object or stringbuffer class

Using character array char carray[]=new char[4];


carray[0]=’j’;
Using string class carray[1]=’a’;
carray[2]=’v’;
carray[3]=’a’;

 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”);

To get length of the string int m=firstname.length();

To concatenate two string String fullname=name1+name2; String city=”new”+”delhi”;

String arrays

Eg : String item[]=new String[3];

 The string array item stores three strings.

item[0]=”soap”;

item[1]=”biscuits”;

item[2]=”powder”;

101
String methods

Most commonly used string methods

Method Task performed

s2=s1.toLowerCase; Converts the string s1 to all lowercase

s2=s1.toUpperCase‟; Converts the string s1 to all uppercase

s2=s1.replace(„x‟,‟y‟); Replace all appearances of x with y

s1.equal(s2); Returns true if s1 is equal to s2

s2=s1.trim(); Remove white space at the beginning and end of the String s1

s1.equalsIgnoreCase(s2); Returns true if s1 is equal to s2, ignoring the case of characters

s1.length(); Gives the length of s1.

s1.charAt(n) Gives nth character of s1

s1.concat(s2); Concatenates s1 and s2

s1.substring(n); Gives substring starting from nth character.

s1.substirng(n,m); Gives substring starting from nth character up to mth character

String.valueOf(p); Creates a string object of the parameter p(simple type or


object)

p.toString(); Creates a string representation of object p

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

String.valueOf(variable); Converts the parameter value to string representation.

102
s1.compareTo(s2) Returns negative if s1<s2, positive if s1>s2, zero if s1 and s2
equal.

Example program Alphabetic ordering of strings


class Stringordering
{
static String name[]={“Madras”, “Delhi, “Ahmedabad”, “Calcutta”,” Bombay”}
public static void main(String args[]);
{
int size=name.lenght();
String temp=null;
for (int i=0; i< size; i++)
{
for (int j = i+1; j<size; j++)
{
if name[j].comapreTo(name[i])<0)
{
temp=name[i];
name[i]=name[j];
name[j]=temp;
}
}
}
for (int i=0; i<size; i++)
{
System.out.println(name[i]);
}
}
}
StringBuffer class

 StringBuffer class is a peer class of String.

 String creates strings of fixed_length


103
 StringBuffer class creates string of flexible length that can be modified in terms of both
length and content.

 In stringbuffer class we can insert characters and substrings in the middle of a string, or
append another string to the end.

Eg: StringBuffer str=new StringBuffer(“annu”);

Methods Task

s1.setChartAt(n, „x‟); Modifies the nth character to x

s1.append(s2); Appends the string s2 to s1 at the end

s1.insert(n,s2); Inserts the string s2 at the position n of the string


s1

s1.setLength(n); Sets the length of the string s1 to n. if


n<s1.length() s1 is truncated. If n>s1.length()
zeros are added to s1.

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

3. Which of these access specifiers can be used for an interface?


a) Public
b) Protected
c) private
d) All of the mentioned

4. Which of these keywords is used by a class to use an interface defined previously?


a) import
b) Import
c) implements
106
d) Implements

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

6. Which of these keywords is used to define packages in Java?


a) pkg
b) Pkg
c) package
d) Package

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

14. What will be the output of the following Java code?

intarr[]=newint[5];
System.out.print(arr);

a) 0
b) value stored in arr[0]
c) 00000
d) Class name@ hashcode in hexadecimal form

15. Which of these is an incorrect Statement?


a) It is necessary to use new operator to initialize an array
b) Array can be initialized using comma separated expressions surrounded by curly braces
c) Array can be initialized when they are declared
d) None of the mentioned

16. Which of these is necessary to specify at time of array initialization?


a) Row
b) Column
c) Both Row and Column
d) None of the mentioned
17. String in Java is a?
a) class
b) object
c) variable
d) character array
18. Which of these method of String class is used to obtain character at specified index?
a) char()
b) Charat()
c) charat()
d) charAt()
19. Which of these keywords is used to refer to member of base class from a subclass?
a) upper
b) super
c) this
d) none of the mentioned
20. Which of these method of String class can be used to test to strings for equality?
a) isequal()
b) isequals()
c) equal()
d) equals()
21. Which of the following statements are incorrect?
a) String is a class
b) Strings in java are mutable

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

23. Which of these is a wrapper for data type int?


a) Integer
b) Long
c) Byte
d) Double
24. Which of these is a super class of wrappers Long, Character & Integer?
a) Long
b) Digits
c) Float
d) Number
25. Which of these is a wrapper for simple data type char?
a) Float
b) Character
c) String
d) Integer
26. Which of these methods is used to obtain value of invoking object as a long?
a) long value()
b) long longValue()
c) Long longvalue()
d) Long Longvalue()

27. Which of the following is a type of polymorphism in Java?


a) Compile time polymorphism
b) Execution time polymorphism
c) Multiple polymorphism
d) Multilevel polymorphism

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

29. When Overloading does not occur?


a) More than one method with same name but different method signature and different number or type of
parameters
b) More than one method with same name, same signature but different number of signature
c) More than one method with same name, same signature, same number of parameters but different type
d) More than one method with same name, same number of parameters and type but different
signature

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

Answer: (b) Default encoding of the host platform

37. What is the return type of the hashCode() method in the Object class?

a. Object
b. int
c. long
d. void

Answer: (b) int

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

Answer: (c) Javadoc tool

111
5 Marks

8. Explain in detail about Constructors.


9. Describe about string.
10. Explain in detail about looping statements with suitable examples.
11. Write a Java program using parameterized and default constructor.
12. Write short notes on Method overloading in java.
13. Explain in detail about final variables and methods.
10 Marks
1. Explain in detail about Inheritance and its types
2. Discuss about Nesting of methods

*****************UNIT III COMPLETED**********************

UNIT IV

PACKAGES

INTRODUCTION

 A package is a collection of classes, interfaces and sub-packages.


 A sub-package in turns divides into classes, interfaces, sub-sub-packages, etc.
 Learning about JAVA is nothing but learning about various packages.
 By default one predefined package is imported for each and every JAVA program and
whose name is java.lang.*.
 Whenever we develop any java program, it may contain many number of user defined
classes and user defined interfaces.
 If we are not using any package name to place user defined
classes and interfaces, JVM will assume its own package called NONAME package.

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".

JAVA API PACKAGES

Packages Contents

java.lang Language support classes.

java.util Language utility classes such as vectors, hash tables, random number,
date etc.

java.io Input and output classes.

java.awt Set of classes for implementing graphical user interfaces.

java.net Classes for networking.

java.applet Classes for creating and implementing applets.

USING SYSTEM PACKAGES

 Packages are organized in a hierarchical structure.


 The package named java contains the package awt, which in turns contain various
classes required for implementing graphical user interface.
There are two ways of accessing the classes stored in a package

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

Syntax: import packagename.classname;

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

 Package can be named using the standard java naming rules.


 Name should be unique, duplicate name cause run-time error.
 Package begins with lowercase letter.
(To distinguish with class name, class name beings with uppercase.)
Example:

double y = java . lang . Math . sqrt(x);

package class method

name name name


114
This statement uses a fully qualified class name Math to invoke the method sqrt( ).

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
}

 Package name is firstpackage.


 This file is saved as a file called FirstClass.java and located in a directory name
firstpackage.
 When source file is compiled, java will create a .class file and store it in the same
directory.
 The .class file should in the directory that has the same name as the package.

Steps:

 Declare the package at the beginning of a file using the form

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.

Java support Package hierarchy

 Specify multiple package names in a package statement, separated by dots.

E.g.: Package firstpackage.secondpackage;

 Store the package secondpackage in a subdirectory of firstpacakge.

115
ACCESSING A PACKAGE

The general form of import statement is as follows

import package1 [.package2] [.package3].classname;

 Package1 is the name of the top level package


 Package2 is the name of the package that is inside the package2 and so on.
 We can have any number of packages in a package hierarchy. Finally explicit classname is
specified.
USING A PACKAGE
 Create a classA under the package1;
 Import the classA from package1 in a program
 Compile the program
 During compilation, the compiler checks for the file ClassA.class in the package1 director
for information it needs.
 During running the program the interpreter loads the program along with the code of the
ClassA.class file.

Example 1

package package1; import package1.ClassA;


public class ClassA class PackageTest1
{ {
public void displayA() public static void main(String args[])
{
{ ClassA obj=new ClassA();
System.out.println(“class a”); obj.displayA();
} }
} }

Example 2

package package2; import package1.ClassA;


public class ClassB import package2.*;
{ class PackageTest1
{
public void displayB()
115 public static void main(String args[])
{ {
protected int m= 10; ClassA obj=new ClassA();
System.out.println(“class b”);
ADDING CLASS TO A PACKAGE
It is simple to add a class to an existing package. Consider the following package:
package p1;
public ClassA
{
// body of A
}
The package p1 contains one public class by name A. Suppose we want to add another class B
to this package. This can be done as follows:
1. Define the package and make it public.
2. Place the package statement
package p1;
before the class definition as follows:
package p1
public class B
{
// body of B
}
3. Store this as B.java file under the directory p1.
4. Compile B.java file. This will create a B.class file and place it in the directory p1.
Now, the package will contain both classes A and B. A statement like
import p1 . *;
will import both of them.
HIDING CLASSES
 To hide certain classes from accessing from outside of the package. Such classes should be
declared “ not public “. Example:

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.

MANAGING ERRORS AND EXCEPTIONS

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:

1. Find the problem ( Hit the exception )


2. Inform that an error has occurred ( Throw the exception )
3. Receive the error information ( Catch the exception )
4. Take corrective actions ( Handle the exceptions )
 When writing programs, we must always be an the lookout for places in the program where
an exception could be generated.
 Some come exceptions that we must watch out for catching are listed in table.

EXCEPTION TYPE CAUSE OF EXCEPTION

ArithmeticException Caused by math errors such as division by


zero

ArrayIndexOutOfBoundsException Caused by bad array indexed

ArrayStoreException Caused when a program tries to store the


wrong type data in an array.

FileNotFoundException Caused by an attempt to access a


nonexistent file

IOException Caused by general I/O failures, such as


inability to read from a file.

NullPointerException Caused by referencing a null object

NumberFormatException Caused when a conversion between strings


and number fails.

OutOfMemoryException Caused when there‟s not enough memory


to allocate a new object.

121
SecurityException Caused when an applet tries to perform an
action not allowed by the browser‟s
security settings.

StackOverflowException Caused when the system runs out of stack


space.

StringIndexOutOfBoundsException Caused when a program attempts to access


a nonexistent character position in a string.

Common Java Exceptions

Exceptions in java can be categorized into two types:

 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.

SYNTAX OF EXCEPTION HANDLING CODE

 The basic concept of exception handling are throwing an exception and catching it.
try block

Statement that causes an exception


Exception object Creator

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);
}
}

MULTIPLE CATCH STATEMENTS


 In some cases, more than one exception could be raised by a single piece of code.
 To handle this type of situation, you can specify two or more catch clause, each catching a
different type of exception.
Syntax:
……………
……………
try
{
statement; // generates an exception
123
}
catch (Exception-Type-1 e)
{
statement; // processes exception type 1
}
catch (Exception-Type-2 e)
{

statement; // processes exception type 2


}
.
catch (Exception-Type-N e)
{
statement; // processes exception type N
}
……………
 When an exception in a try block is generated, the java treats the multiple catch
statements like cases in a switch statement.
 The first statement whose parameter matches with the exception object will be
executed, and the remaining statements will be skipped.

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

 Creating threads in Java is simple.


 Threads are implemented in the form of objects that contain a method called run( ).
 The run( ) method is the heart and soul of any thread. It makes up the entire body of the
thread and is the only method in which the thread‟s behavior can be implemented.
 A typical run( ) would appear as follows:
public void run( )

---- ( Statements for implementing thread )

 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.

Declaring the class

The thread class can be extended as follows:

class MyThread extends Thread


{
……..
……..
}
Now we have a new type of thread MyThread.

Implementing the run( ) method

 The run( ) method has been inherited by the class MyThread.


 We have to override this method in order to implement the code to be executed by our
thread.
 The basic implementation of run( ) will look like this:
public void run( )
{
……..
…….. // Thread code here
}
 when we start the new thread, Java calls the thread‟s run( ) method, so it is the run( ) where
all the action takes place.
STARTING NEW THREAD

 To actually create and run on instance of the thread class, we must write the following
MyThread aThread = new MyThread( );

aThread.start ( ); //invokes run( ) method

 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

class A extends Thread


{
public void run( )
{
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( )
{
for ( int i=1;i<=3;i++)
{
System.out.println(“\t From thread B:i=”+i);
}
System.out.println( “ Exit from B”);
}
}
class ThreadTest
{
public static void main(String[] args)
{
new A( ).start( );
new B( ).start( );
}
}

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

suspend( ) //blocked until further orders

wait( ) //blocked until certain condition

 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

sleep,wait,suspend resume,notify stop

Blocked
Idle thread

STATE TRANSITION DIAGRAM OF A 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.

SCHEDULING A NEW BORN THREAD

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 Thread Runnable Threads

Relinquishing control using yield( ) method.

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

Running Runnable Suspended

Relinquishing control using suspend( ) method

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)

Running Runnable sleeping

Relinquishing control using sleep( ) method

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
● ●

Running Runnable Waiting

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:

final void notify()

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:

final void notifyall()

 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:

final void wait()

 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

Answer: (b) Default encoding of the host platform

2. What is the return type of the hashCode() method in the Object class?

e. Object
f. int
g. long
h. void

Answer: (b) int

3. Evaluate the following Java expression, if x=3, y=5, and z=10:

++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: (c) Javadoc tool

5. Which of these package is used for graphical user interface?


a) java.applet
b) java.awt
c) java.awt.image
d) java.io

Answer: b

6. Which of this package is used for analyzing code during run-time?


a) java.applet
b) java.awt
c) java.io
d) java.lang.reflect

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

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
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

15. Which of these keywords is not a part of exception handling?


a) try
b) finally
c) thrown
d) catch

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

18 .Which of these keywords is used to manually throw an exception?


a) try
b) finally
c) throw
d) catch
Answer: c
19. What is multithreaded programming?
a) It‟s a process in which two different processes run simultaneously
b) It‟s a process in which two or more parts of same process run simultaneously
c) It‟s a process in which many different process are able to access same information
d) It‟s a process in which a single process can access information from many sources
19. Which of these are types of multitasking?
a) Process based
b) Thread based

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

MANAGING INPUT/OUTPUT FILES IN JAVA

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.

Data representation in Java files

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.

Relationship of Java program with I/O devices

 stream in java is a path along which data flows.


 It has a source and a destination.
 Both the source and the destination may be physical devices or programs or other
streams in the same program.
 Java streams are classified into two basic types, namely input stream and output
stream.
 An input stream extracts data from the source(file) and sends it to the program.
 An output stream takes data from the program and sends it to the destination(file).The
following figure illustrates the use of input and output streams.

Using input and output streams


STREAM CLASSES

 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.

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

Input stream methods

DataInputStream extends FilterInputStream and implements the interface DataInput. The


DataInput interface contains the following methods.

The OutputStream includes methods that are designed to perform the following tasks:
 Writing bytes
 Closing streams
 Flushing streams
OuputStream Methods

Hierarchy of output stream classes

153
 The DataOutputStream, a counterpart of DataInputStream, implements the interface
DataOutput and, therefore, implements the following methods contained in DataOutput
interface.

CHARACTER STREAM CLASSES


 Character stream classes can be used to read and write 16-bit Unicode characters.
 There are two kinds of character stream classes, namely, reader stream classes and writer
stream classes.
Reader Stream classes
 Reader stream classes are designed to read character from the files.
 Reader class is the base class for all other classes in this group.
 The Reader class contains methods that are identical to those available in the
InputStream class, except Reader is designed to handle characters.

Hierarchy of reader stream classes

Writer stream Classes


 The writer stream classes are designed to perform all output operations on files.
 Only difference is that while output stream classes are designed to write bytes, the
writer stream classes are designed to write characters.

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:

 Uniform Resource Locator. It specifies the applets address.

DIFFERENCE BETWEEN APPLETS AND APPLICATIONS


 Applets do not use the main() method for initiating the execution of the code. Applets,
when loaded, automatically call certain methods of applet class to start and execute the
applet code.
 Unlike stand-alone applications, applets cannot run independently. They run from inside a
web page using a special feature known as HTML tag.
 Applets cannot read from or write to the files in the local computer.
 Applets cannot communicate with other servers on the network.
 Applets cannot run any program from the local computer.
 Applets are restricted from using libraries from other languages such as C or C++.
All these restrictions and limitations are placed in the interest of security of systems. These
restrictions ensure that an applet cannot do any damage to the local system.
WRITE APPLETS
The following steps involved in developing and testing in applet are:
1. Building an applet code(.java file).
2. Creating an executable applet(.class file).
3. Designing a Web page using HTML tags.
4. Preparing <APPLET> tag.
5. Incorporating <APPLET> tag into the Web page.
6. Creating HTML file.
156
7. Testing the applet code.
BUILDING APPLET CODE
 Applet code uses the service of two classes namely, Applet and Graphics from the
Java library. The applet class is contained in the java.applet package provides life and behavior
to the applet through its methods such as init(), start(), and paint().
 The Applet class maintains the lifecycle of an applet. The paint() method of the applet
class actually displays the result of the applet code on the screen. The output may be text,
graphics object as an argument, is defined as follows:
public void paint (Graphics g)

The applet code general format as follows:


import java.awt.*;
import java.applet.*;
public class appletclassname extends Applet
{
………………………………………………..
……………………………………………….
public void paint (Graphics g)
{
…………………………….
…………………………….
…………………………….
}
……………………………
……………………………
}
Example:
import java.awt.*;
import java.applet.*;
public class helloworld extends applet
{
public void paint(Graphics g)
{
g.drawstring “Hello Java”, 10, 100);
}
}

Chain of classes inherited by applet class

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

Begin Born Intialization


(Load Applet)
Start()
Stop() Idle Stopped
Runnin
Display g Start()
Paint() destroy()

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:

public void init()

……..(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)
}

Stopped Or Idle state:

 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)

ADDING APPLET TO HTML FILE


<HTML>
<HEAD>
<TITLE> WELCOME TO JAVA APPLETS</TITLE>
</HEAD>
<BODY>
<CENTER>
<H1> APPLETS</H1>
<BR>
</CENTER>
<APPLET
CODE= “HelloJava.class”
WIDTH=300

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

 We must have the following files in our current directory

HelloJava.java

HelloJava.class

HelloJava.html

 To run an applet we require one of the following tools:


1. Java-enabled web browser(such as HotJava or Netscape)
2. Java appletviewer
 If we use a Java-enabled web browser, we will be able to see the entire web page
containing the applet.
 If we use the appletviewer tool, we will only see the applet output.
Ex: appletviewer Hellojava.html

AppletViewer:Hellojava.class

Applet

Hello Java
APPLET TAGS

appletloader.started

The syntax of the <APPLET> tag in full form is shown as follows:

<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]

>

[ <PARAM NAME = name1 VALUE = value1>]

[ <PARAM NAME = name2 VALUE = value2>]

……….

[Text to be displayed in the absence of Java]

</APPLET>

Attributes of APPLET Tag

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

 We can supply user-defined parameters to an applet using <PARAM..> tags.


 Each <PARAM..> tag has a name attribute such as color, and a value attribute such
as red.
 For example, we can change the color of the text displayed to red by an applet by
using a <PARAM..> tag as follows:
<APPLET>
<PARAM = color VALUE = “red”>
</APPLET>
To set up and handle parameters, we need to do two things:
1. Include appropriate <PARAM..> tags in the HTML document.
2. Provide code in the applet to parse these parameters.
Example:
Applet HelloJavaParam

import java.awt.*;

import java.applet.*;

public class HelloJavaParam extends Applet

String str;

public void init( )

str= getParameter(“string”);

if (str == null)

str = “Java”;

165
str = “Hello” + str;

public void paint (Graphics g)

g.drawString(str, 10, 100);

Now let us create HTML file that contains this applet.

The HTML file for HelloJavaParam applet

<HTML>

<!parameterized HTML file>

<HEAD>

<TITLE> Welcome to Java Applets </TITLE>

</HEAD>

<BODY>

<APPLET CODE = HelloJavaParam.class

WIDTH = 400

HEIGHT = 200 >

<PARAM NAME = “string”

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

This will produce the result as shown below:

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

ALIGNING THE DISPLAY

We can align the output of the applet using the ALIGN attribute. This attribute can have
one of the nine values:

LEFT, RIGHT, TOP, TEXT TOP, MIDDLE, ABSMIDDLE, BASELINE,


BOTTOM, ABSBOTTOM

For example ALGN = LEFT will display the output at the left margin of the page.

Example:

<HTML>

<HEAD>

<TITLE> Here is an applet </TITLE>

</HEAD>

167
<BODY>

<APPLET CODE = HelloJava.class

WIDTH = 400

HEIGHT = 200

ALIGN = RIGHT >

</APPLET>

</BODY>

</HTML>

………………………………… Hello Java applet


………………………………………….
Text
……………………………………………………………………………

An applet aligned right


MORE ABOUT HTML TAGS

HTML Tags and Their Functions

Tag Function
<HTML> … Indicates starting & ending of a HTML file
</HTML>

<HEAD> … Contains the details of the web page


</HEAD>

<TITLE> … Contains the title of the browser


</TITLE>

<BODY> It contains the main text


….</BODY>

168
<H1> … </H1> It contains the heading tag, where 1 to 7 are its
size
…..
H1  Largest Font
<H7> …… </H7>
H7  Smallest Font

<CENTER> …. Places the text in the Center Position


</CENTER>

<APPLET> … Indicates the Applet tag for graphical creations


</APPLET>

<PARAM….> User defined parameters

<B> … </B> Boldface

<U> … </U> Underline

<I> …. </I> Italics

<BR> Indicates Break in text position

<P> Indicates the Paragraph tag

<IMG …. > Used for the insertion of the image

<HR> Draws the horizontal ruler

<A… > …. </A> Indicates the Anchor tag (i.e) Hyper reference

<FONT> …. Indicates the setting of Font, Size, Color…..


</FONT>

<!.. > Indicates the comment position

DISPLAYING NUMERICAL VALUES

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

 Applet works in a graphical environment.


 Applet treat input as a string.
 We must first create an area of the screen.
 This is do by using the TextField class of the applet package.

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)

3.Write a HTML document(.html file)


<html>
<applet

code =userIn.class
width = 300
height = 200>
</applet>
</html> Applet Viewer:UserIn.class
4.Use the appletviewer to display the result. Applet

123 215

Input a number in each box

The sum is :338

GRAPHICS PROGRAM MING


appletloader.started

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

LINES AND RECTANGLES

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);

 The g is the Graphics object passed to paint() method.


 We can draw a rectangle using the drawRect() method.
 This method takes four arguments.
 The first two represent the x and y coordinates of the left corner of the
rectangle, and the remaining two represent the width and the height of the rectangle.

Ex:

g.drawRect(10,60,40,30)

 We can draw a solid box by using the method fillRect()

Ex:

g.fillRect(60,10,30,80)

Example:

import java.awt.*;

import java.Applet.*;

public class LineRect extends Applet

public void pain (Graphics g)

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

CIRCLES AND ELLIPSES

appletloader.started

It is achieved by using drawOval() and fillOval()

Height

Width

Ex:

import java.awt.*;

import java.applet.*;

/*<Applet code = “cir.class” height=100 width=200>

</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

 An arc is a part of an oval.


 The drawArc( ) designed to draw arcs takes six arguments.
 The first four of are the same as arguments for drawOval( )method and the last two
represent the starting angle of the arc and the number of degrees around the arc.
 The fillArc( ) method to fill the arc.

import java.awt.*;

import java.applet.*;

public class Face extends Applet


{
public void paint (Graphics g)
{
g.drawOval( 40, 40, 120,150);
g.drawOval(57, 75, 30, 20);
g.drawOval(110, 75, 30, 20);

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

The drawPolygon( ) method takes 3 arguments.

 An array of integers containing x coordinates


 An array of integers containing y coordinates
 An integer for the total number of points
The fillPolygon( ) method used to draw a filled polygon.

179
Ex:

import java.awt.*;

import java.applet.*;

public class Poly extends Applet

int x1 [ ] = {20, 120, 220, 20};


int y1 [ ] = {20, 120, 20, 20};
int n1 = 4;
int x2 [ ] = {120,220, 220,120};
int y2 [ ] = {120, 20, 220,120};
int n2 = 4;
public void paint ( Graphics g)
{
g.drawPolygon(x1, y1, n1);
g.fill Polygon(x2, y2, n2);
}
}
LINE GRAPHS
We can design applets to draw line graphs to illustrate graphically the relationship between two
variables.
Consider the table of values shown as follows:
X 0 60 120 180 240 300 360 400
Y 400 280 220 140 60 60 100 220
Ex:

import java.awt.*;
import java.applet.*;
public class TableGraph extends Applet
{

int x [ ] = { 0, 60, 120, 180, 240, 300, 360, 400}


int y[ ] = {400, 280, 220, 140, 60, 60, 100, 220};
180
int n = x.length;
public void paint ( Graphics g)
{
g.drawPolygon( x, y, n);
}
}

USING CONTROL LOOPS IN APPLETS

 We can use all control structures in an applet.


 The program uses a for loop for drawing circles repeatedly.

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

DRAWING BAR CHARTS

 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.

Year 1991 1992 1993 1994

Turnover(Rs Crores) 110 150 100 170


Example:
import java.awt.*;
import java.applet.*;
public class BarChart extends Applet
{
int n=0;
String label [];
int value [];

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.

public void add<Type>Listener(<Type>Listener EveList)


183
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.
 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.

public void add<Type>Listener(<Type>Listener EveList)

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.

Event and Listener (Java Event Handling)


Changing the state of an object is known as an event. For example, click on button, dragging mouse etc.

The java.awt.event package provides many event classes and Listener interfaces for event handling.

Java Event classes and Listener interfaces

Event Classes Listener Interfaces

ActionEvent ActionListener

MouseEvent MouseListener and MouseMotionListener

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

The events can be broadly classified into two categories:

 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.

Steps involved in event handling

 The User clicks the button and the event is generated.


 Now the object of concerned event class is created automatically and information about the
source and the event get populated with in same object.
 Event object is forwarded to the method of registered listener class.
 the method is now get executed and returns.

Steps to perform Event Handling

Following steps are required to perform event handling:

1. Register the component with the Listener

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.

 It is very tedious to handle a large number of controls within the container.


 Oftenly the width and height information of a component is not given when we need to arrange
them.

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.

Following are the interfaces defining functionalities of Layout Managers.

Sr. Interface & Description


No.

1 LayoutManager

The LayoutManager interface declares those methods which need to be implemented by


the class whose object will act as a layout manager.

2 LayoutManager2

The LayoutManager2 is the sub-interface of the LayoutManager.This interface is for those


classes that know how to layout containers based on layout constraint object.

AWT Layout Manager Classes:

Following is the list of commonly used controls while designed GUI using AWT.

Sr. LayoutManager & Description


No.

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

The GridLayout manages the components in form of a rectangular grid.

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

Sr. Control & Description


No.

1 MenuComponent

It is the top level class for all menu related controls.

2 MenuBar

The MenuBar object is associated with the top-level window.

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

CheckboxMenuItem is subclass of MenuItem.

6 PopupMenu

PopupMenu can be dynamically popped up at a specified position within a component.

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

You might also like