Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
333 views

Java Notes-Ii CS

The document discusses the question paper pattern for the Programming in Java subject for semester 4 of the BSC Computer Science program at Kailash Women's College. It will have 3 parts - Part A will have 15 multiple choice questions with 1 mark each from each of the 5 units. Part B will have 2 questions of 5 marks each from each unit. Part C will have 5 questions of 10 marks each, with one question from each unit. The document also provides an overview of the 5 units that will be covered in the subject - introduction to OOPs, elements of Java, classes and objects, packages and exception handling, and I/O streams and applets.

Uploaded by

Ahfrin J
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
333 views

Java Notes-Ii CS

The document discusses the question paper pattern for the Programming in Java subject for semester 4 of the BSC Computer Science program at Kailash Women's College. It will have 3 parts - Part A will have 15 multiple choice questions with 1 mark each from each of the 5 units. Part B will have 2 questions of 5 marks each from each unit. Part C will have 5 questions of 10 marks each, with one question from each unit. The document also provides an overview of the 5 units that will be covered in the subject - introduction to OOPs, elements of Java, classes and objects, packages and exception handling, and I/O streams and applets.

Uploaded by

Ahfrin J
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 265

KAILASH WOMEN’S COLLEGE, NANGAVALLI

DEPARTMENT OF COMPUTER SCIENCE

CLASS : II - BSC COMPUTER SCIENCE

SUBJECT NAME : PROGRAMMING IN JAVA

PAPER CODE : 21UCS06

SEMESTER : IV

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)

KAILASH WOMEN’S COLLEGE, nangavalli


Cs - IV Semester
PROGRAMMING IN JAVA
UNIT – I

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

UNIT – II

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
loop – continue Statement. Arrays: One Dimensional Array – Creating an array –
Array processing – Multidimensional Array – Vectors – ArrayList – Advantages of
Array List over Array Wrapper classes.

Unit – III

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

UNIT – IV
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 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.

UNIT – V

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

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.

INTRODUCTION TO OOPS
 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

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

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


derived from structure programming programming is a computer
and based upon the concept of calling programming design
procedures. It follows a step-by-step philosophy or methodology
approach in order to break down a that organizes/ models
task into a set of variables and software design around data
routines via a sequence of or objects rather than
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 In OOP, objects can move


movement moves freely within the system from and communicate with each
one function to another. other 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


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

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


have the concept of inheritance. 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 In OOP, there is a concept of


procedural programming. function overloading and
operator overloading.
10. Importance It gives importance to functions over It gives importance to data
data. over functions.

11. Virtual class In procedural programming, there are In OOP, there is an


no virtual classes. appearance 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 In OOP, a program is


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

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.

JAVA EVOLUTION
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
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 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:

 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

 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 Runtime Environment(JRE)
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.

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++.”


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

Interface statements Optional

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.
 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.
 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
 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 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

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 + “!”);
}
}}
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;

COMMENTS IN JAVA

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:

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;
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. */

***************************UNITI COMPLETED*************************
UNIT II
CONSTANTS
 Constants refers to fixed values that do not change during the execution of a
program.
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.

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

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:

variablename = value;
For example:
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.
 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.

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
 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.
 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
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.
 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 relation.
Operator Meaning
 Java supports six relational operators.
< is less than
 A simple relational expression
<= is less than or equal
contains only one relational operator
to
and is of the following form:
> is greater than

ae-1 relational operator ae-2 >= is greater than or


equal to
 Where ae-1 and ae-2 are arithmetic
== is equal to
expressions.
!= is not equal to
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

op-1 op-2 op-1 && op-2 op-1 || op-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

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

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

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

Highest
The Precedence of ( ) [] .
the Java Operators ++ –– ~ !
* / %
+ –
>> >>> <<
> >= < <=
== !=
&
^
|
&&
||
?:
= op=
JAVA EXPRESSIONS
Lowest
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 expression 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

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 statement

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)

 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; {
}
marks = marks + bonus_marks;
statement-x;
}
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.

Example
if (degree = = “BCA”)
{
General form points = points+500;
System.out.println(“Its BCA”);
if (test expression) }
{ else
True block statements; {
} points = points+200;
else
System.out.println(“Its BSC
{
False block statements; CS”);
} }
Statement-X; ….

3. Nesting of if …else statement


 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
5. Nesting of if …else statement

4. Else if ladder

 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)
statement -3; else if (marks>79)
….. grade=”second”;
…..
else if (marks>79)
else if (condition n)
statement -n; grade=”third”;
else else
default-statement; grade=”fail”; // Default-stmt
System.out.println(“grade=”+grade);

The Switch Statement

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

General form Example1


switch(expression)
switch(expression) {
{ case ‘1’:
case value-1: System.out.println(“Monday”);
block-1 break;
break; case ‘2’:
case value-2: System.out.println(“Tuesday”);
block-2 break;
break; case ‘3’:
case value-3: System.out.println(“Wednesday”);
block-3 break;
break; case ‘4’:
……….. System.out.println(“Thursday”);
………. break;
default: ………………
default-block ………………..
break;
} default:
statement-x; System.out.println(“WRONG INPUT”);
break;
}
System.out.println(“ WELCOME TO THIS WEEK”);
…..
THE ? : OPERATOR

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. If (x<0)
Flag=0;
else
Flag=1;
Conditional expression ? Expression1 : expression2;
Ex1: Can be
written as

Flag = (x<0) ? 0 :
1;

Ex2:

Y = (x>2) ?
(2*x+1) : (3*x+2);

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

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

Here the body of the loop is executed 10 times for


n=1,2..10.

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 Simple example-1

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


{ {
sum = sum + n; 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 ! = 5; ++j) for (j=1; j<=10; 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.

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
} }
 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:

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
Form1Form2

type arrayname[];type[] arrayname;

Example
Int number[];Int[] number;
Float average[];Float[] average;

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

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.

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

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.

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

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

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

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

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

ACCESSING CLASS MEMBERS

 we can access class members using DOT(.) operator

Syntax:
Accessing variables Accessing method
E.g.
objectname. variablename = value; Tri1.length=10; Tri1.getdata (10, 20);
objectname.methodname(parameter-list); 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();
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).
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 ();
}
};

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;

}
METHOD OVERLOADING

 Methods that have the same name, but different parameter lists and different definitions
are called method overloading.
 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;
STATIC MEMBERS





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

}}

THIS KEYWORD

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

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

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.

Simple example of command-line argument in java


In this example, we are receiving only one argument and printing it. To run this java program, you must pass
least one argument from the command prompt.

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

Example of command-line argument that prints all the values


In this example, we are printing all the arguments passed from the command-line. For this purpose, we ha
traversed the array using for loop.

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

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


o Multiple inheritance (several super classes)
o 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

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

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
{
public static void main (String args[])
{
Room1 obj=new Room1(14,12,10);
int area1=obj.area ();
{
Length=x;
Breadth=y;
}
int area ()
{
return (Length*Breadth);
}
}
class Room1 extends Room
{
int height;
Room1 (int x, int y, int z)
{
super (x, y);
Height=z;
}
}

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

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;
objc.b=20;
objc.product();
}
}
class B extends A
{
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.
 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.
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àfinalizer 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.
 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.

Syntax for ABSTRACT CLASS:


abstract class <clsname> For example:

{ abstract class Op

Abstract return_type method_name (method {

parameters if any); abstract void sum ();

}; };

ABSTRACT METHODS
 When a method is defined as final than that method is not re-defined in a subclass.
 Java allows a method to be re-defined in a sub class and those methods are called abstract
methods.
 When a class contains one or more abstract methods, then it should be declared as abstract
class.
 When a class is defined as abstract class, it must satisfy following conditions
 We can’t use abstract classes to instantiate objects directly. For example
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
 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.
 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.
 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
{
{
static final int code = 1001;
variables declaration;
void display();
} declaration;
methods

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

interface ItemConstants
{
int code = 1001;
string name = “Fan”;
}
interface Item extends ItemConstants
{
void display( );
}
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

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

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’;
 In java strings are class objects and implemented using two classes; String and
carray[3]=’a’;
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”;

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.


;

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

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

// inserting a string in the middle

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

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

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.


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 static void main(String args[])
public void displayA()
{
{ 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()
public static void main(String args[])
{ {
protected int m= 10; ClassA obj=new ClassA();
System.out.println(“class b”); ClassB objb=new ClassB();
System.out.println(“m=”+m); obj.displayA();
} obj.displayB();
} }
}

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:
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
{
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.
 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:
 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.
 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.

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

Statement that handles the exception


Exception handler

 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.
 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
{ Division by zero
public static void main(String args[])
y=1
{
int a=10;
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

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)
{
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.

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

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

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.

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

Newborn

start

Running Runnable stop


Dead

Active Thread
yield
stop

Killed thread

sleep,wait,suspend resume,notify
Blocked stop

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.
 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 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.
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)
{
}
}
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

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
{
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( );
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
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.
 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( );
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()

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

**************UNIT IV COMPLETED***************

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

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

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

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.

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

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()
Idle
Running Stop() Stopped
Display 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
 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
 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
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>
<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
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

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

<APPLET

[CODEBASE = codebase_URL]

CODE = AppletFileName.class

[ALT = alternate_text]

[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.
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”;

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:

Appletviewer HelloJavaParam.html

This will produce the result as shown below:

AppletViewer:HelloJavaParam.class
Applet
Hello Applet!

appletloader.started
APPLET TAGS

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

appletloader.started
APPLET TAGS

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>

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

<H1> … It contains the heading tag, where 1 to 7 are


</H1> its size

….. H1  Largest Font

<H7> …… H7  Smallest Font


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

<APPLET> … Indicates the Applet tag for graphical


</APPLET> creations

<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… > …. Indicates the Anchor tag (i.e) Hyper


</A> reference

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


</FONT>

<!.. > Indicates the comment position

DISPLAYING NUMERICAL VALUES

 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

appletloader.started

GETTING INPUT FROM THE USER


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

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>

4.Use the appletviewer to display the result.


Applet Viewer:UserIn.class
Applet

Input a number in each box


123
The sum is :338 215

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)

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.

GRAPHICS PROGRAMMING

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

 The simplest shape we can draw with Graphics class is a line.


 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

Width = 250

Height = 200>

</Applet>
AppletViewer:Linerect.class
Applet

appletloader.started

CIRCLES AND ELLIPSES


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

Heigh
t

Width

Ex:

import java.awt.*;

import java.applet.*;

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

</Applet>*/

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

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

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

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);
else
g.fillOval(120, 1*60+10, 50, 50);
}
}
} AppletViewer.controlLoop.class
Applet

appletloader.started

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

Turnover(Rs Crores) 110150 100170

Example:
import java.awt.*;
import java.applet.*;
public class BarChart extends Applet
{
int n=0;
String label [];
int value [];
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”>
</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)

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.

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

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

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

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.

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.

************UNIT V COMPLETED**********
PROGRAMMING IN JAVA
ONE MARK QUESTIONS
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

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. Which of the following is a type of polymorphism in Java Programming?


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

Answer: b

12. What is Truncation in Java?


a) Floating-point value assigned to a Floating type
b) Floating-point value assigned to an integer type
c) Integer value assigned to floating type
d) Integer value assigned to floating type

Answer: b

13. What is the extension of compiled java classes?


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

Answer: c

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

15. Which of these are selection statements in Java?


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

Answer: d

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


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

Answer: c
17. Which of the following is a superclass of every class in Java?
a) ArrayList
b) Abstract class
c) Object class
d) String
Answer: c

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


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

Answer: c

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

20. 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
21. Which of these keywords are used for the block to be examined for exceptions?
a) check
b) throw
c) catch
d) try

Answer: d
22. Which one of the following is not an access modifier?
a) Protected
b) Void
c) Public
d) Private

Answer: b

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

24. Which class provides system independent server side implementation?


a) Server
b) ServerReader
c) Socket
d) ServerSocket

Answer: d

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

26. 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) Bytecode is executed by the JVM.


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

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


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

Answer: d

29. 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
30. When does method overloading is determined?
a) At run time
b) At compile time
c) At coding time
d) At execution time

Answer: b

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

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

33.Which concept of Java is achieved by combining methods and attribute into a class?
a) Encapsulation
b) Inheritance
c) Polymorphism
d) Abstraction
Answer: a

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

35. What is it called where child object gets killed if parent object is killed?
a) Aggregation
b) Composition
c) Encapsulation
d) Association

Answer: b
36. 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

Answer: a
37. Method overriding is combination of inheritance and polymorphism?
a) True
b) false

Answer: a
38. 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

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

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

Answer: (b) int

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

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

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

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

44.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
45.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

Answer: c
46.Which of this package is used for invoking a method remotely?
a) java.rmi
b) java.awt
c) java.util
d) java.applet

Answer: a
47.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
48.Which of these methods can be used to output a string in an applet?
a) display()
b) print()
c) drawString()
d) transient()

Answer: c

49.Which of these methods is a part of Abstract Window Toolkit (AWT) ?


a) display()
b) paint()
c) drawString()
d) transient()

Answer: b
50.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
51.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

52. 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
53. Which of these keywords is not a part of exception handling?
a) try
b) finally
c) thrown
d) catch

Answer: c
54. Which of these keywords must be used to monitor for exceptions?
a) try
b) finally
c) throw
d) catch

Answer: a
55. 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

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


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

Answer: c
ONE MARK QUESTIONS
UNIT I
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
7. What will be the output of the following Java code?
class increment {
public static void main(String args[])
{
int g = 3;
System.out.print(++g * 8);
}
}
a) 32
b) 33
c) 24
d) 25
Answer: a
output:
$ javac increment.java
$ java increment
32
8. Which environment variable is used to set the java path?
a) MAVEN_Path
b) JavaPATH
c) JAVA
d) JAVA_HOME
Answer: d
9. What will be the output of the following Java program?
class output {
public static void main(String args[])
{
double a, b,c;
a = 3.0/0;
b = 0/4.0;
c=0/0.0;
System.out.println(a);
System.out.println(b);
System.out.println(c);
}
}
a)NaN
b) Infinity
c) 0.0
d) all of the mentioned
Answer: d
10. Which of the following is not an OOPS concept in Java?
a) Polymorphism
b) Inheritance
c) Compilation
d) Encapsulation
Answer: c
11. 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

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


class variable_scope
{
public static void main(String args[])
{
int x;
x = 5;
{
int y = 6;
System.out.print(x + " " + y);
}
System.out.println(x + " " + y);
}
}
a) Compilation error
b) Runtime error
c) 5 6 5 6
d) 5 6 5
Answer: a
output:
$ javac variable_scope.java
Exception in thread "main" java.lang.Error: Unresolved compilation problem: y cannot be
resolved to a variable
13. 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
14. Which of the following is a type of polymorphism in Java Programming?
a) Multiple polymorphism
b) Compile time polymorphism
c) Multilevel polymorphism
d) Execution time polymorphism
Answer: b
15. What will be the output of the following Java program?
class leftshift_operator
{
public static void main(String args[])
{
byte x = 64;
int i;
byte y;
i = x << 2;
y = (byte) (x << 2)
System.out.print(i + " " + y);
}
}
a) 0 256
b) 0 64
c) 256 0
d) 64 0
Answer: c
output:
$ javac leftshift_operator.java
$ java leftshift_operator
256 0
16. What will be the output of the following Java code?

class box
{
int width;
int height;
int length;
}
class main
{
public static void main(String args[])
{
box obj = new box();
obj.width = 10;
obj.height = 2;
obj.length = 10;
int y = obj.width * obj.height * obj.length;
System.out.print(y);
}
}
a) 100
b) 400
c) 200
d) 12
Answer: c
output:
$ javac main.java
$ java main200
17. What is Truncation in Java?
a) Floating-point value assigned to a Floating type
b) Floating-point value assigned to an integer type
c) Integer value assigned to floating type
d) Integer value assigned to floating type
Answer:b
18. What will be the output of the following Java program?

class Output
{
public static void main(String args[])
{
int arr[] = {1, 2, 3, 4, 5};
for ( int i = 0; i < arr.length - 2; ++i)
System.out.println(arr[i] + " ");
}
}
a) 1 2 3 4 5
b) 1 2 3 4
c) 1 2
d) 1 2 3
Answer: d
output:
$ javac Output.java
$ java Output
123
19. What will be the output of the following Java code snippet?

class abc
{
public static void main(String args[])
{
if(args.length>0)
System.out.println(args.length);
}
}
a) The snippet compiles and runs but does not print anything
b) The snippet compiles, runs and prints 0
c) The snippet compiles, runs and prints 1
d) The snippet does not compile
Answer: a
20. What is the extension of compiled java classes?
a) .txt
b) .js
c) .class
d) .java
Answer: c.
21. Which exception is thrown when java is out of memory?
a) MemoryError
b) OutOfMemoryError
c) MemoryOutOfBoundsException
d) MemoryFullException
Answer: b
22. What will be the output of the following Java code?
class String_demo
{
public static void main(String args[])
{
char chars[] = {'a', 'b', 'c'};
String s = new String(chars);
System.out.println(s);
}
}
a) abc
b) a
c) b
d) c
Answer: a
23. Which of these are selection statements in Java?
a) break
b) continue
c) for()
d) if()
Answer: d
24. What will be the output of the following Java program?
class recursion
{
int func (int n)
{
int result;
if (n == 1)
return 1;
result = func (n - 1);
return result;
}
}
class Output
{
public static void main(String args[])
{
recursion obj = new recursion() ;
System.out.print(obj.func(5));
}
}
a) 1
b) 120
c) 0
d) None of the mentioned
Answer: a
Output:
$ javac Output.javac
$ java Output 1
25. What will be the output of the following Java code?

class output
{
public static void main(String args[])
{
String c = "Hello i love java";
boolean var;
var = c.startsWith("hello");
System.out.println(var);
}
}
a) 0
b) true
c) 1
d) false
Answer: d
26. Which of these keywords is used to define interfaces in Java?
a) intf
b) Intf
c) interface
d) Interface
Answer: c.
27. What will be the output of the following Java program?

class output
{
public static void main(String args[])
{
StringBuffer s1 = new StringBuffer("Quiz");
StringBuffer s2 = s1.reverse();
System.out.println(s2);
}
}
a) QuizziuQ
b) ziuQQuiz
c) Quiz
d) ziuQ
Answer: d
Output:
$ javac output.java
$ java output
ziuQ
28. What will be the output of the following Java code?

class Output
{
public static void main(String args[])
{
Integer i = new Integer(257);
byte x = i.byteValue();
System.out.print(x);
}
}
a) 257
b) 256
c) 1
d) 0
Answer: c
Output:
$ javac Output.java
$ java Output: 1
29. What will be the output of the following Java program?

class Output
{ public static void main(String args[])
{
double x = 2.0;
double y = 3.0;
double z = Math.pow( x, y );
System.out.print(z);
}
}
a) 9.0
b) 8.0
c) 4.0
d) 2.0
Answer: b
Output:
$ javac Output.java
$ java Output: 8.0

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. What will be the output of the following Java code?
class Output
{
public static void main(String args[])
{
double x = 3.14;
int y = (int) Math.ceil(x);
System.out.print(y);
}
}
a) 3
b) 0
c) 4
d) 3.0
Answer: c
Output:
$ javac Output.java
$ java Output: 4
32. What will be the output of the following Java program?

import java.net.*;
class networking
{
public static void main(String[] args) throws Exception
{
URL obj = new URL("https://www.sanfoundry.com/javamcq");
URLConnection obj1 = obj.openConnection();
int len = obj1.getContentLength();
System.out.print(len);
}
}
a) 127
b) 126
c) Runtime Error
d) Compilation Error
Answer: a

Output:
$ javac networking.java
$ java networking : 127
33. Which of the below is not a Java Profiler?
a) JProfiler
b) Eclipse Profiler
c) JVM
d) JConsole
Answer: c
34. What will be the output of the following Java program?
import java.net.*;
class networking
{
public static void main(String[] args) throws MalformedURLException
{
URL obj = new URL("https://www.sanfoundry.com/javamcq");
System.out.print(obj.toExternalForm());
}
}
a) www.sanfoundry.com
b) https://www.sanfoundry.com/javamcq
c) sanfoundry
d) sanfoundry.com
Answer: b
Output:
$ javac networking.java
$ java networking
https://www.sanfoundry.com/javamcq
35. What will be the output of the following Java code snippet?

import java.util.*;
class Arraylists
{
public static void main(String args[])
{
ArrayLists obj = new ArrayLists();
obj.add("A");
obj.add("B");
obj.add("C");
obj.add(1, "D");
System.out.println(obj);
}
}
a) [A, D, C]
b) [A, B, C]
c) [A, B, C, D]
d) [A, D, B, C]
Answer: d

Output:
$ javac Arraylist.java
$ java Arraylist
[A, D, B, C].
36. 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
37. What will be the output of the following Java program?
import java.util.*;
class Collection_iterators
{
public static void main(String args[])
{
LinkedList list = new LinkedList();
list.add(new Integer(2));
list.add(new Integer(8));
list.add(new Integer(5));
list.add(new Integer(1));
Iterator i = list.iterator();
Collections.reverse(list);
Collections.sort(list);
while(i.hasNext())
System.out.print(i.next() + " ");
}
}
a) 1 2 5 8
b) 2 1 8 5
c) 1 5 8 2
d) 2 8 5 1
Answer: a
38. 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
39. Which of these keywords are used for the block to be examined for exceptions?
a) check
b) throw
c) catch
d) try
Answer: d
40. What will be the output of the following Java code?
class newthread extends Thread
{
Thread t;
newthread()
{
t1 = new Thread(this,"Thread_1");
t2 = new Thread(this,"Thread_2");
t1.start();
t2.start();
}
public void run()
{
t2.setPriority(Thread.MAX_PRIORITY);
System.out.print(t1.equals(t2));
}
}
class multithreaded_programing
{
public static void main(String args[])
{
new newthread();
}
}
a) truetrue
b) falsefalse
c) true
d) false
Answer: b
Output:
$ javac multithreaded_programing.java
$ java multithreaded_programing
falsefalse
41. Which one of the following is not an access modifier?
a) Protected
b) Void
c) Public
d) Private
Answer: b.
42. What will be the output of the following Java program?
final class A
{
int i;
}
class B extends A
{
int j;
System.out.println(j + " " + i);
}
class inheritance
{
public static void main(String args[])
{
B obj = new B();
obj.display();
}
}
a) 2 2
b) 3 3
c) Runtime Error
d) Compilation Error
Answer: d
output:
$ javac inheritance.java
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
i cannot be resolved or is not a field
43. 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
44. Which class provides system independent server side implementation?
a) Server
b) ServerReader
c) Socket
d) ServerSocket
Answer: d
46. 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
5 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.

10 Marks
1. What is mean by OOP? Explain OOP Concepts.

2. Explain History and Evolution of Java.

3. Explain in detail about List the Java Tokens.

4. Differences between procedure oriented programming and object oriented programming.

5. Explain the types of java program.

6. Detail about overview of java.


UNIT II
1. Which of these operators is used to allocate memory to array variable in Java?
a) malloc
b) alloc
c) new
d) new malloc
Answer: c
2. 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
Answer: d
3. What will be the output of the following Java code?
int arr[] = new int [5];
System.out.print(arr);
a) 0
b) value stored in arr[0]
c) 00000
d) Class name@ hashcode in hexadecimal form
Answer: d
4. 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
Answer: a
5. 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
Answer: a
6. What will be the output of the following Java code?
class array_output
{
public static void main(String args[])
{
int array_variable [] = new int[10];
for (int i = 0; i < 10; ++i)
{
array_variable[i] = i;
System.out.print(array_variable[i] + " ");
i++;
}
}
}
a) 0 2 4 6 8
b) 1 3 5 7 9
c) 0 1 2 3 4 5 6 7 8 9
d) 1 2 3 4 5 6 7 8 9 10
Answer: a
output:
$ javac array_output.java
$ java array_output: 0 2 4 6 8
7. What will be the output of the following Java code?

class multidimention_array
{
public static void main(String args[])
{
int arr[][] = new int[3][];
arr[0] = new int[1];
arr[1] = new int[2];
arr[2] = new int[3];
int sum = 0;
for (int i = 0; i < 3; ++i)
for (int j = 0; j < i + 1; ++j)
arr[i][j] = j + 1;
for (int i = 0; i < 3; ++i)
for (int j = 0; j < i + 1; ++j)
sum + = arr[i][j];
System.out.print(sum);
}
}
a) 11
b) 10
c) 13
d) 14
Answer: b
output:
$ javac multidimention_array.java
$ java multidimention_array
10
8. What will be the output of the following Java code?
class evaluate
{
public static void main(String args[])
{
int arr[] = new int[] {0 , 1, 2, 3, 4, 5, 6, 7, 8, 9};
int n = 6;
n = arr[arr[n] / 2];
System.out.println(arr[n] / 2);
}
}
a) 3
b) 0
c) 6
d) 1
Answer: d
output:
$ javac evaluate.java
$ java evaluate:1
9. What will be the output of the following Java code?

class array_output
{
public static void main(String args[])
{
char array_variable [] = new char[10];
for (int i = 0; i < 10; ++i)
{
array_variable[i] = 'i';
System.out.print(array_variable[i] + "");
}
}
}
a) 1 2 3 4 5 6 7 8 9 10
b) 0 1 2 3 4 5 6 7 8 9 10
c) i j k l m n o p q r
d) i i i i i i i i i i
Answer: d
output:
$ javac array_output.java
$ java array_output
iiiiiiiiii
10. What will be the output of the following Java code?
class array_output
{
public static void main(String args[])
{
int array_variable[][] = {{ 1, 2, 3}, { 4 , 5, 6}, { 7, 8, 9}};
int sum = 0;
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3 ; ++j)
sum = sum + array_variable[i][j];
System.out.print(sum / 5);
}
}
a) 8
b) 9
c) 10
d) 11
Answer: b.
output:
$ javac array_output.java
$ java array_output:9

11. What is the type of variable ‘b’ and ‘d’ in the following Java snippet?

int a[], b;
int []c, d;
a) ‘b’ and ‘d’ are int
b) ‘b’ and ‘d’ are arrays of type int
c) ‘b’ is int variable; ‘d’ is int array
d) ‘d’ is int variable; ‘b’ is int array
Answer: c
12. Which of these is an incorrect array declaration?
a) int arr[] = new int[5] ;
b) int [] arr = new int[5] ;
c)int arr[];arr = new int[5];
d) int arr[] = int [5] new;
Answer: d
13. What will be the output of the following Java code?
1. int arr[] = new int [5];
2. System.out.print(arr);
a) 0
b) value stored in arr[0].
c) 00000
d) Garbage value
Answer: d

14. What will be the output of the following Java code snippet?
1. Object[] names = new String[3];
2. names[0] = new Integer(0);
a) ArrayIndexOutOfBoundsException
b) ArrayStoreException
c) Compilation Error
d) Code runs successfully
Answer: b
15. Generics does not work with?
a) Set
b) List
c) Tree
d) Array
Answer: d
16. How to sort an array?
a) Array.sort()
b) Arrays.sort()
c) Collection.sort()
d) System.sort()
Answer: b.
17. How to copy contents of array?
a) System.arrayCopy()
b) Array.copy()
c) Arrays.copy()
d) Collection.copy()
Answer: a
18. Can you make an array volatile?
a) True
b) False
Answer: a
19. Where is an array stored in memory?
a) heap space
b) stack space
c) heap space and stack space
d) first generation memory
Answer: a
20. An array elements are always stored in ________ memory locations.
a) Sequential
b) Random
c) Sequential and Random
d) Binary search
Answer: a
21. What is the range of short data type in Java?
a) -128 to 127
b) -32768 to 32767
c) -2147483648 to 2147483647
d) None of the mentioned
Answer: b
22. What is the range of byte data type in Java?
a) -128 to 127
b) -32768 to 32767
c) -2147483648 to 2147483647
d) None of the mentioned
Answer: a
23. Which of the following are legal lines of Java code?
1. int w = (int)888.8;
2. byte x = (byte)100L;
3. long y = (byte)100;
4. byte z = (byte)100L;
a) 1 and 2
b) 2 and 3
c) 3 and 4
d) All statements are correct
Answer: d
24. An expression involving byte, int, and literal numbers is promoted to which of these?
a) int
b) long
c) byte
d) float
Answer: a
25. Which of these literals can be contained in float data type variable?
a) -1.7e+308
b) -3.4e+038
c) +1.7e+308
d) -3.4e+050
Answer: b
26. Which data type value is returned by all transcendental math functions?
a) int
b) float
c) double
d) long
Answer: c
27. What will be the output of the following Java code?
class average {
public static void main(String args[])
{
double num[] = {5.5, 10.1, 11, 12.8, 56.9, 2.5};
double result;
result = 0;
for (int i = 0; i < 6; ++i)
result = result + num[i];
System.out.print(result/6);

}
}
a) 16.34
b) 16.566666644
c) 16.46666666666667
d) 16.46666666666666
Answer: c
output:
$ javac average.java
$ java average: 16.46666666666667
28. What will be the output of the following Java statement?

class output {
public static void main(String args[])
{
double a, b,c;
a = 3.0/0;
b = 0/4.0;
c=0/0.0;

System.out.println(a);
System.out.println(b);
System.out.println(c);
}
}
a) Infinity
b) 0.0
c) NaN
d) all of the mentioned
Answer: d
29. What will be the output of the following Java code?
class increment {
public static void main(String args[])
{
int g = 3;
System.out.print(++g * 8);
}
}
a) 25
b) 24
c) 32
d) 33
Answer: c
output:
$ javac increment.java
$ java increment:32
30. What will be the output of the following Java code?

class area {
public static void main(String args[])
{
double r, pi, a;
r = 9.8;
pi = 3.14;
a = pi * r * r;
System.out.println(a);
}
}
a) 301.5656
b) 301
c) 301.56
d) 301.56560000
Answer: a
output:
$ javac area.java
$ java area
301.5656
31. Which component is used to compile, debug and execute java program?
a) JVM
b) JDK
c) JIT
d) JRE
Answer: b
32. Which component is responsible for converting bytecode into machine specific code?
a) JVM
b) JDK
c) JIT
d) JRE
Answer: a
33. Which component is responsible to run java program?
a) JVM
b) JDK
c) JIT
d) JRE
Answer: d
34. Which component is responsible to optimize bytecode to machine code?
a) JVM
b) JDK
c) JIT
d) JRE
Answer: c
35. Which statement is true about java?
a) Platform independent programming language
b) Platform dependent programming language
c) Code dependent programming language
d) Sequence dependent programming language
Answer: a
36. Which of the below is invalid identifier with the main method?
a) public
b) static
c) private
d) final
Answer: c
37. What is the extension of java code files?
a) .class
b) .java
c) .txt
d) .js
Answer: b.
38. What is the extension of compiled java classes?
a) .class
b) .java
c) .txt
d) .js
Answer: a.
39. How can we identify whether a compilation unit is class or interface from a .class file?
a) Java source file header
b) Extension of compilation unit
c) We cannot differentiate between class and interface
d) The class or interface name should be postfixed with unit type
Answer: a

40. What is use of interpreter?


a) They convert bytecode to machine language code
b) They read high level code and execute them
c) They are intermediated between JIT and JVM
d) It is a synonym for JIT
Answer: b
41. Which of the following is not OOPS concept in Java?
a) Inheritance
b) Encapsulation
c) Polymorphism
d) Compilation
Answer: d
42. 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
43. When does method overloading is determined?
a) At run time
b) At compile time
c) At coding time
d) At execution time
Answer: b
44. 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
45. 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
46. Which concept of Java is achieved by combining methods and attribute into a class?
a) Encapsulation
b) Inheritance
c) Polymorphism
d) Abstraction
View Answer

Answer: a
Explanation: Encapsulation is implemented by combining methods and attribute into a class. The
class acts like a container of encapsulating properties.
47. 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
48. What is it called where child object gets killed if parent object is killed?
a) Aggregation
b) Composition
c) Encapsulation
d) Association
Answer: b

49. 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
Answer: a
50. Method overriding is combination of inheritance and polymorphism?
a) True
b) false
Answer: a

5MARK

1. Define Data Type. Criticize the declaration of variable in Java.


2. Write a Java program to interchange the values without using temporary variable.
3. Write a Java program to use Bit-wise operators.
4. Tell about the varargs in java? Write the syntax and develop any program.
5. Give the Structure of Java? Explain type of programs in Java

10 MARK

1. What is an Array? Explain types of arrays in Java with example.


2. Write a Java program to read and display the array elements in order
3. What is an Operator? Explain type of operators in Java with example programs.
4. Explain the decision making and looping.
5. Explain the evaluation of expressions.
UNIT III
1. Which of this keyword can be used in a subclass to call the constructor of superclass?
a) super
b) this
c) extent
d) extends
Answer: a
2. What is the process of defining a method in a subclass having same name & type
signature as a method in its superclass?
a) Method overloading
b) Method overriding
c) Method hiding
d) None of the mentioned
Answer: b
3. Which of these keywords can be used to prevent Method overriding?
a) static
b) constant
c) protected
d) final
Answer: d
4. Which of these method of class String is used to extract a single character from a String
object?
a) CHARAT()
b) chatat()
c) charAt()
d) ChatAt()
Answer: c
5.Which of these is correct way of calling a constructor having no parameters, of superclass
A by subclass B?
a) super(void);
b) superclass.();
c) super.A();
d) super();

Answer: d
6. Which of these is supported by method overriding in Java?
a) Abstraction
b) Encapsulation
c) Polymorphism
d) None of the mentioned
Answer: c
7. What will be the output of the following Java program?
class Alligator
{
public static void main(String[] args)
{
int []x[] = {{1,2}, {3,4,5}, {6,7,8,9}};
int [][]y = x;
System.out.println(y[2][1]);
}
}
a) 2
b) 3
c) 7
d) Compilation Error
Answer: c
Explanation: Both x,and y are pointing to the same array.
8. Which of these constructors is used to create an empty String object?
a) String()
b) String(void)
c) String(0)
d) None of the mentioned
Answer: a
9. What will be the output of the following Java program?
class Abc
{
public static void main(String[]args)
{
String[] elements = { "for", "tea", "too" };
String first = (elements.length > 0) ? elements[0]: null;
}
}
a) Compilation error
b) An exception is thrown at run time
c) The variable first is set to null
d) The variable first is set to elements[0]
Answer: d
11. Which of these class is superclass of every class in Java?
a) String class
b) Object class
c) Abstract class
d) ArrayList class
Answer: b
12. Which of these method of Object class can clone an object?
a) Objectcopy()
b) copy()
c) Object clone()
d) clone()
Answer: c
13. Which of these method of Object class is used to obtain class of an object at run time?
a) get()
b) void getclass()
c) Class getclass()
d) None of the mentioned
Answer: c
14. Which of these keywords can be used to prevent inheritance of a class?
a) super
b) constant
c) class
d) final
Answer: d
15. Which of these keywords cannot be used for a class which has been declared final?
a) abstract
b) extends
c) abstract and extends
d) none of the mentioned
Answer: a
16. Which of these class relies upon its subclasses for complete implementation of its
methods?
a) Object class
b) abstract class
c) ArrayList class
d) None of the mentioned
Answer: b
17. What will be the output of the following Java program?
abstract class A
{
int i;
abstract void display();
}
class B extends A
{
int j;
void display()
{
System.out.println(j);
}
}
class Abstract_demo
{
public static void main(String args[])
{
B obj = new B();
obj.j=2;
obj.display();
}
}
a) 0
b) 2
c) Runtime Error
d) Compilation Error
Answer: b
18. What will be the output of the following Java program?
class A
{
int i;
int j;
A()
{
i = 1;
j = 2;
}
}
class Output
{
public static void main(String args[])
{
A obj1 = new A();
A obj2 = new A();
System.out.print(obj1.equals(obj2));
}
}
a) false
b) true
c) 1
d) Compilation Error
Answer: a
19. What will be the output of the following Java code?
class Output
{
public static void main(String args[])
{
Object obj = new Object();
System.out.print(obj.getclass());
}
}
a) Object
b) class Object
c) class java.lang.Object
d) Compilation Error
Answer: c
20. What will be the output of the following Java code?
class A
{
int i;
int j;
A()
{
i = 1;
j = 2;
}
}
class Output
{
public static void main(String args[])
{
A obj1 = new A();
System.out.print(obj1.toString());
}
}
a) true
b) false
c) String associated with obj1
d) Compilation Error
Answer: c
21. Which of these keywords are used to define an abstract class?
a) abst
b) abstract
c) Abstract
d) abstract class
Answer: b
22. Which of these is not abstract?
a) Thread
b) AbstractList
c) List
d) None of the Mentioned
Answer: a
23. If a class inheriting an abstract class does not define all of its function then it will be
known as?
a) Abstract
b) A simple class
c) Static class
d) None of the mentioned
Answer: a
24. Which of these is not a correct statement?
a) Every class containing abstract method must be declared abstract
b) Abstract class defines only the structure of the class not its implementation
c) Abstract class can be initiated by new operator
d) Abstract class can be inherited
Answer: c
25. Which of these packages contains abstract keyword?
a) java.lang
b) java.util
c) java.io
d) java.system
Answer: a.
26. What will be the output of the following Java code?

class A
{
public int i;
private int j;
}
class B extends A
{
void display()
{
super.j = super.i + 1;
System.out.println(super.i + " " + super.j);
}
}
class inheritance
{
public static void main(String args[])
{
B obj = new B();
obj.i=1;
obj.j=2;
obj.display();
}
}
a) 2 2
b) 3 3
c) Runtime Error
d) Compilation Error
Answer: d
27. What will be the output of the following Java code?
class A
{
public int i;
public int j;
A()
{
i = 1;
j = 2;
}
}
class B extends A
{
int a;
B()
{
super();
}
}
class super_use
{
public static void main(String args[])
{
B obj = new B();
System.out.println(obj.i + " " + obj.j)
}
}
a) 1 2
b) 2 1
c) Runtime Error
d) Compilation Error
Answer: a
output:
$ javac super_use.java
$ java super_use:1 2
28. What will be the output of the following Java code?

class A
{
int i;
void display()
{
System.out.println(i);
}
}
class B extends A
{
int j;
void display()
{
System.out.println(j);
}
}
class method_overriding
{
public static void main(String args[])
{
B obj = new B();
obj.i=1;
obj.j=2;
obj.display();
}
}
a) 0
b) 1
c) 2
d) Compilation Error
Answer: c
output:
$ javac method_overriding.java
$ java method_overriding: 2
29. What will be the output of the following Java code?

class A
{
public int i;
protected int j;
}
class B extends A
{
int j;
void display()
{
super.j = 3;
System.out.println(i + " " + j);
}
}
class Output
{
public static void main(String args[])
{
B obj = new B();
obj.i=1;
obj.j=2;
obj.display();
}
}
a) 1 2
b) 2 1
c) 1 3
d) 3 1
Answer: a
output:
$ javac Output.java
$ java Output:1 2
31. Which of this keyword must be used to inherit a class?
a) super
b) this
c) extent
d) extends
Answer: d
32. A class member declared protected becomes a member of subclass of which type?
a) public member
b) private member
c) protected member
d) static member
Answer: b
33. Which of these is correct way of inheriting class A by class B?
a) class B + class A {}
b) class B inherits class A {}
c) class B extends A {}
d) class B extends class A {}
Answer: c

34. Which two classes use the Shape class correctly?


A. public class Circle implements Shape
{
private int radius;
}
B. public abstract class Circle extends Shape
{
private int radius;
}
C. public class Circle extends Shape
{
private int radius;
public void draw();
}
D. public abstract class Circle implements Shape
{
private int radius;
public void draw();
}
E. public class Circle extends Shape
{
private int radius;
public void draw()
{
/* code here */
}
}
F. public abstract class Circle implements Shape
{
private int radius;
public void draw()
{
/* code here */
}
}
a) B,E
b) A,C
c) C,E
d) T,H
Answer: a

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


class A
{
int i;
void display()
{
System.out.println(i);
}
}
class B extends A
{
int j;
void display()
{
System.out.println(j);
}
}
class inheritance_demo
{
public static void main(String args[])
{
B obj = new B();
obj.i=1;
obj.j=2;
obj.display();
}
}
a) 0
b) 1
c) 2
d) Compilation Error
Answer: c
output:
$ javac inheritance_demo.java
$ java inheritance_demo : 2
36. What will be the output of the following Java program?

class A
{
int i;
}
class B extends A
{
int j;
void display()
{
super.i = j + 1;
System.out.println(j + " " + i);
}
}
class inheritance
{
public static void main(String args[])
{
B obj = new B();
obj.i=1;
obj.j=2;
obj.display();
}
}
a) 2 2
b) 3 3
c) 2 3
d) 3 2
Answer: c
output:
$ javac inheritance.java
$ java inheritance: 2 3
37. What will be the output of the following Java program?

class A
{
public int i;
public int j;
A()
{
i = 1;
j = 2;
}
}
class B extends A
{
int a;
B()
{
super();
}
}
class super_use
{
public static void main(String args[])
{
B obj = new B();
System.out.println(obj.i + " " + obj.j)
}
}
a) 1 2
b) 2 1
c) Runtime Error
d) Compilation Error
Answer: a
output:
$ javac super_use.java
$ java super_use:1 238
38. What is not type of inheritance?
a) Single inheritance
b) Double inheritance
c) Hierarchical inheritance
d) Multiple inheritance
Answer: b
39. Using which of the following, multiple inheritance in Java can be implemented?
a) Interfaces
b) Multithreading
c) Protected methods
d) Private methods
Answer: a

40. All classes in Java are inherited from which class?


a) java.lang.class
b) java.class.inherited
c) java.class.object
d) java.lang.Object
Answer: d
41. In order to restrict a variable of a class from inheriting to subclass, how variable should
be declared?
a) Protected
b) Private
c) Public
d) Static
Answer: b
42. If super class and subclass have same variable name, which keyword should be used to
use super class?
a) super
b) this
c) upper
d) classname
Answer: a
43. Static members are not inherited to subclass.
a) True
b) False
Answer: b
44. Which of the following is used for implementing inheritance through an interface?
a) inherited
b) using
c) extends
d) implements
Answer: d
45. Which of the following is used for implementing inheritance through class?
a) inherited
b) using
c) extends
d) implements
Answer: c
46. What would be the result if a class extends two interfaces and both have a method with
same name and signature? Lets assume that the class is not implementing that method.
a) Runtime error
b) Compile time error
c) Code runs successfully
d) First called method is executed successfully
Answer: b
47. Does Java support multiple level inheritance?
a) True
b) False
Answer: a
48. Which of these class is superclass of String and StringBuffer class?
a) java.util
b) java.lang
c) ArrayList
d) None of the mentioned
Answer: b
49. Which of these operators can be used to concatenate two or more String objects?
a) +
b) +=
c) &
d) ||
Answer: a
50. Which of this method of class String is used to obtain a length of String object?
a) get()
b) Sizeof()
c) lengthof()
d) length()
Answer: d
5mark

1.Define Class, Method and Object? Show the syntax to define these in java
2. Compare Method Overriding and Method Overloading
3.Create a java program to display “Hello! Java” using Class, Object and Method.
4. Give the differences between Abstract class and Interface
5. Discuss in detail about Abstract Classes in Java
10 MARK

1.explain the types of inheritance


2.explain the overriding methods.
3.details about defining interface and extending interface.
4. Write the difference between String and StringBuffer classes.
5. Define String? Explain different String declarations with an example
6.List and explain any five string methods.
UNIT IV
1. Which of these keywords is used to define packages in Java?
a) pkg
b) Pkg
c) package
d) Package
Answer: c
2.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.
Answer:b
3. 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
Answer: d
4. 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
Answer: a.
5. 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.*
Answer: c
6. Which of the following is an incorrect statement about packages?
a) Package defines a namespace in which classes are stored
b) A package can contain other package within it
c) Java uses file system directories to store packages
d) A package can be renamed without renaming the directory in which the classes are
stored
Answer: d
7. Which of the following package stores all the standard java classes?
a) lang
b) java
c) util
d) java.packages
Answer: b
8. What will be the output of the following Java program?

package pkg;
class display
{
int x;
void show()
{
if (x > 1)
System.out.print(x + " ");
}
}
class packages
{
public static void main(String args[])
{
display[] arr=new display[3];
for(int i=0;i<3;i++)
arr[i]=new display();
arr[0].x = 0;
arr[1].x = 1;
arr[2].x = 2;
for (int i = 0; i < 3; ++i)
arr[i].show();
}
}
a) 0
b) 1
c) 2
d) 0 1 2
Answer: c
9. What will be the output of the following Java program?
package pkg;
class output
{
public static void main(String args[])
{
StringBuffer s1 = new StringBuffer("Hello");
s1.setCharAt(1, x);
System.out.println(s1);
}
}
a) xello
b) xxxxx
c) Hxllo
d) Hexlo
Answer: c
10. What will be the output of the following Java program?
package pkg;
class output
{
public static void main(String args[])
{
StringBuffer s1 = new StringBuffer("Hello World");
s1.insert(6 , "Good ");
System.out.println(s1);
}
}
a) HelloGoodWorld
b) HellGoodoWorld
c) Compilation error
d) Runtime error
Answer: d
11. Which of these keywords is used to define interfaces in Java?
a) interface
b) Interface
c) intf
d) Intf
Answer: a
12. 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
Answer: c
13. Which of these access specifiers can be used for an interface?
a) Public
b) Protected
c) private
d) All of the mentioned
Answer: a
14. Which of these keywords is used by a class to use an interface defined previously?
a) import
b) Import
c) implements
d) Implements
Answer: c
15. 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
Answer: b
16. Which of the following is an incorrect statement about packages?
a) Interfaces specifies what class must do but not how it does
b) Interfaces are specified public if they are to be accessed by any code in the program
c) All variables in interface are implicitly final and static
d) All variables are static and methods are public if interface is defined pubic
Answer: d
17. What will be the output of the following Java program?

interface calculate
{
void cal(int item);
}
class display implements calculate
{
int x;
public void cal(int item)
{
x = item * item;
}
}
class interfaces
{
public static void main(String args[])
{
display arr = new display;
arr.x = 0;
arr.cal(2);
System.out.print(arr.x);
}
}
a) 0
b) 2
c) 4
d) None of the mentioned
Answer: c
18. What will be the output of the following Java program?
1 interface calculate
{
void cal(int item);
}
class displayA implements calculate
{
int x;
public void cal(int item)
{
x = item * item;
}
}
class displayB implements calculate
{
int x;
public void cal(int item)
{
x = item / item;
}
}
class interfaces
{
public static void main(String args[])
{
displayA arr1 = new displayA;
displayB arr2 = new displayB;
arr1.x = 0;
arr2.x = 0;
arr1.cal(2);
arr2.cal(2);
System.out.print(arr1.x + " " + arr2.x);
}
}
a) 0 0
b) 2 2
c) 4 1
d) 1 4
Answer: c
19. What will be the output of the following Java program?
interface calculate
{
int VAR = 0;
void cal(int item);
}
class display implements calculate
{
int x;
public void cal(int item)
{
if (item<2)
x = VAR;
else
x = item * item;
}
}
class interfaces
{

public static void main(String args[])


{
display[] arr=new display[3];

for(int i=0;i<3;i++)
arr[i]=new display();
arr[0].cal(0);
arr[1].cal(1);
arr[2].cal(2);
System.out.print(arr[0].x+" " + arr[1].x + " " + arr[2].x);
}
}
a) 0 1 2
b) 0 2 4
c) 0 0 4
d) 0 1 4
Answer: c
21. Which of the following access specifiers can be used for an interface?
a) Protected
b) Private
c) Public
d) Public, protected, private
Answer: a
22. Which of the following is the correct way of implementing an interface A by class B?
a) class B extends A{}
b) class B implements A{}
c) class B imports A{}
d) None of the mentioned
Answer: b
23. All methods must be implemented of an interface.
a) True
b) False
Answer: a
24. What type of variable can be defined in an interface?
a) public static
b) private final
c) public final
d) static final
Answer: d
25. What does an interface contain?
a) Method definition
b) Method declaration
c) Method declaration and definition
d) Method name
Answer: b
26. What type of methods an interface contain by default?
a) abstract
b) static
c) final
d) private
Answer: a
27. What will happen if we provide concrete implementation of method in interface?
a) The concrete class implementing that method need not provide implementation of that method
b) Runtime exception is thrown
c) Compilation failure
d) Method not found exception is thrown
Answer: c
28. What happens when a constructor is defined for an interface?
a) Compilation failure
b) Runtime Exception
c) The interface compiles successfully
d) The implementing class will throw exception
Answer: a
29. What happens when we access the same variable defined in two interfaces implemented
by the same class?
a) Compilation failure
b) Runtime Exception
c) The JVM is not able to identify the correct variable
d) The interfaceName.variableName needs to be defined
Answer: d
30. Can “abstract” keyword be used with constructor, Initialization Block, Instance
Initialization and Static Initialization Block.
a) True
b) False
Answer: b
31. 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
32. 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
33. 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
Answer: a
34. 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
Answer: c
35. Which of this package is used for invoking a method remotely?
a) java.rmi
b) java.awt
c) java.util
d) java.applet
Answer: a
36. What will be the output of the following Java program?
import java.lang.reflect.*;
class Additional_packages
{
public static void main(String args[])
{
try
{
Class c = Class.forName("java.awt.Dimension");
Constructor constructors[] = c.getConstructors();
for (int i = 0; i < constructors.length; i++)
System.out.println(constructors[i]);
}
catch (Exception e)
{
System.out.print("Exception");
}
}
}
a) Program prints all the constructors of ‘java.awt.Dimension’ package
b) Program prints all the possible constructors of class ‘Class’
c) Program prints “Exception”
d) Runtime Error
Answer: a
37. What will be the output of the following Java program?
import java.lang.reflect.*;
class Additional_packages
{
public static void main(String args[])
{
try
{
Class c = Class.forName("java.awt.Dimension");
Field fields[] = c.getFields();
for (int i = 0; i < fields.length; i++)
System.out.println(fields[i]);
}
catch (Exception e)
{
System.out.print("Exception");
}
}
}
a) Program prints all the constructors of ‘java.awt.Dimension’ package
b) Program prints all the methods of ‘java.awt.Dimension’ package
c) Program prints all the data members of ‘java.awt.Dimension’ package
d) program prints all the methods and data member of ‘java.awt.Dimension’ package
Answer: c
38. What is the length of the application box made in the following Java program?
import java.awt.*;
import java.applet.*;
public class myapplet extends Applet
{
Graphic g;
g.drawString("A Simple Applet",20,20);
}
a) 20
b) Default value
c) Compilation Error
d) Runtime Error
Answer: c
39. What will be the output of the following Java program?
import java.lang.reflect.*;
class Additional_packages
{
public static void main(String args[])
{
try
{
Class c = Class.forName("java.awt.Dimension");
Method methods[] = c.getMethods();
for (int i = 0; i < methods.length; i++)
System.out.println(methods[i]);
}
catch (Exception e)
{
System.out.print("Exception");
}
}
}
a) Program prints all the constructors of ‘java.awt.Dimension’ package
b) Program prints all the methods of ‘java.awt.Dimension’ package
c) Program prints all the data members of ‘java.awt.Dimension’ package
d) program prints all the methods and data member of ‘java.awt.Dimension’ package
Answer: b
38. Why are generics used?
a) Generics make code more fast
b) Generics make code more optimised and readable
c) Generics add stability to your code by making more of your bugs detectable at compile
time
d) Generics add stability to your code by making more of your bugs detectable at runtime
Answer: c
39. Which of these type parameters is used for a generic class to return and accept any type
of object?
a) K
b) N
c) T
d) V
Answer: c
40. Which of these type parameters is used for a generic class to return and accept a
number?
a) K
b) N
c) T
d) V
Answer: b
41. Which of these is an correct way of defining generic class?
a) class name(T1, T2, …, Tn) { /* … */ }
b) class name<T1, T2, …, Tn> { /* … */ }
c) class name[T1, T2, …, Tn] { /* … */ }
d) class name{T1, T2, …, Tn} { /* … */ }
Answer: b
42. Which of the following is an incorrect statement regarding the use of generics and
parameterized types in Java?
a) Generics provide type safety by shifting more type checking responsibilities to the compiler
b) Generics and parameterized types eliminate the need for down casts when using Java
Collections
c) When designing your own collections class (say, a linked list), generics and
parameterized types allow you to achieve type safety with just a single class definition as
opposed to defining multiple classes
d) All of the mentioned

Answer: c
43. Which of the following reference types cannot be generic?
a) Anonymous inner class
b) Interface
c) Inner class
d) All of the mentioned
Answer: a
44. What will be the output of the following Java program?

public class BoxDemo


{
public static <U> void addBox(U u, java.util.List<Box<U>> boxes)
{
Box<U> box = new Box<>();
box.set(u);
boxes.add(box);
}
public static <U> void outputBoxes(java.util.List<Box<U>> boxes)
{
int counter = 0;
for (Box<U> box: boxes)
{
U boxContents = box.get();
System.out.println("Box #" + counter + " contains [" + boxContents.toString() +
"]");
counter++;
}
}
public static void main(String[] args)
{
java.util.ArrayList<Box<Integer>> listOfIntegerBoxes = new
java.util.ArrayList<>();
BoxDemo.<Integer>addBox(Integer.valueOf(10), listOfIntegerBoxes);
BoxDemo.outputBoxes(listOfIntegerBoxes);
}
}
a)10
b) Box #0 [10]
c) Box contains [10]
d) Box #0 contains [10
Answer: d

a) 8. What will be the output of the following Java program?


public class BoxDemo
{
public static <U> void addBox(U u,
java.util.List<Box<U>> boxes)
{
Box<U> box = new Box<>();
box.set(u);
boxes.add(box);
}
public static <U> void outputBoxes(java.util.List<Box<U>> boxes)
{
int counter = 0;
for (Box<U> box: boxes)
{
U boxContents = box.get();
System.out.println("[" + boxContents.toString() + "]");
counter++;
}
}
public static void main(String[] args)
{
java.util.ArrayList<Box<Integer>> listOfIntegerBoxes = new
java.util.ArrayList<>();
BoxDemo.<Integer>addBox(Integer.valueOf(0), listOfIntegerBoxes);
BoxDemo.outputBoxes(listOfIntegerBoxes);
}
}
a) 0
b) 1
c) [1]
d) [0]
Answer: d
45. What will be the output of the following Java program?
import java.util.*;
public class genericstack <E>
{
Stack <E> stk = new Stack <E>();
public void push(E obj)
{
stk.push(obj);
}
public E pop()
{
E obj = stk.pop();
return obj;
}
}
class Output
{
public static void main(String args[])
{
genericstack <String> gs = new genericstack<String>();
gs.push("Hello");
System.out.print(gs.pop() + " ");
genericstack <Integer> gs = new genericstack<Integer>();
gs.push(36);
System.out.println(gs.pop());
}
}
a) Error
b) Hello
c) 36
d) Hello 36
Answer: d
46. What will be the output of the following Java program?
public class BoxDemo
{
public static <U> void addBox(U u,
java.util.List<Box<U>> boxes)
{
Box<U> box = new Box<>();
box.set(u);
boxes.add(box);
}
public static <U> void outputBoxes(java.util.List<Box<U>> boxes)
{
int counter = 0;
for (Box<U> box: boxes)
{
U boxContents = box.get();
System.out.println("Box #" + counter + " contains [" + boxContents.toString() +
"]");
counter++;
}
}
public static void main(String[] args)
{
java.util.ArrayList<Box<Integer>> listOfIntegerBoxes = new
java.util.ArrayList<>();
BoxDemo.<Integer>addBox(Integer.valueOf(10), listOfIntegerBoxes);
BoxDemo.outputBoxes(listOfIntegerBoxes);
}
}
a) 10
b) Box #0 [10]
c) Box contains [10]
d) Box #0 contains [10]
Answer: d
47. 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
Answer: b
48. Which of these are types of multitasking?
a) Process based
b) Thread based
c) Process and Thread based
d) None of the mentioned
Answer: c
49. Thread priority in Java is?
a) Integer
b) Float
c) double
d) long
Answer: a
50. 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
Answer: d
51. 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
Answer: d
52. What will be the output of the following Java code?
class multithreaded_programing
{
public static void main(String args[])
{
Thread t = Thread.currentThread();
System.out.println(t);
}
}
a) Thread[5,main]
b) Thread[main,5]
c) Thread[main,0]
d) Thread[main,5,main]
Answer: d
53. What is the name of the thread in the following Java Program?
class multithreaded_programing
{
public static void main(String args[])
{
Thread t = Thread.currentThread();
System.out.println(t);
}
}
a)main
b) Thread
c) System
d) None of the mentioned
Answer: a
54. 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
Answer: b
55. Which of these are types of multitasking?
a) Process based
b) Thread based
c) Process and Thread based
d) None of the mentioned
Answer: c
56 Thread priority in Java is?
a) Integer
b) Float
c) double
d) long
Answer: a

5MARK
1. What is a Java Exception and its Types
2. Explain about try, catch, statements with examples
3.Write a java program to create own exception for Negative Value Exception if the user
enter negative value.
4.Explain Exception handling fundamentals.
5. explain in Uncaught Exception.
6.Short notes on difference between checked and unchecked exceptions?
7.detail about the use of finally statements with examples

10 MARK

1. Explain about creating your own Exception clauses


2. What is Multithreading? What are the ways to create multiple threads in java.
3. Explain about Thread Life Cycle
4. Write a java program to implement inter thread communication
5. Define Daemon Threads? Explain with an example
6. Explain in detail about thread methods?
7. Tell what is synchronization? Give its types and explain
8. Discuss how to set the priority to threads? What are the different ranges.
9. Recall what is package? Explain how to create user defined package in java with
example
10. Write a java program to find the factorial value of the given number using user
defined package concept.
UNIT V
1.Which of these stream contains the classes which can work on character stream?
a) InputStream
b) OutputStream
c) Character Stream
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
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.Which of the following is an incorrect statement about packages?
a) Package defines a namespace in which classes are stored
b) A package can contain other package within it
c) Java uses file system directories to store packages
d) A package can be renamed without renaming the directory in which the classes are
stored
Answer: d
7.Which of the following package stores all the standard java classes?
a) lang
b) java
c) util
d) java.packages
Answer: b
8.What will be the output of the following Java program?

package pkg;
class output
{
public static void main(String args[])
{
StringBuffer s1 = new StringBuffer("Hello World");
s1.insert(6 , "Good ");
System.out.println(s1);
}
}
a) HelloGoodWorld
b) HellGoodoWorld
c) Compilation error
d) Runtime error
Answer: d
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
14. What is the Message is displayed in the applet made by the following Java program?
import java.awt.*;
import java.applet.*;
public class myapplet extends Applet
{
public void paint(Graphics g)
{
g.drawString("A Simple Applet", 20, 20);
}
}
a) A Simple Applet
b) A Simple Applet 20 20
c) Compilation Error
d) Runtime Error
Answer: a
15. What is the length of the application box made by the following Java program?
import java.awt.*;
import java.applet.*;
public class myapplet extends Applet
{
public void paint(Graphics g)
{
g.drawString("A Simple Applet", 20, 20);
}
}
a) 20
b) 50
c) 100
d) System dependent
Answer: a
16. What is the length of the application box made the following Java program?

import java.awt.*;
import java.applet.*;
public class myapplet extends Applet
{
Graphic g;
g.drawString("A Simple Applet", 20, 20);
}
a) 20
b) Default value
c) Compilation Error
d) Runtime Error
Answer: c
17. What will be the output of the following Java program?
import java.io.*;
class Chararrayinput
{
public static void main(String[] args)
{
String obj = "abcdefgh";
int length = obj.length();
char c[] = new char[length];
obj.getChars(0, length, c, 0);
CharArrayReader input1 = new CharArrayReader(c);
CharArrayReader input2 = new CharArrayReader(c, 1, 4);
int i;
int j;
try
{
while((i = input1.read()) == (j = input2.read()))
{
System.out.print((char)i);
}
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
a) abc
b) abcd
c) abcde
d) none of the mentioned
Answer: d
18. 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
19. Which of this class can be used to format dates and times?
a) Date
b) SimpleDate
c) DateFormat
d) textFormat
Answer: c
20. Which of these method returns an instance of DateFormat that can format time
information?
a) getTime()
b) getTimeInstance()
c) getTimeDateinstance()
d) getDateFormatinstance()
Answer: b
21. 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
22. 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?
import java.text.*;
import java.util.*;
class Date_formatting
{
public static void main(String args[])
{
Date date = new Date();
SimpleDateFormat sdf;
sdf = new SimpleDateFormat("mm:hh:ss");
System.out.print(sdf.format(date));
}
}
a) 3:55:4
b) 3.55.4
c) 55:03:04
d) 03:55:04
Answer: c
24. What will be the output of the following Java program?
import java.text.*;
import java.util.*;
class Date_formatting
{
public static void main(String args[])
{
Date date = new Date();
SimpleDateFormat sdf;
sdf = new SimpleDateFormat("hh:mm:ss");
System.out.print(sdf.format(date));
}
}
a) 3:55:4
b) 3.55.4
c) 55:03:04
d) 03:55:04
Answer: d
25. What will be the output of the following Java program?
import java.text.*;
import java.util.*;
class Date_formatting
{
public static void main(String args[])
{
Date date = new Date();
SimpleDateFormat sdf;
sdf = new SimpleDateFormat("E MMM dd yyyy");
System.out.print(sdf.format(date));
}
}
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
26. What will be the output of the following Java program?

import java.text.*;
import java.util.*;
class Date_formatting
{
public static void main(String args[])
{
Date date = new Date();
SimpleDateFormat sdf;
sdf = new SimpleDateFormat("z");
System.out.print(sdf.format(date));
}
}
a) z
b) Jul
c) Mon
d) PDT
Answer: d
27. Which of the following is not a class of java.util.regex?
a) Pattern class
b) matcher class
c) PatternSyntaxException
d) Regex class
Answer: d
28.What is the significance of Matcher class for regular expression in java?
a) interpretes pattern in the string
b) Performs match in the string
c) interpreted both pattern and performs match operations in the string
d) None of the mentioned.
Answer:a
29. Object of which class is used to compile regular expression?
a) Pattern class
b) Matcher class
c) PatternSyntaxException
d) None of the mentioned
Answer: a
30. Which capturing group can represent the entire expression?
a) group *
b) group 0
c) group * or group 0
d) None of the mentioned
Answer: b
Explanation: Group 0 is a special group which represents the entire expression.
31. groupCount reports a total number of Capturing groups.
a) True
b) False
Answer: a
32. Which of the following matches nonword character using regular expression in java?
a) \w
b) \W
c) \s
d) \S
Answer: b
33. Which of the following matches end of the string using regular expression in java?
a) \z
b) \\
c) \*
d) \Z
Answer: a
34. What does public int end(int group) return?
a) offset from last character of the subsequent group
b) offset from first character of the subsequent group
c) offset from last character matched
d) offset from first character matched
Answer: a
35. what does public String replaceAll(string replace) do?
a) Replace all characters that matches pattern with a replacement string
b) Replace first subsequence that matches pattern with a replacement string
c) Replace all other than first subsequence of that matches pattern with a replacement string
d) Replace every subsequence of the input sequence that matches pattern with a
replacement string
Answer: d
36. What does public int start() return?
a) returns start index of the input string
b) returns start index of the current match
c) returns start index of the previous match
d) none of the mentioned
Answer: c
37. Which of these packages contains all the classes and methods required for even
handling in Java?
a) java.applet
b) java.awt
c) java.event
d) java.awt.event
Answer: d
38. What is an event in delegation event model used by Java programming language?
a) An event is an object that describes a state change in a source
b) An event is an object that describes a state change in processing
c) An event is an object that describes any change by the user and system
d) An event is a class used for defining object, to create events
Answer: a
39. Which of these methods are used to register a keyboard event listener?
a) KeyListener()
b) addKistener()
c) addKeyListener()
d) eventKeyboardListener()
Answer: c
40. Which of these methods are used to register a mouse motion listener?
a) addMouse()
b) addMouseListener()
c) addMouseMotionListner()
d) eventMouseMotionListener()
Answer: c
41. What is a listener in context to event handling?
a) A listener is a variable that is notified when an event occurs
b) A listener is a object that is notified when an event occurs
c) A listener is a method that is notified when an event occurs
d) None of the mentioned
Answer: b
42. Event class is defined in which of these libraries?
a) java.io
b) java.lang
c) java.net
d) java.util
Answer: d
43. Which of these methods can be used to determine the type of event?
a) getID()
b) getSource()
c) getEvent()
d) getEventObject()
Answer: a
44. Which of these class is super class of all the events?
a) EventObject
b) EventClass
c) ActionEvent
d) ItemEvent
Answer: a
45. Which of these events will be notified if scroll bar is manipulated?
a) ActionEvent
b) ComponentEvent
c) AdjustmentEvent
d) WindowEvent
Answer: c.
46. Which of these events will be generated if we close an applet’s window?
a) ActionEvent
b) ComponentEvent
c) AdjustmentEvent
d) WindowEvent
Answer: d
47. Which of these keywords is used to define packages in Java?
a) pkg
b) Pkg
c) package
d) Package
Answer: c
48. 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.
Answer: b
49. 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
Answer: d
50. 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
Answer: a.

51. 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.*
Answer: c
5MARK

1.Explain the i/o streams


2.Explain the byte stream
3.Short notes in character streams
4.Explain about applets.
5.Explain the applet life cycle.
6.Short notes in graphics class
7.Short notes in rectangles ,polygon , circles.

10 MARK

1.Detailed about i/o streams


2.Explain about applets.
3.Detailed about graphics.

You might also like