0% found this document useful (0 votes)
237 views

432 Bcs3&Bca31 Java Programming

Uploaded by

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

432 Bcs3&Bca31 Java Programming

Uploaded by

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

THIRUVALLUVAR

UNIVERSITY

E-NOTES

CCS 31– JAVA


PROGRAMMING
(3rd Semester – B.SC CS/BCA)

PREPARED BY

Mr. T. KOSALAIRAMAN, MCA, M.Phil., M.Tech.


Assistant Professor, Department of Computer Science,
RAAK Arts and Science College, Perambai

Mrs. S. RAMYA, M.C.A., M.Phil.


Assistant Professor, Department of Computer Applications,
RAAK Arts and Science College, Perambai.
E-NOTES / B.SC CS /BCA

SYLLABUS

Objectives:
To improve Object Oriented Programming gathered already through an independent
platform.
Unit – I: BASICS, ESSENTIALS, CONTROL STATEMENT AND CLASSES &
OBJECTS
Computer and its Languages – Stage, Origin and Features for Java - JDK–OOP;
JavaEssentials:Program – API - Variables& Literals - Data Types - String Class – Operators -
Type conversion - Constants - Scope – Comments - Keyboard Input; Control
Statements:Conditional Statements – Looping Statements - Break and Continue Statements;
Classesand Objects: Modifiers - Arguments - Constructors - Packages and import - Static
Class -Overloaded Methods and Constructors - Returning Objects – toString() - this reference
–Enumeration - Garbage Collection.

Unit – II: ARRAYS, INHERITANCE, INTERFACES AND PACKAGES


Arrays - Three or More Dimensions; Inheritance: Basics - Calling the SuperclassConstructor
- Overriding Superclass Methods - Inheritance from Subclasses –Polymorphism -Abstract
Classes and Methods - Interfaces: Fields - Multiple inheritance - Interface inheritance;
Packages: Creating packages – Accessing package from otherpackages- Access Specifier.

Unit – III: STRING HANDLING, EXCEPTION HANDLING AND


MULTITHREADING
String Handling: Basics - Operations –String Methods - String Buffer class – StringBuilder –
to String method -String Tokenizer class. Exception Basics: try and catch block- Multiple
catch block - Nested try - throws keyword - Throw vs Throws - Final vsFinally vs Finalize -
Method Overriding - Custom Exception - Multithreading: LifeCycle - Methods in Thread -
thread application – Thread priority – Synchronization -Inter-thread communication -
Suspending, Resuming, and Stopping Threads;

Unit – IV: APPLET AND GUI APPLICATION


Applets: Basis - Lifecycle - Applet classes - Application – Graphics; AWT-I:
GUIProgramming - AWT classes - Windows fundamentals- Creating Windows –
DialogBoxes - Layout Managers - Radio Buttons and Check Boxes – Borders-Swing

Unit – V: JAVA DATABASE CONNECTIVITY


JDBC - Types of Drivers- Architecture- Classes and Interfaces - Developing
JDBCApplication - New Database and Table with JDBC - Working with Database Metadata.

1 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

UNIT I

1. Computer and its language

 Computer language or programming language is a coded syntax used by computer


programmers to communicate with a computer.
 It is the only language that computers, software programs and computer hardware can
understand.
 Computer language establishes a flow of communication between software programs.
 The language enables a computer user to dictate what commands the computer must
perform to process data. Computer language comes in various types that employ
different sets of syntax.

1.1 Low Level Computer Languages


 These are machine codes or close to it. Computer cannot understand instruction given
in high level languages or in English.

 It can only understand and execute instructions given in the form of machine
languages i.e. the binary number 0 and 1.

There are two types of low level computer language.

1.1.1. Machine Language


The lowest and most elementary language and was the first type of programming language to
be developed. Mache language is basically the only language which computer can
understand. In fact, a manufacturer designs a computer to obey just one language, its machine
code, which is represented inside the computer by a string of binary digits (bits) 0 and 1. The
symbol 0 stand for the absence of an electric pulse and 1 for the presence of an electric pulse.
Since a computer is capable of recognizing electric signals, therefore, it understands machine
language.
Advantages
1. It makes fast and efficient use of the computer
2. It requires no translator to translate the code i.e. directly understood by the
computer.

2 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

Disadvantages
1. All operation codes have to be remembered
2. All memory addresses have to be remembered
3. It is hard to amend or find errors in a program written in the machine language
4. These languages are machine dependent i.e. a particular machine language can be
used on only one type of computer.
1.1.2 Assembly Languages
It was developed to overcome some of the many inconveniences of machine language. This
is another low level but a very important language in which operation codes and operands are
given in the form of alphanumeric symbols instead of 0’s and 1’s. These alphanumeric
symbols will be known as mnemonic codes and can have maximum up to 5 letter
combinations e.g. ADD for addition, SUB for subtraction, START LABEL etc. because of
this feature it is also known as “Symbolic Programming Language”. This language is very
difficult and needs a lot of practice to master it because very small English support is given.
This symbolic language helps in compiler orientations. The instructions of the assembly
language will also be converted to machine codes by language translator to be executed by
the computer

Advantages
1. It is easier to understand and use as compared to machine language
2. It is easy to locate and correct errors
3. It is modified easily
Disadvantages
1. Like machine language it is also machine dependent
2. Since it is machine dependent, there programmer should have the knowledge of he
hardware also.

3 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

1.2 High Level Languages


High level computer languages give formats close to English language and the purpose of
developing high level languages is to enable people to write programs easily and in their own
native language environment (English). High-level languages are basically symbolic
languages that use English words and/or mathematical symbols rather than mnemonic codes.
Each instruction in the high level language is translated into many machine language
instructions thus showing one-to-many translation.

 Problem-Oriented Language: These are languages used for handling specialized


types of data processing problems where programmer only specifies the
input/output requirements and other relative information of the problem, that are to
be solved. The programmer does not have to specify the procedure to be followed
in solving that particular problem.
 Procedural Language: These are general purpose languages that are designed to
express the logic of a data processing problem.

4 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

 Non-procedural Language: Computer Programming Languages that allow users


and professional programmers to specify the results they want without specifying
how to solve the problem.
Selection of a Computer Language
There are many high-level languages in use today. The choice of language depends on type
and complexity of the problem.

1. Purpose e.g. business, educational, scientific.


2. Facilities provided e.g. meaningful variable names, control and data structures,
error checking facilities.
3. Ease of learning and use.
4. Portability - if a program is to he used on or in more than one system.
5. Popularity - availability of compilers/interpreters.
6. Documentation provided.
Types of High Level Languages
Many languages have been developed for achieving different variety of tasks, some are fairly
specialized others are quite general purpose. These are categorized according to their use as:

Algebraic Formula-Type Processing. These languages are oriented towards the


computational procedures for solving mathematical and statistical problems. Examples are
1. BASIC (Basic All Purpose Symbolic Instruction Code)
2. FORTRAN (Formula Translation).
3. PL/1 (Programming Language, Version 1).
4. ALGOL (Algorithmic Language).
5. APL (A Programming Language).
Business Data Processing. These languages emphasize their capabilities for maintaining
data processing procedures and files handling problems. Examples are:
1. COBOL (Common Business Oriented Language)
2. RPG (Report Program Generator).
String and List Processing. These are used for string manipulation including search for
patterns, inserting and deleting characters. Examples are: LISP (List Processing).
Multipurpose Language. A general purpose language used for algebraic procedures, data
and string processing. Examples are:
5 BCS 31/BCA 31 – JAVA PROGRAMMING
E-NOTES / B.SC CS /BCA

1. Pascal (after the name of Blaise Pascal).


2. PL/1 (Programming Language, version 1).
3. C language.
Simulation: These may be written in algebraic or multipurpose languages. Examples are:
1. SPSS (Statistical Package System Simulator).
2. GPSS (General Purpose System Simulator).
Advantages: Following are the advantages of a high level language:
1. User-friendly (people based)
2. Similar to English with vocabulary of words awl symbols therefore it is easier to
learn.
3. They require less time to write
4. They are easier to maintain
5. Problem oriented' rather than 'machine' based
6. Shorter than their low-level equivalents. One statement translates into many
machine code instructions.
7. Program written in a high-level equivalent can he translated into many machine
language and therefore can run on every computer for which there exists an
appropriate translator.
8. It is independent of the machine on which it used i.e. programs developed in high
level language can be run on any computer.
Disadvantages: There are certain disadvantages also Inspite these disadvantages high-level
languages have proved their worth. The advantages out-weigh the disadvantages by far, for
most applications. These are:
1. A high-level language has to be translated into the -machine language by a
translator and thus a price in computer time is paid.
2. The object code generated by a translator might be inefficient compared to an
equivalent assembly language program
1.2 Features of Java
 The main objective of Java programming language creation was to make it portable,
simple and secure programming language.
 Apart from this, there are also some awesome features which play important role in
the popularity of this language.
6 BCS 31/BCA 31 – JAVA PROGRAMMING
E-NOTES / B.SC CS /BCA

 The features of Java are also known as java buzzwords. Following is a list of most
important features of Java language.
The Java Features given below are simple and easy to understand.
Simple
 Object-Oriented
 Portable
 Platform independent
 Secured
 Robust
 Architecture neutral
 Dynamic
 Interpreted
 High Performance
 Multithreaded
 Distributed
Simple
Java is very easy to learn and its syntax is simple, clean and easy to understand. According to
Sun, Java language is simple because:
 syntax is based on C++ (so easier for programmers to learn it after C++).
 Removed many confusing and/or rarely-used features e.g., explicit pointers, operator
overloading etc.
 No need to remove unreferenced objects because there is Automatic Garbage
Collection in java.
Object-oriented

 Java is Object-oriented programming language. Everything in Java is an object.


Object-oriented means we organize our software as a combination of different types
of objects that incorporates both data and behaviour.
 Object-oriented programming(OOPs) is a methodology that simplifies software
development and maintenance by providing some rules.

7 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

Basic concepts of OOPs are:

 Object
 Class
 Inheritance
 Polymorphism
 Abstraction
 Encapsulation

Platform Independent
 Java is platform independent because it is different from other languages like C, C++
etc. which are compiled into platform specific machines while Java is a write once,
run anywhere language. A platform is the hardware or software environment in which
a program runs.
 There are two types of platforms software-based and hardware-based. Java provides
software-based platform.
 The Java platform differs from most other platforms in the sense that it is a software-
based platform that runs on the top of other hardware-based platforms.
It has two components:
 Runtime Environment
 API(Application Programming Interface)
 Java code can be run on multiple platforms e.g. Windows, Linux, Sun Solaris,
Mac/OS etc. Java code is compiled by the compiler and converted into bytecode. This
bytecode is a platform-independent code because it can be run on multiple platforms
i.e. Write Once and Run Anywhere(WORA).

Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java is
secured because:
 No explicit pointer
 Java Programs run inside virtual machine sandbox

8 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

 Classloader: Classloader in Java is a part of the Java Runtime Environment(JRE)


which is used to dynamically load Java classes into the Java Virtual Machine. It adds
security by separating the package for the classes of the local file system from those
that are imported from network sources.
 Bytecode Verifier: It checks the code fragments for illegal code that can violate
access right to objects.
 Security Manager: It determines what resources a class can access such as reading and
writing to the local disk.
These security are provided by java language. Some security can also be provided by
application developer through SSL, JAAS, Cryptography etc.

Robust
Robust simply means strong. Java is robust because:
 It uses strong memory management.
 There are lack of pointers that avoids security problem.
 There is automatic garbage collection in java.
 There is exception handling and type checking mechanism in java. All these points
makes java robust.
Architecture-neutral
 Java is architecture neutral because there is no implementation dependent features e.g.
size of primitive types is fixed.
 In C programming, int data type occupies 2 bytes of memory for 32-bit architecture
and 4 bytes of memory for 64-bit architecture. But in java, it occupies 4 bytes of
memory for both 32 and 64 bit architectures.
Portable
 Java is portable because it facilitates you to carry the java bytecode to any platform.
High-performance
 Java is faster than traditional interpretation since bytecode is "close" to native code
still somewhat slower than a compiled language (e.g., C++). Java is an interpreted
language, so it is also a reason that why it is slower than compiled language C, C++.

9 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

Distributed
 Java is distributed because it facilitates us to create distributed applications in java.
RMI and EJB are used for creating distributed applications. We may access files by
calling the methods from any machine on the internet.

Multi-threaded
 A thread is like a separate program, executing concurrently. We can write Java
programs that deal with many tasks at once by defining multiple threads.
 The main advantage of multi-threading is that it doesn't occupy memory for each
thread. It shares a common memory area. Threads are important for multi-media, Web
applications etc.

1.3 Java Development Kit (JDK)


 The Java Development Kit (JDK) is a software development environment used for
developing Java applications and applets. It includes the Java Runtime Environment
(JRE), an interpreter/loader (java), a compiler (javac), an archiver (jar), a
documentation generator (javadoc) and other tools needed in Java development.

 People new to Java may be confused about whether to use the JRE or the JDK. To run
Java applications and applets, simply download the JRE. However, to develop Java
applications and applets as well as run them, the JDK is needed.

 Java developers are initially presented with two JDK tools, java and javac. Both are
run from the command prompt. Java source files are simple text files saved with an
extension of .java. After writing and saving Java source code, the javac compiler is
invoked to create .class files. Once the .class files are created, the 'java' command can
be used to run the java program.

 For developers who wish to work in an integrated development environment (IDE), a


JDK bundled with Netbeans can be downloaded from the Oracle website. Such IDEs
speed up the development process by introducing point-and-click and drag-and-drop
features for creating an application.

10 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

 There are different JDKs for various platforms. The supported platforms include
Windows, Linux and Solaris. Mac users need a different software development kit,
which includes adaptations of some tools found in the JDK.

1.4 OOP Concept


Object means a real word entity such as pen, chair, table etc. Object-Oriented
Programming is a methodology or paradigm to design a program using classes and objects.
It simplifies the software development and maintenance by providing some concepts:
 Object
 Class
 Inheritance
 Polymorphism
 Abstraction
 Encapsulation
Object
 Any entity that has state and behavior is known as an object. For example: chair, pen,
table, keyboard, bike etc. It can be physical and logical.
Class
 Collection of objects is called class. It is a logical entity.
Inheritance
 When one object acquires all the properties and behaviours of parent object i.e.
known as inheritance. It provides code reusability. It is used to achieve runtime
polymorphism.
Polymorphism
 When one task is performed by different ways i.e. known as polymorphism. For
example: to convince the customer differently, to draw something e.g. shape or
rectangle etc.
 In java, we use method overloading and method overriding to achieve polymorphism.
 Another example can be to speak something e.g. cat speaks meaw, dog barks woof
etc.

11 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

Abstraction
 Hiding internal details and showing functionality is known as abstraction. For
example: phone call, we don't know the internal processing.
 In java, we use abstract class and interface to achieve abstraction.

Encapsulation
 Binding (or wrapping) code and data together into a single unit is known as
encapsulation. For example: capsule, it is wrapped with different medicines.
 A java class is the example of encapsulation. Java bean is the fully encapsulated class
because all the data members are private here.

1.5 Java essential


 Java is used to build applications and platforms for a number of devices, including
computers, laptops, gaming consoles, Blu-ray players, car navigation systems,
medical monitoring devices, parking meters, lottery terminals and smartphones.
 It is also a key language for networking, particularly for data centers that store and
transfer Web-based data.

Applets
 Java is also used to create miniature, dynamic programs that run alongside or are
embedded within Web pages.
 These programs are called applets and can be used to display maps, weather, games or
other interactive widgets or tools on a Web page.

Programming
 Based on a C and C++-based syntax, Java is object-oriented and class-based.
 Developers adopt and use Java because code can be run securely on nearly any other
platform, regardless of the operating system or architecture of the device, as long as
the device has a Java Runtime Environment (JRE) installed.

12 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

 The JRE varies depending on the specific type of device, but essentially it runs a
“virtual” machine, or environment, that translates the code into an application or
program.

Java and JavaScript


 Although their names are quite similar and they are both used to create dynamic tools
and games on a Web page, Java and JavaScript are different languages.
 Java is more robust and can be used as the sole programming language for an
application, while JavaScript is a lightweight scripting language that adds
functionality -- like a Java applet -- onto a Web page.
1.6 API

An application programming interface (API), in the context of Java, is a collection of


prewritten packages, classes, and interfaces with their respective methods, fields and
constructors. Similar to a user interface, which facilitates interaction between humans and
computers, an API serves as a software program interface facilitating interaction.

In Java, most basic programming tasks are performed by the API’s classes and packages,
which are helpful in minimizing the number of lines written within pieces of code.

Java Development Kit (JDK) is comprised of three basic components, as follows:

 Java compiler
 Java Virtual Machine (JVM)
 Java Application Programming Interface (API)

The Java API, included with the JDK, describes the function of each of its components. In
Java programming, many of these components are pre-created and commonly used. Thus, the
programmer is able to apply prewritten code via the Java API. After referring to the available
API classes and packages, the programmer easily invokes the necessary code classes and
packages for implementation.

13 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

1.7 Variables
A variable is the name given to a memory location. It is the basic unit of storage in a
program.

 The value stored in a variable can be changed during program execution.


 A variable is only a name given to a memory location, all the operations done on
the variable effects that memory location.
 In Java, all the variables must be declared before they can be used.

Declare variables

We can declare variables in java as follows:

Datatype - Type of data that can be stored in this variable.


variable_name - Name given to the variable.
value - It is the initial value stored in the variable.

1.8 Literals
Literals in java are a sequence of characters(digits, letters and other characters) that
represent constant values to be stored in variables. Java language specifies five major types
of literals. They are

 Interger literals

 Floating point literals


14 BCS 31/BCA 31 – JAVA PROGRAMMING
E-NOTES / B.SC CS /BCA

 Character literals

 String literals

 Boolean literals

1.9 Data types


Data types represent the different values to be stored in the variable. In java, there are two
types of data types:
 Primitive data types
 Non-primitive data types

1.9.1Primitive Data Types


There are eight primitive datatypes supported by Java. Primitive datatypes are predefined by
the language and named by a keyword.

byte
 Byte data type is an 8-bit signed two's complement integer

 Minimum value is -128 (-2^7)

 Maximum value is 127 (inclusive)(2^7 -1)

 Default value is 0

 Byte data type is used to save space in large arrays, mainly in place of integers, since
a byte is four times smaller than an integer.

 Example: byte a = 100, byte b = -50


15 BCS 31/BCA 31 – JAVA PROGRAMMING
E-NOTES / B.SC CS /BCA

short
 Short data type is a 16-bit signed two's complement integer

 Minimum value is -32,768 (-2^15)

 Maximum value is 32,767 (inclusive) (2^15 -1)

 Short data type can also be used to save memory as byte data type. A short is 2 times
smaller than an integer

 Default value is 0.

 Example: short s = 10000, short r = -20000

int
 Int data type is a 32-bit signed two's complement integer.

 Minimum value is - 2,147,483,648 (-2^31)

 Maximum value is 2,147,483,647(inclusive) (2^31 -1)

 Integer is generally used as the default data type for integral values unless there is a
concern about memory.

 The default value is 0

 Example: int a = 100000, int b = -200000

long

 Long data type is a 64-bit signed two's complement integer

 Minimum value is -9,223,372,036,854,775,808(-2^63)

 Maximum value is 9,223,372,036,854,775,807 (inclusive)(2^63 -1)

 This type is used when a wider range than int is needed

 Default value is 0L

 Example: long a = 100000L, long b = -200000L

float
 Float data type is a single-precision 32-bit IEEE 754 floating point

16 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

 Float is mainly used to save memory in large arrays of floating point numbers

 Default value is 0.0f

 Float data type is never used for precise values such as currency

 Example: float f1 = 234.5f

double
 double data type is a double-precision 64-bit IEEE 754 floating point

 This data type is generally used as the default data type for decimal values, generally
the default choice

 Double data type should never be used for precise values such as currency

 Default value is 0.0d

 Example: double d1 = 123.4

boolean

 boolean data type represents one bit of information

 There are only two possible values: true and false

 This data type is used for simple flags that track true/false conditions

 Default value is false

 Example: boolean one = true

char

 char data type is a single 16-bit Unicode character

 Minimum value is '\u0000' (or 0)

 Maximum value is '\uffff' (or 65,535 inclusive)

 Char data type is used to store any character

 Example: char letterA = 'A'

17 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

1.10 String class


 The java.lang.String class provides a lot of methods to work on string. By the help of
these methods, we can perform operations on string such as trimming, concatenating,
converting, comparing, replacing strings etc.

 Java String is a powerful concept because everything is treated as a string if you


submit any form in window based, web based or mobile application.

Important methods of String class.

Java String toUpperCase() and toLowerCase() method

The java string toUpperCase() method converts this string into uppercase letter and string
toLowerCase() method into lowercase letter.

Program:
String s="Sachin";
System.out.println(s.toUpperCase());//SACHIN
System.out.println(s.toLowerCase());//sachin
System.out.println(s);//Sachin(no change in original)

Output
SACHIN
sachin
Sachin
1.11 Operators
Java provides a rich set of operators to manipulate variables. We can divide all the Java
operators into the following groups −

 Arithmetic Operators

 Relational Operators

 Bitwise Operators
18 BCS 31/BCA 31 – JAVA PROGRAMMING
E-NOTES / B.SC CS /BCA

 Logical Operators

 Assignment Operators

 Misc Operators

1.11.1 The Arithmetic Operators


Arithmetic operators are used in mathematical expressions in the same way that they are
used in algebra. The following table lists the arithmetic operators −

Assume integer variable A holds 10 and variable B holds 20, then −

Show Examples

Operator Description Example

+ (Addition) Adds values on either side of the operator. A + B will give 30

Subtracts right-hand operand from left-


- (Subtraction) A - B will give -10
hand operand.

Multiplies values on either side of the


* (Multiplication) A * B will give 200
operator.

Divides left-hand operand by right-hand


/ (Division) B / A will give 2
operand.

Divides left-hand operand by right-hand


% (Modulus) B % A will give 0
operand and returns remainder.

++ (Increment) Increases the value of operand by 1. B++ gives 21

19 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

-- (Decrement) Decreases the value of operand by 1. B-- gives 19

1.11.2 The Relational Operators


There are following relational operators supported by Java language.

Assume variable A holds 10 and variable B holds 20, then −

Show Examples

Operator Description Example

Checks if the values of two operands are equal


== (equal to) (A == B) is not true.
or not, if yes then condition becomes true.

Checks if the values of two operands are equal


!= (not equal to) or not, if values are not equal then condition (A != B) is true.
becomes true.

Checks if the value of left operand is greater


> (greater than) than the value of right operand, if yes then (A > B) is not true.
condition becomes true.

Checks if the value of left operand is less than


< (less than) the value of right operand, if yes then condition (A < B) is true.
becomes true.

Checks if the value of left operand is greater


>= (greater than
than or equal to the value of right operand, if (A >= B) is not true.
or equal to)
yes then condition becomes true.

20 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

Checks if the value of left operand is less than


<= (less than or
or equal to the value of right operand, if yes (A <= B) is true.
equal to)
then condition becomes true.

1.11.3 The Bitwise Operators


Java defines several bitwise operators, which can be applied to the integer types, long, int,
short, char, and byte.

Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60 and b =
13; now in binary format they will be as follows −

a = 0011 1100

b = 0000 1101

a&b = 0000 1100

a|b = 0011 1101

a^b = 0011 0001

~a = 1100 0011

The following table lists the bitwise operators −

Assume integer variable A holds 60 and variable B holds 13 then −

Show Examples

Operator Description Example

& (bitwise Binary AND Operator copies a bit to the (A & B) will give 12 which
and) result if it exists in both operands. is 0000 1100

21 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

Binary OR Operator copies a bit if it exists (A | B) will give 61 which is


| (bitwise or)
in either operand. 0011 1101

^ (bitwise Binary XOR Operator copies the bit if it is (A ^ B) will give 49 which is
XOR) set in one operand but not both. 0011 0001

(~A ) will give -61 which is


~ (bitwise Binary Ones Complement Operator is unary 1100 0011 in 2's
compliment) and has the effect of 'flipping' bits. complement form due to a
signed binary number.

Binary Left Shift Operator. The left


A << 2 will give 240 which
<< (left shift) operands value is moved left by the number
is 1111 0000
of bits specified by the right operand.

Binary Right Shift Operator. The left


>> (right operands value is moved right by the A >> 2 will give 15 which is
shift) number of bits specified by the right 1111
operand.

Shift right zero fill operator. The left


operands value is moved right by the
>>> (zero fill A >>>2 will give 15 which
number of bits specified by the right
right shift) is 0000 1111
operand and shifted values are filled up with
zeros.

22 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

1.11.4The Logical Operators


The following table lists the logical operators −

Assume Boolean variables A holds true and variable B holds false, then −

Show Examples

Operator Description Example

Called Logical AND operator. If both the operands (A && B) is


&& (logical and)
are non-zero, then the condition becomes true. false

Called Logical OR Operator. If any of the two


|| (logical or) operands are non-zero, then the condition becomes (A || B) is true
true.

Called Logical NOT Operator. Use to reverses the


!(A && B) is
! (logical not) logical state of its operand. If a condition is true then
true
Logical NOT operator will make false.

1.11.5The Assignment Operators


Following are the assignment operators supported by Java language −

Show Examples

Operator Description Example

Simple assignment operator. Assigns values from right side C = A +


= operands to left side operand. B will
assign
value of

23 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

A + B
into C

Add AND assignment operator. It adds right operand to the left C += A is


operand and assign the result to left operand. equivalent
+=
to C = C
+A

Subtract AND assignment operator. It subtracts right operand from C -= A is


the left operand and assign the result to left operand. equivalent
-=
to C = C
–A

Multiply AND assignment operator. It multiplies right operand C *= A is


with the left operand and assign the result to left operand. equivalent
*=
to C = C
*A

/= Divide AND assignment operator. It divides left operand with the C /= A is


right operand and assign the result to left operand. equivalent
to C = C /
A

Modulus AND assignment operator. It takes modulus using two C %= A


%= operands and assign the result to left operand. is
equivalent
to C = C

24 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

%A

C <<= 2
is same as
<<= Left shift AND assignment operator.
C = C <<
2

C >>= 2
is same as
>>= Right shift AND assignment operator.
C = C >>
2

C &= 2 is
&= Bitwise AND assignment operator. same as C
=C&2

bitwise exclusive OR and assignment operator. C ^= 2 is


^= same as C
=C^2

bitwise inclusive OR and assignment operator. C |= 2 is


|= same as C
=C|2

25 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

1.11.6 Miscellaneous Operators


There are few other operators supported by Java Language.

Conditional Operator ( ? : )
Conditional operator is also known as the ternary operator. This operator consists of three
operands and is used to evaluate Boolean expressions. The goal of the operator is to decide,
which value should be assigned to the variable.

Syntax:

variable x = (expression) ? value if true : value if false


instance of Operator
This operator is used only for object reference variables. The operator checks whether the
object is of a particular type (class type or interface type).

Syntax:

(Object reference variable) instanceof (class/interface type)

1.12 Type Casting

Assigning a value of one type to a variable of another type is known as Type Casting.
Syntax:
int x = 10;
byte y = (byte)x;

In Java, type casting is classified into two types,

Widening Casting(Implicit)

26 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

Narrowing Casting(Explicitly done)

Automatic Type casting take place when,

 The two types are compatible


 The target type is larger than the source type

Example :

public class Test


{
public static void main(String[] args)
{
int i = 100;
long l = i; //no explicit type casting required
float f = l; //no explicit type casting required
System.out.println("Int value "+i);
System.out.println("Long value "+l);
System.out.println("Float value "+f);
}

}
Output:
Int value 100
Long value 100
Float value 100.0

27 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

Narrowing or Explicit type conversion


When you are assigning a larger type value to a variable of smaller type, then you need to
perform explicit type casting.

Example :

public class Test


{
public static void main(String[] args)
{
double d = 100.04;
long l = (long)d; //explicit type casting required
int i = (int)l; //explicit type casting
required

System.out.println("Double value "+d);


System.out.println("Long value "+l);
System.out.println("Int value "+i);
}

Output:
Double value 100.04
Long value 100
Int value 100
1.13 Constants
A constant is a variable whose value cannot change once it has been assigned.Java doesn't
have built-in support for constants, but the variable modifiers static and final can be used to
effectively create one. Constants can make your program more easily read and understood
by others.

28 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

1.14 Scope of a Variable in Java

 The scope of a variable specifies the region of the source program where that variable
is known, accessible and can be used.

 In Java, the declared variable has a definite scope. When a variable is defined within a
class, its scope determines whether it can be used only within the defined class or
outside of the class also.

 Local variables can be used only within the block in which they are defined.

 The scope of instance variables covers the entire class, so they can be used by any of
the methods within that class.

 Variables must be declared before usage within a scope.

 Variables that are declared in an outer scope can also be used in an inner scope.

 The unique way in which Java checks for the scope of a given variable makes it
possible to create a variable in an inner scope such that a definition of that variable
hides its original value. Program makes this point clear.

1.15 Java Comments

The java comments are statements that are not executed by the compiler and interpreter. The
comments can be used to provide information or explanation about the variable, method,
class or any statement. It can also be used to hide program code for specific time.

Types of Java Comments

There are 3 types of comments in java.

 Single Line Comment


 Multi Line Comment
 Documentation Comment

29 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

1.15.1 Java Single Line Comment

The single line comment is used to comment only one line.

Syntax:

//This is single line comment

Program:

public class CommentExample1


{ public static void main(String[] args)
{
int i=10;//Here, i is a variable
System.out.println(i);
}
}

Output:
10

1.15.2 Java Multi Line Comment

The multi line comment is used to comment multiple lines of code.

Syntax:
/*
This
is
multi line
comment
*/
30 BCS 31/BCA 31 – JAVA PROGRAMMING
E-NOTES / B.SC CS /BCA

Program
public class CommentExample2
{ public static void main(String[] args)
{
/* Let's declare and
print variable in java. */
int i=10;
System.out.println(i);
}
}

Output
10

1.15.3 Java Documentation Comment

The documentation comment is used to create documentation API. To create documentation


API, you need to use javadoc tool.

Syntax:
/**
This
is
documentation
comment
*/
1.16 Keyboard Input(JAVA Scanner class)

 There are various ways to read input from the keyboard, the java.util.Scanner class is
one of them.
 The Java Scanner class breaks the input into tokens using a delimiter that is
whitespace bydefault. It provides many methods to read and parse various primitive
values.

31 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

 Java Scanner class is widely used to parse text for string and primitive types using
regular expression.
 Java Scanner class extends Object class and implements Iterator and Closeable
interfaces.

Commonly used methods of Scanner class

 There is a list of commonly used Scanner class methods:

public String next() It returns the next token from the scanner.

public String nextLine() It moves the scanner position to the next


line and returns the value as a string.

public byte nextByte() It scans the next token as a byte.


public short nextShort() It scans the next token as a short value.

public int nextInt() It scans the next token as an int value.

public long nextLong() It scans the next token as a long value.

public float nextFloat() It scans the next token as a float value.

public double nextDouble() It scans the next token as a double value.

1.17 Control statement (Decision Making)


Decision making structures have one or more conditions to be evaluated or tested by the
program, along with a statement or statements that are to be executed if the condition is
determined to be true, and optionally, other statements to be executed if the condition is
determined to be false.
Following is the general form of a typical decision making structure found in most of the
programming languages

32 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

Java programming language provides following types of decision making statements. Click
the following links to check their detail.

1.17.1 If statement:
An if statement consists of a Boolean expression followed by one or more statements.

Syntax
if(Boolean_expression) {
// Statements will execute if the Boolean expression is true
}

Explanation:
If the Boolean expression evaluates to true then the block of code inside the if statement will
be executed. If not, the first set of code after the end of the if statement (after the closing
curly brace) will be executed.

33 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

Flow Diagram

Example

public class Test {

public static void main(String args[]) {


int x = 10;

if( x < 20 ) {
System.out.print("This is if statement");
}
}
}

Output
This is if statement.

34 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

1.17.2 If…else

An if statement can be followed by an optional else statement, which executes when the
Boolean expression is false.

Syntax

if(Boolean_expression) {
// Executes when the Boolean expression is true
}else {
// Executes when the Boolean expression is false
}

Explanation:

If the boolean expression evaluates to true, then the if block of code will be executed,
otherwise else block of code will be executed.

Flow Diagram

35 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

Example
Live Demo
public class Test {

public static void main(String args[])


{ int x = 30;

if( x < 20 ) {
System.out.print("This is if statement");
}else {
System.out.print("This is else statement");
}
}
}
Output
This is else statement

1.17.3 Switch statement


A switch statement allows a variable to be tested for equality against a list of values. Each
value is called a case, and the variable being switched on is checked for each case.
Syntax
switch(expression) {
case value :
// Statements
break; // optional
case value :
// Statements
break; // optional
// You can have any number of case
statements. default : // Optional
// Statements
}
36 BCS 31/BCA 31 – JAVA PROGRAMMING
E-NOTES / B.SC CS /BCA

The following rules apply to a switch statement −


 The variable used in a switch statement can only be integers, convertable integers
(byte, short, char), strings and enums.
 You can have any number of case statements within a switch. Each case is followed
by the value to be compared to and a colon.
 The value for a case must be the same data type as the variable in the switch and it
must be a constant or a literal.
 When the variable being switched on is equal to a case, the statements following that
case will execute until a break statement is reached.
 When a break statement is reached, the switch terminates, and the flow of control
jumps to the next line following the switch statement.
 Not every case needs to contain a break. If no break appears, the flow of control
will fall through to subsequent cases until a break is reached.
 A switch statement can have an optional default case, which must appear at the end of
the switch. The default case can be used for performing a task when none of the cases
is true. No break is needed in the default case.
Flow Diagram

37 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

Example

public class Test {

public static void main(String args[]) {


// char grade = args[0].charAt(0);
char grade = 'C';

switch(grade)
{ case 'A' :
System.out.println("Excellent!");
break;
case 'B' :
case 'C' :
System.out.println("Well done");
break;
case 'D' :
System.out.println("You passed");
case 'F' :
System.out.println("Better try
again"); break;
default :
System.out.println("Invalid grade");
}
System.out.println("Your grade is " + grade);
}
}

Output

Well done
Your grade is C

38 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

1.18 Looping Statement

A loop statement allows us to execute a statement or group of statements multiple times and
following is the general form of a loop statement in most of the programming languages −

 While loop
 For loop
 Do…while loop

1.18.1 While loop

A while loop statement in Java programming language repeatedly executes a target statement
as long as a given condition is true.

Syntax

while(Boolean_expression) {
// Statements
}
39 BCS 31/BCA 31 – JAVA PROGRAMMING
E-NOTES / B.SC CS /BCA

Explanation:

Here, statement(s) may be a single statement or a block of statements. The condition may be
any expression, and true is any non zero value.

When executing, if the boolean_expression result is true, then the actions inside the loop will
be executed. This will continue as long as the expression result is true.

When the condition becomes false, program control passes to the line immediately following
the loop.

Flow Diagram

Here, key point of the while loop is that the loop might not ever run. When the expression is
tested and the result is false, the loop body will be skipped and the first statement after the
while loop will be executed.

40 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

Example

public class Test {

public static void main(String args[])


{ int x = 10;

while( x < 13 )
{ System.out.print("value of x : " +
x ); x++;
System.out.print("\n");
}
}
}

Output

value of x : 10
value of x : 11
value of x : 12

1.18.2 For loop

 A for loop is a repetition control structure that allows you to efficiently write a loop
that needs to be executed a specific number of times.
 A for loop is useful when you know how many times a task is to be repeated.

Syntax

for(initialization; Boolean_expression; update) {


// Statements
}
41 BCS 31/BCA 31 – JAVA PROGRAMMING
E-NOTES / B.SC CS /BCA

Explanation:

 The initialization step is executed first, and only once. This step allows you to
declare and initialize any loop control variables and this step ends with a semi colon
(;).
 Next, the Boolean expression is evaluated. If it is true, the body of the loop is
executed. If it is false, the body of the loop will not be executed and control jumps to
the next statement past the for loop.
 After the body of the for loop gets executed, the control jumps back up to the update
statement. This statement allows you to update any loop control variables. This
statement can be left blank with a semicolon at the end.
 The Boolean expression is now evaluated again. If it is true, the loop executes and the
process repeats (body of loop, then update step, then Boolean expression). After the
Boolean expression is false, the for loop terminates.
Flow Diagram

42 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

Example
Live Demo
public class Test {

public static void main(String args[]) {

for(int x = 10; x < 13; x = x + 1)


{ System.out.print("value of x : " + x );
System.out.print("\n");
}
}
}

Output
value of x : 10
value of x : 11
value of x : 12

1.18.3 Do…while

A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to
execute at least one time.

Syntax

do {
// Statements
}while(Boolean_expression);

Explanation:

Notice that the Boolean expression appears at the end of the loop, so the statements in the
43 BCS 31/BCA 31 – JAVA PROGRAMMING
E-NOTES / B.SC CS /BCA

loop execute once before the Boolean is tested.


If the Boolean expression is true, the control jumps back up to do statement, and the
statements in the loop execute again. This process repeats until the Boolean expression is
false.
Flow Diagram

Example:

public class Test {

public static void main(String args[])


{ int x = 10;

do {
System.out.print("value of x : " + x );
x++;
System.out.print("\n");
}while( x < 13 );
}
}

44 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

Output:
value of x : 10
value of x : 11
value of x : 12
1.19 Break statement
The break statement in Java programming language has the following two usages −
When the break statement is encountered inside a loop, the loop is immediately terminated
and the program control resumes at the next statement following the loop.
It can be used to terminate a case in the switch statement (covered in the next chapter).
Syntax
break;
Flow Diagram

Example
Live Demo
public class Test {
public static void main(String args[]) {
int [] numbers = {10, 20, 30, 40, 50};
for(int x : numbers ) {
if( x == 30 ) {

45 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

break;
}
System.out.print( x );
System.out.print("\n");
}
}
}
Output
10
20

1.19.1 Continue statement


The continue keyword can be used in any of the loop control structures. It causes the loop to
immediately jump to the next iteration of the loop.
In a for loop, the continue keyword causes control to immediately jump to the update
statement.
In a while loop or do/while loop, control immediately jumps to the Boolean expression.
Syntax
continue;
Flow Diagram

46 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

Example
Live Demo
public class Test {

public static void main(String args[])


{ int [] numbers = {10, 20, 30, 40,
50};

for(int x : numbers )
{ if( x == 30 ) {
continue;
}
System.out.print( x );
System.out.print("\n");
}
}
}
Output
10
20
40
50
1.20 Class and Objects:
 Object − Objects have states and behaviors. Example: A dog has states - color, name,
breed as well as behaviors – wagging the tail, barking, eating. An object is an
instance of a class.

 Class − A class can be defined as a template/blueprint that describes the


behavior/state that the object of its type support.

Objects in Java

 If we consider the real-world, we can find many objects around us, cars, dogs,
humans, etc. All these objects have a state and a behavior.
47 BCS 31/BCA 31 – JAVA PROGRAMMING
E-NOTES / B.SC CS /BCA

 If we consider a dog, then its state is - name, breed, color, and the behavior is -
barking, wagging the tail, running.

 If you compare the software object with a real-world object, they have very similar
characteristics.

 Software objects also have a state and a behavior. A software object's state is stored
in fields and behavior is shown via methods.

 So in software development, methods operate on the internal state of an object and


the object-to-object communication is done via methods.

Classes in Java
A class is a blueprint from which individual objects are created..

Example:
public class Dog {
String breed;
int age;
String color;
void barking() {
}

void hungry() {
}

void sleeping() {
}
}
A class can contain any of the following variable types.

 Local variables − Variables defined inside methods, constructors or blocks are called
local variables. The variable will be declared and initialized within the method and
the variable will be destroyed when the method has completed.

48 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

 Instance variables − Instance variables are variables within a class but outside any
method. These variables are initialized when the class is instantiated. Instance
variables can be accessed from inside any method, constructor or blocks of that
particular class.

1.21 Access Modifiers in Java

Java Modifiers are used to define access to various Java classes and objects, Java functions,
and Java constructors. They are also used to change the meaning of any keyword in Java.

There are 4 types of access modifiers in Java, namely

 Default
 Private
 Protected
 Public

1.21.1 Default Access Modifiers in Java

The default Java Modifier is used to define access when no other modifier is specified for the
class or function, with this modifier they are accessible only within the same package.

1.21.2 Private Access Modifiers in Java

The keyword private Java Modifier is used to define access to a Java datatype or method,
with this it is only accessible in the same class, i.e. any other class of the same package won’t
be able to access it. The keyword used is ‘private’ classes cannot be defined with this access
type.

1.21.3 Protected Access Modifiers in Java

With this keyword, the Java methods or Java datatypes can be accessed within the same
package or subclass of a different package. The keyword used is ‘protected’.

49 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

1.21.4 Public Access Modifiers in Java

In public modifier in java, there is no restriction, i.e. Java datatypes or methods can be
accessed from anywhere in the program. It has the widest scope amongst all the modifiers. It
uses the keyword ‘public’.

1.22 Arguments

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.

Program:

class sam{

public static void main(String args[])

{ System.out.println("Your first argument is:

"+args[0]);

}
1.22 Constructors
Constructors are used to initialize the object’s state. Like methods, a constructor also contains
collection of statements(i.e. instructions) that are executed at time of Object creation.
Each time an object is created using new() keyword at least one constructor (it could be
default constructor) is invoked to assign initial values to the data members of the same class.
Constructor is invoked at the time of object or instance creation. For Example:

50 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

class Geek
{
.......
// A Constructor
new Geek() {}
.......
}
// We can create an object of above class
// using below statement. This statement
// calls above constructor.
Geek obj = new Geek();
Rules for writing Constructor
Constructor(s) of a class must has same name as the class name in which it resides.
A constructor in Java can not be abstract, final, static and Synchronized.
Access modifiers can be used in constructor declaration to control its access i.e which other
class can call the constructor.
1.23 Package and imports
Package are used in Java, in-order to avoid name conflicts and to control access of class,
interface and enumeration etc. A package can be defined as a group of similar types of
classes, interface, enumeration or sub-package. Using package it becomes easier to locate the
related classes and it also provides a good structure for projects with hundreds of classes and
other files.

Types of Packages: Built-in and User defined

Built-in Package: Existing Java package for example java.lang, java.util etc.
User-defined-package: Java package created by user to categorize their project's classes and
interface.

51 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

Creating a package
Creating a package in java is quite easy. Simply include a package command followed by
name of the package as the first statement in java source file.
1.24 static class
 Java allows us to define a class within another class. Such a class is called a nested
class. The class which enclosed nested class is known as Outer class. In java, we can’t
make Top level class static. Only nested classes can be static.
 Following are major differences between static nested class and non-static nested
class. Non-static nested class is also called Inner Class.
 Nested static class doesn’t need reference of Outer class, but Non-static nested class
or Inner class requires Outer class reference.
 Inner class(or non-static nested class) can access both static and non-static members
of Outer class. A static class cannot access non-static members of the Outer class. It
can access only static members of Outer class.
 An instance of Inner class cannot be created without an instance of outer class and an
Inner class can reference data and methods defined in Outer class in which it nests, so
we don’t need to pass reference of an object to the constructor of the Inner class. For
this reason Inner classes can make program simple and concise.

52 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

1.25 Overloaded methods and Constructors


 A method is a set of code that can take arguments, that is values, and do something
with those values. For example, a method in a payroll program could multiply wages
by hours worked. The method then returns the value it comes up with and this value is
sent back to the line of code that called the method.

 You can overload a method in the same way as a constructor. That is, multiple
methods can exist, each with the same name. Remember, though, that they can't have
the same number of arguments or the same type of arguments! Overloading isn't
cloning.

Program:
public double setRate(double c) {
conversionRate = 352.222;
return conversionRate;
}
public double setRate(double c, double m)
{ conversionRate = 352.22;
modifier = .0035;
double newRate = conversionRate * modifier;
return newRate;
}
1.26 Returning objects
 When we pass a primitive type to a method, it is passed by value. But when we pass
an object to a method, the situation changes dramatically, because objects are passed
by what is effectively call-by-reference. Java does this interesting thing that’s sort of a
hybrid between pass-by-value and pass-by-reference. Basically, a parameter cannot be
changed by the function, but the function can ask the parameter to change itself via
calling some method within it.
 While creating a variable of a class type, we only create a reference to an object.
Thus, when we pass this reference to a method, the parameter that receives it will
refer to the same object as that referred to by the argument.
53 BCS 31/BCA 31 – JAVA PROGRAMMING
E-NOTES / B.SC CS /BCA

 This effectively means that objects act as if they are passed to methods by use of call-
by-reference.
 Changes to the object inside the method do reflect in the object used as an argument.

1.27 to string()
 The toString() method returns the string representation of the object.
 If you print any object, java compiler internally invokes the toString() method on the
object. So overriding the toString() method, returns the desired output, it can be the
state of an object etc. depends on your implementation.

Advantage:
 By overriding the toString() method of the Object class, we can return values of the
object, so we don't need to write much code.
Program:
class Student{
int rollno;
String name;
String city;
Student(int rollno, String name, String city)
{ this.rollno=rollno;
this.name=name;
this.city=city;
}
public static void main(String args[]){
Student s1=new Student(101,"Raj","lucknow");
Student s2=new Student(102,"Vijay","ghaziabad");
System.out.println(s1);//compiler writes here s1.toString()
System.out.println(s2);//compiler writes here s2.toString()
}
}
Output:
Student@1fee6fc

54 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

Student@1eed786
1.29 this reference
 There can be a lot of usage of java this keyword. In java, this is a reference
variable that refers to the current object.
Usage of java this keyword
 Here is given the 6 usage of java this keyword.
 this can be used to refer current class instance variable.
 this can be used to invoke current class method (implicitly)
 this() can be used to invoke current class constructor.
 this can be passed as an argument in the method call.
 this can be passed as argument in the constructor call.
 this can be used to return the current class instance from the method.
Suggestion: If you are beginner to java, lookup only three usage of this keyword.

this: to refer current class instance variable


 The this keyword can be used to refer current class instance variable. If there is
ambiguity between the instance variables and parameters, this keyword resolves the
problem of ambiguity.
Program:
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee)
{ rollno=rollno;

55 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

name=name;
fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis1{
public static void main(String args[])
{ Student s1=new
Student(111,"ankit",5000f); Student s2=new
Student(112,"sumit",6000f); s1.display();
s2.display();
}}

Output:
0 null 0.0
0 null 0.0

1.30 Eumeration

Enum in java is a data type that contains fixed set of constants.

It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY and SATURDAY) , directions (NORTH, SOUTH, EAST and
WEST) etc. The java enum constants are static and final implicitly. It is available from JDK
1.5.

Java Enums can be thought of as classes that have fixed set of constants.

 enum improves type safety


 enum can be easily used in switch
 enum can be traversed
 enum can have fields, constructors and methods

56 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

 enum may implement many interfaces but cannot extend any class because it
internally extends Enum clas

Program:

class EnumExample1{
public enum Season { WINTER, SPRING, SUMMER, FALL }

public static void main(String[] args) {


for (Season s : Season.values())
System.out.println(s);

}}

Output:
WINTER
SPRING
SUMMER
FALL
1.31 Garbage Collection
 In java, garbage means unreferenced objects.
 Garbage Collection is process of reclaiming the runtime unused memory
automatically. In other words, it is a way to destroy the unused objects.
 To do so, we were using free() function in C language and delete() in C++. But, in
java it is performed automatically. So, java provides better memory management.
 Advantage of Garbage Collection
 It makes java memory efficient because garbage collector removes the unreferenced
objects from heap memory.
 It is automatically done by the garbage collector(a part of JVM) so we don't need to
make extra efforts.

57 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

How can an object be unreferenced?


There are many ways:
 By nulling the reference
 By assigning a reference to another
 By annonymous object etc
1.31.1 By nulling a reference
Employee e=new Employee();
e=null;
1.31.2 By assigning a reference to
another Employee e1=new
Employee(); Employee e2=new
Employee();
e1=e2;//now the first object referred by e1 is available for garbage collection
1.31.3 By annonymous object
new Employee();

58 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

UNIT I

QUESTION BANK

PART – A
(2 marks)

1. What is Java API?(Apr/May 2019)


2. Differentiate Break() & Continue() statements. (Apr/May 2019)
3. Define the term object. (Nov/Dec 2018).
4. What is Constructor? (Nov/Dec 2018).
5. Define Java.
6. What is the functions of java Virtual Machine?
7. How java differ from C++?
8. What is “System.out.println”?
9. List any four features of java?
10. What is meant by control statements?
11. What is java bytecode?
12. What is an Array?
13. List content of a Java Development Kit.
14. Define the term Variable with example?
15. Write about evolution of java?
16. What is meant by Operator?
17. What is Scanner Class?
18. What is Encapsulation?
19. Mention any four data types in java?
20. List some methods in system class?
21. What is static class?
22. What is the function of print() method?
PART – B
(5 marks)

1. Explain different elements of Java Program.(Apr/May 2019)


2. Write short notes on Access Specifiers. (Apr/May 2019)
3. Write a short note on Integer & floating point constants.(Nov/Dec 2018)
4. Explain Syntax of “Switch” Statements with example program(Nov/Dec 2018)
5. Discuss about java Operator.
6. Briefly explain about the nested if…else statement with example.
7. Discuss various java data types with example.
8. Explain Object Oriented Concepts.
9. How to create and compile a simple java program?
10. Describe about JVM.

59 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

PART – C
(10 marks)

1. Explain various Features of Java. (Apr/May 2019)


2. Discuss on the syntax of while,do-while and for loop statement with
example.(Nov 2018)
3. What are arrays? How to define and access elements?
4. Explain branching statements with suitable examples.
5. What are the various Loop Constructs available in java? Explain
with example.
6. Elaborately describe the control statements.

60 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

UNIT II

2.1 Arrays

 Array is a collection of similar type of elements that have contiguous memory


location.
 Java array is an object that contains elements of similar data type.
 It is a data structure where we store similar elements. We can store only fixed set of
elements in a java array.
 Array in java is index based, first element of the array is stored at 0 index.

Advantage of Java Array

 Code Optimization: It makes the code optimized, we can retrieve or sort the data
easily.
 Random access: We can get any data located at any index position.

Disadvantage of Java Array

 Size Limit: We can store only fixed size of elements in the array. It doesn't grow its
size at runtime. To solve this problem, collection framework is used in java.

Types of Array in java

There are two types of array.

 Single Dimensional Array


 Multidimensional Array

Single Dimensional Array in java

Syntax
dataType[] arr; (or)
dataType []arr; (or)
dataType arr[];

61 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

Instantiation of an Array in java

arrayRefVar=new datatype[size];

Example

class Testarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}

Output:
10
20
70
40
50
Declaration, Instantiation and Initialization of Java Array
int a[]={33,3,4,5};//declaration, instantiation and initialization
Example to print this array.
class Testarray1{
public static void main(String args[]){
int a[]={33,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0;i<a.length;i++)//length is the property of array

62 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

System.out.println(a[i]);
}}
Output:
33
3
4
Passing Array to method
 We can pass the java array to method so that we can reuse the same logic on any
array.

Example

class Testarray2{
static void min(int arr[]){
int min=arr[0];
for(int i=1;i<arr.length;i++)
if(min>arr[i])
min=arr[i];
System.out.println(min);
}
public static void main(String args[]){
int a[]={33,3,4,5};
min(a);//passing array to method
}}
Output:
3
Multidimensional array

 Data is stored in row and column based index (also known as matrix form).

Syntax

dataType[][] arrayRefVar; (or)

63 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

dataType [][]arrayRefVar; (or)


dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];

Example

int[][] arr=new int[3][3];//3 row and 3 column

Example

arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;

Example Program

class Testarray3{
public static void main(String args[]){
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}}

64 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

Output:
123
245
445
Copying a array

 We can copy an array to another by the arraycopy method of System class.

Syntax

public static void arraycopy(

Object src, int srcPos,Object dest, int destPos, int length


)
Example
class TestArrayCopyDemo {
public static void main(String[] args) {
char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',
'i', 'n', 'a', 't', 'e', 'd' };
char[] copyTo = new char[7];
System.arraycopy(copyFrom, 2, copyTo, 0, 7);
System.out.println(new String(copyTo));
}
}

Output: caffeine
Multidimensional Arrays

 It's also possible to create an array of arrays known as multidimensional array. For
example,

int[][] a = new int[3][4];

65 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

 Here, a is a two-dimensional (2d) array. The array can hold maximum of 12 elements
of type int.
 Remember, Java uses zero-based indexing, that is, indexing of arrays in Java starts
with 0 and not 1.
Example

String[][][] personalInfo = new String[3][4][2];

 Here, personalInfo is a 3d array that can hold maximum of 24 (3*4*2) elements of


type String.

How to initialize a 2d array in Java?

Here's an example to initialize a 2d array in Java.


int[][] a = {

{1, 2, 3},
{4, 5, 6, 9},
{7},
};

As mentioned, each component of array a is an array in itself, and length of each rows is also
different.
Let's write a program to prove it.

classMultidimensionalArray{ public

staticvoid main(String[] args){ int[]

[] a ={

{1,2,3},

{4,5,6,9},

66 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

{7},

};

System.out.println("Length of row 1: "+ a[0].length);

System.out.println("Length of row 2: "+ a[1].length);

System.out.println("Length of row 3: "+ a[2].length);

When you run the program, the output will be:

Length of row 1: 3

Length of row 2: 4

Length of row 3: 1

Since each component of a multidimensional array is also an array (a[0], a[1] and a[2]are also
arrays), you can use length attribute to find the length of each rows.

How to initialize a 3d array in Java?

You can initialize 3d array in similar way like a 2d array. Here's an example:

// test is a 3d array

67 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

int[][][] test = {

{1, -2, 3},

{2, 3, 4}

},

{-4, -5, 6, 9},

{1},

{2, 3}

};

Basically, 3d array is an array of 2d arrays.Similar like 2d arrays, rows of 3d arrays can vary
in length.

Example: Program to print elements of 3d array using loop

68 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

class ThreeArray {

public static void main(String[] args) {

// test is a 3d array

int[][][] test = {

{1, -2, 3},

{2, 3, 4}

},

{-4, -5, 6, 9},

{1},

{2, 3}

};

// for..each loop to iterate through elements of 3d array

for (int[][] array2D: test) {

for (int[] array1D: array2D)

{ for(int item: array1D) {

System.out.println(item);

69 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

When you run the program, the output will be:

-2

2.2 Inheritance in Java

Inheritance in java is a mechanism in which one object acquires all the properties and
behaviors of parent object. It is an important part of OPPs(Object Oriented programming
system).

The idea behind inheritance in java is that you can create new classes that are built upon
existing classes. When you inherit from an existing class, you can reuse methods and fields of
parent class, and you can add new methods and fields also.

70 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

Inheritance represents the IS-A relationship, also known as parent-child relationship.

Why use inheritance in java

o For Method Overriding (so runtime polymorphism can be achieved).


o For Code Reusability.

Terms used in Inheritence

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: Superclass 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 previous class.

Syntax of Java Inheritance

class Subclass-name extends Superclass-name


{
//methods and fields
}

Java Inheritance Example

As displayed in the above figure, Programmer is the subclass and Employee is the superclass.
Relationship between two classes is Programmer IS-A Employee.It means that Programmer
is a type of Employee.

class Employee{
float salary=40000;
}
71 BCS 31/BCA 31 – JAVA PROGRAMMING
E-NOTES / B.SC CS /BCA

class Programmer extends Employee{


int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}

Programmer salary is:40000.0


Bonus of programmer is:10000
Types of inheritance in java
 On the basis of class, there can be three types of inheritance in java: single, multilevel
and hierarchical.
 In java programming, multiple and hybrid inheritance is supported through interface
only. We will learn about interfaces later.

Note: Multiple inheritance is not supported in java through class.


When a class extends multiple classes i.e. known as multiple inheritance. For Example:

Single Inheritance Example


File: TestInheritance.java

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
72 BCS 31/BCA 31 – JAVA PROGRAMMING
E-NOTES / B.SC CS /BCA

d.eat();
}}
Output:

barking...
eating...
Multilevel Inheritance Example
File: TestInheritance2.java

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
Output:

weeping...
barking...
eating...
Hierarchical Inheritance Example
File: TestInheritance3.java
73 BCS 31/BCA 31 – JAVA PROGRAMMING
E-NOTES / B.SC CS /BCA

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
Output:

meowing...
eating...
Why multiple inheritance is not supported in java?
To reduce the complexity and simplify the language, multiple inheritance is not supported in
java.

Consider a scenario where A, B and C are three classes. The C class inherits A and B classes.
If A and B classes have same method and you call it from child class object, there will be
ambiguity to call method of A or B class.

Since compile time errors are better than runtime errors, java renders compile time error if
you inherit 2 classes. So whether you have same method or different, there will be compile
time error now.

74 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were

Public Static void main(String args[]){


C obj=new C();
obj.msg();//Now which msg() method would be invoked?
}
}
When use Aggregation?
o Code reuse is also best achieved by aggregation when there is no is-a relationship.
o Inheritance should be used only if the relationship is-a is maintained throughout the
lifetime of the objects involved; otherwise, aggregation is the best choice.

Understanding meaningful example of Aggregation


In this example, Employee has an object of Address, address object contains its own
informations such as city, state, country etc. In such case relationship is Employee HAS-A
address.

Address.java
public class Address
{ String
city,state,country;

public Address(String city, String state, String country) {


this.city = city;
this.state = state;
this.country = country;

75 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

}
Emp.java
public class Emp {
int id;
String name;
Address address;

public Emp(int id, String name,Address address) {


this.id = id;
this.name = name;
this.address=address;
}

void display()
{ System.out.println(id+"
"+name);
System.out.println(address.city+" "+address.state+" "+address.country);
}

public static void main(String[] args) {


Address address1=new Address("gzb","UP","india");
Address address2=new Address("gno","UP","india");

Emp e=new Emp(111,"varun",address1);


Emp e2=new Emp(112,"arun",address2);

e.display();
e2.display();

}
}
76 BCS 31/BCA 31 – JAVA PROGRAMMING
E-NOTES / B.SC CS /BCA

Output:111 varun
gzb UP india
112 arun
gno UP india
2.3 Super keyword in java
 The super keyword in java is a reference variable which is used to refer immediate
parent class object.
 Whenever you create the instance of subclass, an instance of parent class is created
implicitly which is referred by super reference variable.

Usage of java super Keyword


1. super can be used to refer immediate parent class instance variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.

1) super is used to refer immediate parent class instance variable.


We can use super keyword to access the data member or field of parent class. It is used if
parent class and child class have same fields.

class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
77 BCS 31/BCA 31 – JAVA PROGRAMMING
E-NOTES / B.SC CS /BCA

}}
Output:

black
white
In the above example, Animal and Dog both classes have a common property color. If we
print color property, it will print the color of current class by default. To access the parent
property, we need to use super keyword.

super can be used to invoke parent class method


The super keyword can also be used to invoke parent class method. It should be used if
subclass contains the same method as parent class. In other words, it is used if method is
overridden.

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("eating bread...");}
void bark(){System.out.println("barking...");}
void work(){
super.eat();
bark();
}
}
class TestSuper2{
public static void main(String args[]){
Dog d=new Dog();
d.work();
}}
Output:
eating...
barking...
78 BCS 31/BCA 31 – JAVA PROGRAMMING
E-NOTES / B.SC CS /BCA

In the above example Animal and Dog both classes have eat() method if we call eat()
method from Dog class, it will call the eat() method of Dog class by default because
priority is given to local.

To call the parent class method, we need to use super keyword.

super is used to invoke parent class constructor.


The super keyword can also be used to invoke the parent class constructor. Let's see a
simple example:

class Animal{ Animal()


{System.out.println("animal is created");}
}
class Dog extends Animal{
Dog(){
super();
System.out.println("dog is created");
}
}
class TestSuper3{
public static void main(String args[]){
Dog d=new Dog();
}}
Output:

animal is created
dog is created

 If a class inherits a method from its superclass, then there is a chance to override
the method provided that it is not marked final.
 The benefit of overriding is: ability to define a behavior that's specific to the
subclass type, which means a subclass can implement a parent class method based
on its requirement.

79 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

 In object-oriented terms, overriding means to override the functionality of an


existing method.

Example
Let us look at an example.

Live Demo

class Animal {

public void move() {

System.out.println("Animals can move");

class Dog extends Animal

{ public void move() {

System.out.println("Dogs can walk and run");

public class TestDog {

public static void main(String args[]) {

Animal a = new Animal(); // Animal reference and object

Animal b = new Dog(); // Animal reference but Dog object

a.move(); // runs the method in Animal class

b.move(); // runs the method in Dog class

80 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

This will produce the following result −

Output

Animals can move


Dogs can walk and run

In the above example, you can see that even though b is a type of Animal it runs the move
method in the Dog class. The reason for this is: In compile time, the check is made on the
reference type.

2.4 OverridingSuperclass Methods


 The argument list should be exactly the same as that of the overridden method.

 The return type should be the same or a subtype of the return type declared in the
original overridden method in the superclass.

 The access level cannot be more restrictive than the overridden method's access level.
Instance methods can be overridden only if they are inherited by the subclass.

 A method declared final cannot be overridden.

 A method declared static cannot be overridden but can be re-declared.

 If a method cannot be inherited, then it cannot be overridden.

 A subclass within the same package as the instance's superclass can override any
superclass method that is not declared private or final.

 A subclass in a different package can only override the non-final methods declared
public or protected.

 An overriding method can throw any uncheck exceptions, regardless of whether the
overridden method throws exceptions or not

 Constructors cannot be overridden.

2.5 Inheritance from Subclass

81 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

 Inheritance can be defined as the process where one class acquires the properties
(methods and fields) of another. With the use of inheritance the information is made
manageable in a hierarchical order.
 The class which inherits the properties of other is known as subclass (derived class,
child class) and the class whose properties are inherited is known as superclass (base
class, parent class).

extends Keyword

extends is the keyword used to inherit the properties of a class. Following is the syntax of
extends keyword.

Syntax

class Super {
.....
.....
}
class Sub extends Super {
.....
.....
}

Following is an example demonstrating Java inheritance. In this example, you can observe
two classes namely Calculation and My_Calculation.

Using extends keyword, the My_Calculation inherits the methods addition() and
Subtraction() of Calculation class.

2.6 Polymorphism

Polymorphism is the ability of an object to take on many forms. The most common use of
polymorphism in OOP occurs when a parent class reference is used to refer to a child class
object.
Any Java object that can pass more than one IS-A test is considered to be polymorphic. In
Java, all Java objects are polymorphic since any object will pass the IS-A test for their own
type and for the class Object.
It is important to know that the only possible way to access an object is through a reference
variable. A reference variable can be of only one type. Once declared, the type of a reference
variable cannot be changed.

82 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

The reference variable can be reassigned to other objects provided that it is not declared final.
The type of the reference variable would determine the methods that it can invoke on the
object.
A reference variable can refer to any object of its declared type or any subtype of its declared
type. A reference variable can be declared as a class or interface type.
Example
Let us look at an example.
public interface Vegetarian{}
public class Animal{}
public class Deer extends Animal implements Vegetarian{}
Now, the Deer class is considered to be polymorphic since this has multiple inheritance.
Following are true for the above examples −
A Deer IS-A Animal
A Deer IS-A Vegetarian
A Deer IS-A Deer
A Deer IS-A Object
When we apply the reference variable facts to a Deer object reference, the following
declarations are legal −
Example
Deer d = new Deer();
Animal a = d;
Vegetarian v = d;
Object o = d;
All the reference variables d, a, v, o refer to the same Deer object in the heap.
Virtual Methods
In this section, I will show you how the behavior of overridden methods in Java allows you to
take advantage of polymorphism when designing your classes.

We already have discussed method overriding, where a child class can override a method in
its parent. An overridden method is essentially hidden in the parent class, and is not invoked
unless the child class uses the super keyword within the overriding method.

2.7 Abstract class in Java

A class that is declared with abstract keyword, is known as abstract class in java. It can have
abstract and non-abstract methods (method with body).

Before learning java abstract class, let's understand the abstraction in java first.

Abstraction in Java

 Abstraction is a process of hiding the implementation details and showing only


functionality to the user.
83 BCS 31/BCA 31 – JAVA PROGRAMMING
E-NOTES / B.SC CS /BCA

 Another way, it shows only important things to the user and hides the internal details
for example sending sms, you just type the text and send the message. You don't
know the internal processing about the message delivery.
 Abstraction lets you focus on what the object does instead of how it does it.

Ways to achieve Abstraction

There are two ways to achieve abstraction in java

1. Abstract class (0 to 100%)


2. Interface (100%)

Abstract class in Java

A class that is declared as abstract is known as abstract class. It needs to be extended and its
method implemented. It cannot be instantiated.

Example abstract class

1. abstract class A{}

abstract method

A method that is declared as abstract and does not have implementation is known as
abstract method.
Example abstract method

abstract void printStatus();//no body and abstract

Example of abstract class that has abstract method

In this example, Bike the abstract class that contains only one abstract method run. It
implementation is provided by the Honda class.

84 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

abstract class Bike{


abstract void run();
}
class Honda4 extends Bike{
void run(){System.out.println("running safely..");}
public static void main(String args[]){
Bike obj = new Honda4();
obj.run();
}
}

2.8 Interface in Java

 An interface in java is a blueprint of a class. It has static constants and abstract


methods.
 The interface in java is a mechanism to achieve abstraction. There can be only
abstract methods in the java interface not method body. It is used to achieve
abstraction and multiple inheritance in Java.
 Java Interface also represents IS-A relationship.
 It cannot be instantiated just like abstract class.

Why use Java interface?


There are mainly three reasons to use interface. They are given below.

o It is used to achieve abstraction.


o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.

How to declare interface?


Interface is declared by using interface keyword. It provides total abstraction; means all the
methods in interface are declared with empty body and are public and all fields are public,
static and final by default. A class that implement interface must implement all the methods
declared in the interface.

85 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

Syntax:
interface <interface_name>{

// declare constant fields


// declare methods that abstract
// by default.
}
In other words, Interface fields are public, static and final by default, and methods are public
and abstract.

2.9 Multiple inheritance in Java by interface


If a class implements multiple interfaces, or an interface extends multiple interfaces i.e.
known as multiple inheritance.

interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}

public static void main(String args[]){


A7 obj = new A7();
obj.print();
obj.show();
}
}
Output:Hello

86 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

2.10 Interface inheritance


A class implements interface but one interface extends another interface .

interface Printable{
void print();
}
interface Showable extends Printable{
void show();
}
class TestInterface4 implements Showable{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
public static void main(String args[]){
TestInterface4 obj = new TestInterface4();
obj.print();
obj.show();
}
}
Hello
Welcome
Default Method in Interface
Since Java 8, we can have method body in interface. But we need to make it default method.
example:

File: TestInterfaceDefault.java

interface Drawable{
void draw();
default void msg(){System.out.println("default method");}
}
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
87 BCS 31/BCA 31 – JAVA PROGRAMMING
E-NOTES / B.SC CS /BCA

class TestInterfaceDefault{
public static void main(String args[]){
Drawable d=new Rectangle();
d.draw();
d.msg();
}}
drawing rectangle
default method
Static Method in Interface
Since Java 8, we can have static method in interface. Let's see an example:

File: TestInterfaceStatic.java

interface Drawable{
void draw();
static int cube(int x){return x*x*x;}
}
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}

class TestInterfaceStatic{
public static void main(String args[]){
Drawable d=new Rectangle();
d.draw();
System.out.println(Drawable.cube(3));
}}
Output:

drawing rectangle
2.11 Java Package
 A java package is a group of similar types of classes, interfaces and sub-packages.

88 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

 Package in java can be categorized in two form, built-in package and user-defined
package.
 There are many built-in packages such as java, lang, awt, javax, swing, net, io, util,
sql etc.

Advantage of Java Package


1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.

2) Java package provides access protection.

3) Java package removes naming collision.

Simple example of java package


The package keyword is used to create a package in java.

//save as Simple.java
package mypack;
public class Simple{

89 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

public static void main(String args[])


{ System.out.println("Welcome to
package");
}
}

How to compile java package


If you are not using any IDE, you need to follow the syntax given below:

1. javac -d directory javafilename


For example

1. javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file. You can use any
directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to
keep the package within the same directory, you can use . (dot).

How to run java package program


You need to use fully qualified name e.g. mypack.Simple etc to run the class.

To Compile: javac -d . Simple.java


To Run: java mypack.Simple
Output:Welcome to package
The -d is a switch that tells the compiler where to put the class file i.e. it represents
destination. The . represents the current folder.
How to access package from another package?
There are three ways to access the package from outside the package.

1. import package.*;
2. import package.classname;
3. fully qualified name.

90 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but
not subpackages.

The import keyword is used to make the classes and interface of another package accessible
to the current package.

Example of package that import the packagename.*


//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello

2) Using packagename.classname
If you import package.classname then only declared class of this package will be accessible.

Example of package by import package.classname


//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
91 BCS 31/BCA 31 – JAVA PROGRAMMING
E-NOTES / B.SC CS /BCA

}
//save by B.java
package mypack;
import pack.A;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello
3) Using fully qualified name
If you use fully qualified name then only declared class of this package will be accessible.
Now there is no need to import. But you need to use fully qualified name every time when
you are accessing the class or interface.

It is generally used when two packages have same class name e.g. java.util and java.sql
packages contain Date class.

Example of package by import fully qualified name


//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
obj.msg();

92 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

}
}
Output:Hello

Subpackage in java
Package inside the package is called the subpackage. It should be created to categorize the
package further.

Example of Subpackage

package com.javatpoint.core;
class Simple{
public static void main(String args[])
{ System.out.println("Hello
subpackage");
}
}

To Compile: javac -d . Simple.java


To Run: java com.javatpoint.core.Simple
Output:Hello subpackage

Creating a Package
While creating a package, you should choose a name for the package and include
a package statement along with that name at the top of every source file that contains the
classes, interfaces, enumerations, and annotation types that you want to include in the
package.

To compile the Java programs with package statements, you have to use -d option as shown
below.

javac -d Destination_folder file_name.java

93 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

Example

package animals;

interfaceAnimal{ p

ublicvoid eat();

publicvoid travel();

Now, let us implement the above interface in the same package animals −

package animals;

/* File name : MammalInt.java */

public class MammalInt implements Animal {

public void eat()

{ System.out.println("Mammal

eats");

public void travel()

{ System.out.println("Mammal travels");

} public int noOfLegs() {

return 0;

public static void main(String args[]) {


94 BCS 31/BCA 31 – JAVA PROGRAMMING
E-NOTES / B.SC CS /BCA

MammalInt m = new MammalInt();

m.eat();

m.travel();

Now compile the java files as shown below −

$ javac -d . Animal.java
$ javac -d . MammalInt.java

Now a package/folder with the name animals will be created in the current directory and
these class files will be placed in it as shown below.

You can execute the class file within the package and get the result as shown below.

Mammal eats
Mammal travels

95 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

2.12 Access Modifiers in java

1. private access modifier


2. Role of private constructor
3. default access modifier
4. protected access modifier
5. public access modifier
6. Applying access modifier with method overriding

 There are two types of modifiers in java: access modifiers and non-access modifiers.
 The access modifiers in java specifies accessibility (scope) of a data member, method,
constructor or class.

There are 4 types of java access modifiers:

1. private
2. default
3. protected
4. public

There are many non-access modifiers such as static, abstract, synchronized, native,
volatile, transient etc. Here, we will learn access modifiers. 1) private access modifier
The private access modifier is accessible only within class.
Simple example of private access modifier
In this example, we have created two classes A and Simple. A class contains private data
member and private method. We are accessing these private members from outside the
class, so there is compile time error.
class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}

public class Simple{


public static void main(String args[]){
96 BCS 31/BCA 31 – JAVA PROGRAMMING
E-NOTES / B.SC CS /BCA

A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}
Role of Private Constructor
If you make any class constructor private, you cannot create the instance of that class
from outside the class. For example:
class A{
private A(){}//private constructor
void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();//Compile Time Error
}
}

Note: A class cannot be private or protected except nested class.

2) default access modifier


If you don't use any modifier, it is treated as default bydefault. The default modifier is
accessible only within package.

Example of default access modifier


In this example, we have created two packages pack and mypack. We are accessing the
A class from outside its package, since A class is not public, so it cannot be accessed
from outside the package.
//save by A.java
package pack;

97 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

class A{
void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}
In the above example, the scope of class A and its method msg() is default so it cannot be
accessed from outside the package.

3) protected access modifier


 The protected access modifier is accessible within package and outside the package
but through inheritance only.
 The protected access modifier can be applied on the data member, method and
constructor. It can't be applied on the class.

Example of protected access modifier


In this example, we have created the two packages pack and mypack. The A class of pack
package is public, so can be accessed from outside the package. But msg method of this
package is declared as protected, so it can be accessed from outside the class only through
inheritance.

//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
98 BCS 31/BCA 31 – JAVA PROGRAMMING
E-NOTES / B.SC CS /BCA

}
//save by B.java
package mypack;
import pack.*;

class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
Output:Hello

4) public access modifier


The public access modifier is accessible everywhere. It has the widest scope among all
other modifiers.

Example of public access modifier


//save by A.java

package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java

package mypack;
import pack.*;

99 BCS 31/BCA 31 – JAVA PROGRAMMING


E-NOTES / B.SC CS /BCA

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
1.
Output:Hello

10 BCS 31/BCA 31 – JAVA PROGRAMMING


0
E-NOTES / B.SC CS /BCA

UNIT II

QUESTION BANK

PART – A
(2 marks)

1. What is class? Give the general format?


2. What is a recursion function?
3. What are java Objects?
4. Define the term constructor.
5. What is static member?
6. Define string class.
7. Define Wrapper class.
8. What is the task of main () method in java?
9. What is abstract class?
10. Define method\function overloading.
11. Define Inheritance.
12. What is an instance?
13. Define super class and subclass.
14. What is Dynamic binding?
15. What is finalize method()?
PART – B
(5 marks)

1. Define the term static method with an example.


2. How the data could be accessed using abstract class?
3. What are Overriding methods?Give an example.
4. Describe briefly about Wrapper class with example.
5. What is Autoboxing?Compare this with Auto Unboxing.
6. Write a program in java to implement overriding.
7. Describe inner class with example.
8. Write a program in java to count the number of characters in a string.
9. Describe various string manipulation in java.
10. Write a short note in parameterized constructor.

PART – C
(10 marks)
1. Explain types of inheritance with example.
2. What is super class ? Give the limitation in its usage. Develop a program to
show its execution.
3. What is method overloading? Explain by giving a suitable example.
10 BCS 31/BCA 31 – JAVA PROGRAMMING
1
E-NOTES / B.SC CS /BCA

4. Explain the static and finalize methods with suitable example.

UNIT III

3.1 String handling


Basics
Strings, which are widely used in Java programming, are a sequence of characters. In Java
programming language, strings are treated as objects.

The Java platform provides the String class to create and manipulate strings.

Creating Strings
The most direct way to create a string is to write –

String greeting = "Hello world!";

Whenever it encounters a string literal in your code, the compiler creates a String object with
its value in this case, "Hello world!'.

As with any other object, you can create String objects by using the new keyword and a
constructor. The String class has 11 constructors that allow you to provide the initial value
of the string using different sources, such as an array of characters.

Program
public class StringDemo {

public static void main(String args[])

{ char[] helloArray = { 'h', 'e', 'l', 'l', 'o',

'.' };

String helloString = new String(helloArray);

System.out.println( helloString );

Output
hello
Note − The String class is immutable, so that once it is created a String object cannot be
changed. If there is a necessity to make a lot of modifications to Strings of characters, then

10 BCS 31/BCA 31 – JAVA PROGRAMMING


2
E-NOTES / B.SC CS /BCA

you should use String Buffer & String Builder Classes.

3.2 STRING OPERATION

String Length
Methods used to obtain information about an object are known as accessor methods. One
accessor method that you can use with strings is the length() method, which returns the
number of characters contained in the string object.

The following program is an example of length(), method String class.

Program
public class StringDemo {

public static void main(String args[])


{ String palindrome = "Dot saw I was
Tod"; int len = palindrome.length();
System.out.println( "String Length is : " + len );
}
}
Live Demo
Output
String Length is : 17
Concatenating Strings
The String class includes a method for concatenating two strings −

string1.concat(string2);

This returns a new string that is string1 with string2 added to it at the end. You can also use
the concat() method with string literals, as in −

"My name is ".concat("Zara");

Strings are more commonly concatenated with the + operator, as in −

"Hello," + " world" + "!"

which results in −

10 BCS 31/BCA 31 – JAVA PROGRAMMING


3
E-NOTES / B.SC CS /BCA

"Hello, world!"

Program:
Live Demo
public class StringDemo {

public static void main(String args[])


{ String string1 = "saw I was ";
System.out.println("Dot " + string1 + "Tod");
}
}
Output
Dot saw I was Tod
Creating Format Strings
You have printf() and format() methods to print output with formatted numbers. The String
class has an equivalent class method, format(), that returns a String object rather than a
PrintStream object.
3.3 STRING METHODS
String manipulation is arguably one of the most common activities in computer
programming. String class has a variety of methods for string manipulation. We will discuss
basic methods with examples.
public char charAt(int index)
This method requires an integer argument that indicates the position of the character that the
method returns.This method returns the character located at the String's specified index.
Remember, String indexes are zero-based—for example,
String x = "airplane";
System.out.println( x.charAt(2) ); // output is 'r'

public String concat(String s)

This method returns a String with the value of the String passed in to the method appended to
the end of the String used to invoke the method—for example,
String x = "book";
System.out.println( x.concat(" author") ); // output is "book author"

The overloaded + and += operators perform functions similar to the concat()method—


for example,

String x = "library";
System.out.println( x + " card"); // output is "library card"
String x = "United";
x += " States"
System.out.println( x ); // output is "United States"
10 BCS 31/BCA 31 – JAVA PROGRAMMING
4
E-NOTES / B.SC CS /BCA

public boolean equalsIgnoreCase(String s)

This method returns a boolean value (true or false) depending on whether the value of the
String in the argument is the same as the value of the String used to invoke the method. This
method will return true even when characters in the String objects being compared have
differing cases—for example,
String x = "Exit";
System.out.println( x.equalsIgnoreCase("EXIT")); // is
"true" System.out.println( x.equalsIgnoreCase("tixe")); // is
"false"

public int length()

This method returns the length of the String used to invoke the method—for example,
String x = "01234567";
System.out.println( x.length() ); // returns

"8" public String replace(char old, char new)

This method returns a String whose value is that of the String used to invoke the method,
updated so that any occurrence of the char in the first argument is replaced by the char in the
second argument—for example,
String x = "oxoxoxox";
System.out.println( x.replace('x', 'X') ); // output is "oXoXoXoX"

public String substring(int begin)/ public String substring(int begin, int end)

The substring() method is used to return a part (or substring) of the String used to invoke the
method. The first argument represents the starting location (zero-based) of the substring. If
the call has only one argument, the substring returned will include the characters to the end of
the original String. If the call has two arguments, the substring returned will end with the
character located in the nth position of the original String where n is the second argument.
Unfortunately, the ending argument is not zero-based, so if the second argument is 7, the last
character in the returned String will be in the original String's 7 position, which is index 6.
Let's look at some examples:
String x = "0123456789"; // the value of each char is the same as its index!
System.out.println( x.substring(5) ); // output is "56789"
System.out.println( x.substring(5, 8)); // output is "567"

public String toLowerCase()

This method returns a String whose value is the String used to invoke the method, but with
any uppercase characters converted to lowercase—for example,
String x = "A New Java Book";
System.out.println( x.toLowerCase() ); // output is "a new java book"

public String toUpperCase()


10 BCS 31/BCA 31 – JAVA PROGRAMMING
5
E-NOTES / B.SC CS /BCA

This method returns a String whose value is the String used to invoke the method, but with
any lowercase characters converted touppercase—for example,
String x = "A New Java Book";
System.out.println( x.toUpperCase() ); // output is"A NEW JAVA BOOK"

public String trim()

This method returns a String whose value is the String used to invoke the method, but with
any leading or trailing blank spaces removed—for example,
String x = " hi ";
System.out.println( x + "x" ); // result is" hi x"
System.out.println(x.trim() + "x"); // result is "hix"

Program
public class StringMethodsDemo {
public static void main(String[] args) {
String targetString = "Java is fun to learn";
String s1= "JAVA";
String s2= "Java";
String s3 = " Hello Java ";
System.out.println("Char at index 2(third position): " +
targetString.charAt(2));
System.out.println("After Concat: "+ targetString.concat("-Enjoy-"));
System.out.println("Checking equals ignoring case: "
+s2.equalsIgnoreCase(s1));
System.out.println("Checking equals with case: " +s2.equals(s1));
System.out.println("Checking Length: "+ targetString.length());
System.out.println("Replace function: "+ targetString.replace("fun", "easy"));
System.out.println("SubString of targetString: "+ targetString.substring(8));
System.out.println("SubString of targetString: "+ targetString.substring(8,
12));
System.out.println("Converting to lower case: "+ targetString.toLowerCase());
System.out.println("Converting to upper case: "+ targetString.toUpperCase());
System.out.println("Triming string: " + s3.trim());
System.out.println("searching s1 in targetString: " + targetString.contains(s1));
System.out.println("searching s2 in targetString: " + targetString.contains(s2));
char [] charArray = s2.toCharArray();
System.out.println("Size of char array: " + charArray.length);
System.out.println("Printing last element of array: " + charArray[3]);
}
}

10 BCS 31/BCA 31 – JAVA PROGRAMMING


6
E-NOTES / B.SC CS /BCA

Output:

Note
String manipulation is one of the most widely performed activities in java programming
Java library is having various built-in methods like substring, concat, replace, converting to
uppercase or lowercase etc.,
3.4 STRING BUFFERED CLASS
Java StringBuffer class is used to create mutable (modifiable) string. The StringBuffer class
in java is same as String class except it is mutable i.e. it can be changed.

Important Constructors of StringBuffer class


Constructor Description

StringBuffer() creates an empty string buffer with the initial capacity of


16.

StringBuffer(String creates a string buffer with the specified


string. str)

StringBuffer(int creates an empty string buffer with the specified capacity


capacity) as length.

Mutable string
A string that can be modified or changed is known as mutable string. StringBuffer and
StringBuilder classes are used for creating mutable string.
StringBuffer append() method
The append() method concatenates the given argument with this string.
Program
10 BCS 31/BCA 31 – JAVA PROGRAMMING
7
E-NOTES / B.SC CS /BCA

class StringBufferExample{
public static void main(String args[])
{ StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);//prints Hello Java
}}
StringBuffer insert() method
The insert() method inserts the given string with this string at the given position.
Program:
class StringBufferExample2{
public static void main(String args[])
{ StringBuffer sb=new StringBuffer("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}}
StringBuffer replace() method
The replace() method replaces the given string from the specified beginIndex and endIndex.
Program:
class StringBufferExample3{
public static void main(String args[])
{ StringBuffer sb=new
StringBuffer("Hello"); sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}}
StringBuffer delete() method
The delete() method of StringBuffer class deletes the string from the specified beginIndex to
endIndex.
Program:
class StringBufferExample4{
public static void main(String args[])
{ StringBuffer sb=new
StringBuffer("Hello"); sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}
StringBuffer reverse() method
The reverse() method of StringBuilder class reverses the current string.
Program:
class StringBufferExample5{
public static void main(String args[])
{ StringBuffer sb=new
StringBuffer("Hello"); sb.reverse();
System.out.println(sb);//prints olleH
}
}
StringBuffer capacity() method
The capacity() method of StringBuffer class returns the current capacity of the buffer. The
10 BCS 31/BCA 31 – JAVA PROGRAMMING
8
E-NOTES / B.SC CS /BCA

default capacity of the buffer is 16. If the number of character increases from its current
capacity, it increases the capacity by (oldcapacity*2)+2. For example if your current capacity
is 16, it will be (16*2)+2=34.
Program:

class StringBufferExample6{
public static void main(String args[])
{ StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
}}

3.5 StringBuilder class

Java StringBuilder class is used to create mutable (modifiable) string. The Java StringBuilder
class is same as StringBuffer class except that it is non-synchronized. It is available since
JDK 1.5.

Important Constructors of StringBuilder class

Constructor Description

StringBuilder() creates an empty string Builder with the initial


capacity of 16.

StringBuilder(String creates a string Builder with the specified


string. str)

StringBuilder(int creates an empty string Builder


w length)

3.6 toString() method

If you want to represent any object as a string, toString() method comes into existence.

The toString() method returns the string representation of the object.

10 BCS 31/BCA 31 – JAVA PROGRAMMING


9
E-NOTES / B.SC CS /BCA

If you print any object, java compiler internally invokes the toString() method on the object.
So overriding the toString() method, returns the desired output, it can be the state of an object
etc. depends on your implementation.

Advantage of Java toString() method

By overriding the toString() method of the Object class, we can return values of the object, so
we don't need to write much code.

Program:

class Student{

int rollno;

String name;

String city;

Student(int rollno, String name, String city)

{ this.rollno=rollno;

this.name=name;

this.city=city;

public static void main(String args[]){

Student s1=new Student(101,"Raj","lucknow");

Student s2=new Student(102,"Vijay","ghaziabad");

System.out.println(s1);//compiler writes here s1.toString()

System.out.println(s2);//compiler writes here s2.toString()

} }

Output:

Student@1fee6fc

11 BCS 31/BCA 31 – JAVA PROGRAMMING


0
E-NOTES / B.SC CS /BCA

Student@1eed786

3.7 StringTokenizer in Java

The java.util.StringTokenizer class allows you to break a string into tokens. It is simple way
to break string.

It doesn't provide the facility to differentiate numbers, quoted strings, identifiers etc. like
StreamTokenizer class. We will discuss about the StreamTokenizer class in I/O chapter.

Constructors of StringTokenizer class

There are 3 constructors defined in the StringTokenizer class.

Constructor Description

StringTokenizer(String str) creates StringTokenizer with specified string.

StringTokenizer(String str, creates StringTokenizer with specified string and


String delim) delimeter.

StringTokenizer(String str, creates StringTokenizer with specified string, delimeter


String delim, boolean and returnValue. If return value is true, delimiter
returnValue) characters are considered to be tokens. If it is false,
delimiter characters serve to separate tokens.

Program:

import java.util.StringTokenizer;
public class Simple{
public static void main(String args[]){
StringTokenizer st = new StringTokenizer("my name is khan"," ");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}}}

Output:

my
name
is
11 BCS 31/BCA 31 – JAVA PROGRAMMING
1
E-NOTES / B.SC CS /BCA

khan

3.8 String Handling

The exception handling in java is one of the powerful mechanism to handle the runtime errors
so that normal flow of the application can be maintained.

3.9 Try and Catch Block

Java try block is used to enclose the code that might throw an exception. It
must be used within the method. Java try block must be followed by either
catch or finally block.
Syntax

try{
//code that may throw exception
}catch(Exception_class_Name ref){}

Catch Block
Java catch block is used to handle the Exception. It must be used after the try
block only.You can use multiple catch block with a single try.

3.10 Multi catch block

If you have to perform different tasks at the occurrence of different Exceptions, use java
multi catch block.

Program:

public class
TestMultipleCatchBlock{ public static
void main(String args[]){ try{
int a[]=new int[5];
a[5]=30/0;
}
catch(ArithmeticException e){System.out.println("task1 is completed");}
catch(ArrayIndexOutOfBoundsException e){System.out.println("task 2 completed");}
catch(Exception e){System.out.println("common task completed");}
System.out.println("rest of the code...");
}}

11 BCS 31/BCA 31 – JAVA PROGRAMMING


2
E-NOTES / B.SC CS /BCA

3.11 Nested try block

The try block within a try block is known as nested try block in java.

Syntax:

try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
}
}
catch(Exception e)
{
}

Program:

class Excep6{
public static void main(String args[])
{ try{
try{
System.out.println("going to divide");
int b =39/0;
}catch(ArithmeticException e){System.out.println(e);}

try{
int a[]=new int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e){System.out.println(e);}

System.out.println("other statement);
11 BCS 31/BCA 31 – JAVA PROGRAMMING
3
E-NOTES / B.SC CS /BCA

}catch(Exception e){System.out.println("handeled");}

System.out.println("normal flow..");
}
}

3.12 throw keyword

The Java throw keyword is used to explicitly throw an exception.

We can throw either checked or uncheked exception in java by throw keyword. The throw
keyword is mainly used to throw custom exception. We will see custom exceptions later.

Syntax

throw exception;

Program:

public class
TestThrow1{ static void
validate(int age)
{ if(age<18)
throw new ArithmeticException("not valid");
else
System.out.println("welcome to vote");
}
public static void main(String args[])
{ validate(13);
System.out.println("rest of the code...");
}
}

3.13 throw vs throws

There are many differences between throw and throws keywords. A list of differences
between throw and throws are given below:

No. throw throws

1) Java throw keyword is used to Java throws keyword is used to declare


explicitly throw an exception. an exception.

11 BCS 31/BCA 31 – JAVA PROGRAMMING


4
E-NOTES / B.SC CS /BCA

2) Checked exception cannot be Checked exception can be propagated


propagated using throw only. with throws.

3) Throw is followed by an Throws is followed by class.


instance.

4) Throw is used within the Throws is used with the method


method. signature.

5) You cannot throw multiple You can declare multiple exceptions


exceptions. e.g.
public void method()throws
IOException,SQLException.

3.14 final Vs finally Vs finalize

There are many differences between final, finally and finalize. A list of differences between
final, finally and finalize are given below:

No. Final finally finalize

1) Final is used to apply Finally is used to Finalize is used to


restrictions on class, method place important perform clean up
and variable. Final class can't code, it will be processing just
be inherited, final method executed whether before object is
can't be overridden and final exception is garbage collected.
variable value can't be handled or not.
changed.

2) Final is a keyword. Finally is a block. Finalize is a


method.

3.15 Method Overriding

If subclass (child class) has the same method as declared in the parent class, it is known as
method overriding in java.

11 BCS 31/BCA 31 – JAVA PROGRAMMING


5
E-NOTES / B.SC CS /BCA

In other words, If subclass provides the specific implementation of the method that has been
provided by one of its parent class, it is known as method overriding.

Usage of Java Method Overriding

 Method overriding is used to provide specific implementation of a method that is


already provided by its super class.
 Method overriding is used for runtime polymorphism
Rules for Java Method Overriding

 Method must have same name as in the parent class


 Method must have same parameter as in the parent class.
 Must be IS-A relationship (inheritance).

Program

class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
class Bike extends Vehicle{

public static void main(String args[])


{ Bike obj = new Bike();
obj.run();
}
}

Output:

Vehicle is running

3.16 custom exception

If you are creating your own Exception that is known as custom exception or user-defined
exception. Java custom exceptions are used to customize the exception according to user
need.

By the help of custom exception, you can have your own exception and

message. Program:
class TestCustomException1{

static void validate(int age)throws


InvalidAgeException{ if(age<18)
throw new InvalidAgeException("not valid");
else
System.out.println("welcome to vote");
11 BCS 31/BCA 31 – JAVA PROGRAMMING
6
E-NOTES / B.SC CS /BCA

public static void main(String args[])


{ try{
validate(13);
}catch(Exception m){System.out.println("Exception occured: "+m);}

System.out.println("rest of the code...");


}
}

3.17 Multithreading

 Multithreading in java is a process of executing multiple threads simultaneously.


 Thread is basically a lightweight sub-process, a smallest unit of processing.
Multiprocessing and multithreading, both are used to achieve multitasking.
 But we use multithreading than multiprocessing because threads share a common
memory area. They don't allocate separate memory area so saves memory, and
context-switching between the threads takes less time than process.
 Java Multithreading is mostly used in games, animation etc.

Advantages of Java Multithreading

 It doesn't block the user because threads are independent and you can perform
multiple operations at same time.

 You can perform many operations together so it saves time.

 Threads are independent so it doesn't affect other threads if exception occur in a single
thread.

Multitasking

Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to


utilize the CPU. Multitasking can be achieved by two ways:

 Process-based Multitasking(Multiprocessing)
 Thread-based Multitasking(Multithreading)

Process-based Multitasking (Multiprocessing)


 Each process have its own address in memory i.e. each process allocates separate
memory area.
 Process is heavyweight.
 Cost of communication between the process is high.
 Switching from one process to another require some time for saving and loading
registers, memory maps, updating lists etc.

11 BCS 31/BCA 31 – JAVA PROGRAMMING


7
E-NOTES / B.SC CS /BCA

Thread-based Multitasking (Multithreading)

 Threads share the same address space.


 Thread is lightweight.
 Cost of communication between the thread is low.
What is Thread in java

A thread is a lightweight sub process, a smallest unit of processing. It is a separate path of


execution.

Threads are independent, if there occurs exception in one thread, it doesn't affect other
threads. It shares a common memory area.

3.18 Life cycle of a Thread

A thread can be in one of the five states. According to sun, there is only 4 states in thread life
cycle in javanew, runnable, non-runnable and terminated. There is no running state.

But for better understanding the threads, we are explaining it in the 5 states.

The life cycle of the thread in java is controlled by JVM. The java thread states are as
follows:

 New
 Runnable
 Running
 Non-Runnable (Blocked)
 Terminated

11 BCS 31/BCA 31 – JAVA PROGRAMMING


8
E-NOTES / B.SC CS /BCA

New

The thread is in new state if you create an instance of Thread class but before the invocation
of start() method.

 Runnable

The thread is in runnable state after invocation of start() method, but the thread scheduler has
not selected it to be the running thread.

 Running

The thread is in running state if the thread scheduler has selected it.

 Non-Runnable (Blocked)

This is the state when the thread is still alive, but is currently not eligible to run.

 Terminated

A thread is in terminated or dead state when its run() method exits.


11 BCS 31/BCA 31 – JAVA PROGRAMMING
9
E-NOTES / B.SC CS /BCA

3.19 Methods in thread

public void run(): is used to perform action for a thread.

public void start(): starts the execution of the thread.JVM calls the run() method on the
thread.

public void sleep(long miliseconds): Causes the currently executing thread to sleep
(temporarily cease execution) for the specified number of milliseconds.

public void join(): waits for a thread to die.

public void join(long miliseconds): waits for a thread to die for the specified miliseconds.

public int getPriority(): returns the priority of the thread.

public int setPriority(int priority): changes the priority of the thread.

public String getName(): returns the name of the thread.

public void setName(String name): changes the name of the thread.

public Thread currentThread(): returns the reference of currently executing thread.

public int getId(): returns the id of the thread.

public Thread.State getState(): returns the state of the thread.

public boolean isAlive(): tests if the thread is alive.

public void yield(): causes the currently executing thread object to temporarily pause and
allow other threads to execute.

public void suspend(): is used to suspend the thread(depricated).

public void resume(): is used to resume the suspended thread(depricated).

public void stop(): is used to stop the thread(depricated).

public boolean isDaemon(): tests if the thread is a daemon thread.

public void setDaemon(boolean b): marks the thread as daemon or user thread.

12 BCS 31/BCA 31 – JAVA PROGRAMMING


0
E-NOTES / B.SC CS /BCA

public void interrupt(): interrupts the thread.

public boolean isInterrupted(): tests if the thread has been interrupted.

public static boolean interrupted(): tests if the current thread has been interrupted.

3.20 Thread Application

 The users are not blocked because threads are independent, and we can perform
multiple operations at times
 As such the threads are independent, the other threads won't get affected if one thread
meets an exception.

3.21 Priority of a Thread

Each thread have a priority. Priorities are represented by a number between 1 and 10. In most
cases, thread schedular schedules the threads according to their priority (known as
preemptive scheduling). But it is not guaranteed because it depends on JVM specification that
which scheduling it chooses.

Three constants defined in Thread class:


1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int MAX_PRIORIT

Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1


and the value of MAX_PRIORITY is 10.
Program:
class TestMultiPriority1 extends
Thread{ public void run(){
System.out.println("running thread name is:"+Thread.currentThread().getName());
System.out.println("running thread priority is:"+Thread.currentThread().getPriority());
}
public static void main(String args[])
{ TestMultiPriority1 m1=new
TestMultiPriority1(); TestMultiPriority1
m2=new TestMultiPriority1();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
}
}
Output:
12 BCS 31/BCA 31 – JAVA PROGRAMMING
1
E-NOTES / B.SC CS /BCA

running thread name is:Thread-0


running thread priority is:10
running thread name is:Thread-1
running thread priority is:1
3.22 Synchronization

Synchronization in java is the capability to control the access of multiple threads to any
shared resource.
Java Synchronization is better option where we want to allow only one thread to access the
shared resource.

Use of synchronization

The synchronization is mainly used to

 To prevent thread interference.


 To prevent consistency problem.

Types of Synchronization
There are two types of synchronization
 Process Synchronization
 Thread Synchronization
 Thread Synchronization

Program:
class Table{
void printTable(int n){//method not synchronized
for(int i=1;i<=5;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}
}
}
class MyThread1 extends Thread{
Table t;
MyThread1(Table t){
this.t=t;
}
public void run()
{ t.printTable(5);
}
}
class MyThread2 extends
Thread{ Table t;
12 BCS 31/BCA 31 – JAVA PROGRAMMING
2
E-NOTES / B.SC CS /BCA

MyThread2(Table t){
this.t=t;
}
public void run()
{ t.printTable(100);
}
}
class TestSynchronization1{
public static void main(String args[])
{ Table obj = new Table();//only one
object MyThread1 t1=new
MyThread1(obj); MyThread2 t2=new
MyThread2(obj); t1.start();
t2.start();
}
}
Output
5
100
10
200
15
300
20
400
25
500

3.23 Inter-thread communication in Java

Inter-thread communication or Co-operation is all about allowing synchronized threads to


communicate with each other.

Cooperation (Inter-thread communication) is a mechanism in which a thread is paused


running in its critical section and another thread is allowed to enter (or lock) in the same
critical section to be executed.It is implemented by following methods of Object class:

 wait()
 notify()
 notifyAll()

wait() method

Causes current thread to release the lock and wait until either another thread invokes the
notify() method or the notifyAll() method for this object, or a specified amount of time has
elapsed.
12 BCS 31/BCA 31 – JAVA PROGRAMMING
3
E-NOTES / B.SC CS /BCA

The current thread must own this object's monitor, so it must be called from the synchronized
method only otherwise it will throw exception.

Method Description

public final void wait()throws waits until object is notified.


InterruptedException

public final void wait(long timeout)throws waits for the specified


InterruptedException amount of time.

notify() method

Wakes up a single thread that is waiting on this object's monitor. If any threads are waiting on
this object, one of them is chosen to be awakened. The choice is arbitrary and occurs at the
discretion of the implementation.

Syntax:

public final void notify()

notifyAll() method

Wakes up all threads that are waiting on this object's monitor.

Syntax:

public final void notifyAll()

3.24 Suspending, Resuming and Stopping Thread

Core Java provides complete control over multithreaded program. You can develop a
multithreaded program which can be suspended, resumed, or stopped completely based on
your requirements. There are various static methods which you can use on thread objects to
control their behavior. Following table lists down those methods −
Sr.No. Method & Description

1 public void suspend()

This method puts a thread in the suspended state and can

12 BCS 31/BCA 31 – JAVA PROGRAMMING


4
E-NOTES / B.SC CS /BCA

be resumed using resume() method.

2 public void stop()

This method stops a thread completely.

3 public void resume()

This method resumes a thread, which was suspended using


suspend() method.

4 public void wait()

Causes the current thread to wait until another thread


invokes the notify().

5 public void notify()

Wakes up a single thread that is waiting on this object's


monitor.

UNIT III QUESTION BANK

PART – A
(2 marks)

1. Define string.
2. Define an buffer
class.
3. Give the meaning for synchronization in java.(Nov 2012)
4. Define thread? Give example.(April 2011)
5. What is the use of thread class?(April 2013)
6. What are the events to be implemented to handle mouse events?(April 2013)
7. Define event sources.
8. What is meant by event listeners?
9. What is meant by event classes?
10. What is GUI?

12 BCS 31/BCA 31 – JAVA PROGRAMMING


5
E-NOTES / B.SC CS /BCA

11. List out some of the GUI based applications.


12. List out any two advantages of GUI.
13. What is a thread?
14. What is a component class in GUI?
15. Define try block.
16. What is final keyword?(April 2014)
17. What is the use finally keyword?(April 2014,April/May 2015)
18. How to define try and catch block?(April 2014)

PART – B
(5 marks)

1. Briefly explain string classes in java.(Nov 2012)


2. Write a note on buffer class with example.(Nov 2012)
3. Explain about five string classes available in java.
4. What is an thread? Explain it types.(Nov 2011,April 2012,April 2014)
5. Describe any five thread application.(April 2011)
6. Discuss the functions of string.
7. Write the java code to implement the use of try and catch.(April 2013)
8. Difference between final finally and finalize keyword.
9. How to implement try and catch?(April 2014)

PART – C
(10 marks)

1. Discuss the various thread process in java.(Nov 2012)


2. Discuss the different types of synchronization.(April 2011, April 2012)
3. Explain the multithreading.(April 2013)
4. Explain thread life cycle.(April 2014)

12 BCS 31/BCA 31 – JAVA PROGRAMMING


6
E-NOTES / B.SC CS /BCA
UNIT IV

APPLETS AND GUI

1. APPLET FUNDAMENTALS

Applet is a special type of program that is embedded in the webpage to generate the
dynamic content. It runs inside the browser and works at client side.

Advantage of Applet

There are many advantages of applet. They are as follows:

2. It works at client side so less response time.

3. Secured

4. It can be executed by browsers running under many plateforms, including Linux, Windows,
Mac Os etc.

Drawback of Applet

5. Plugin is required at client browser to execute applet.

Hierarchy of Applet

As displayed in the above diagram, Applet class extends Panel. Panel class extends Container which is the subclass
of Component.

1. THE APPLET CLASS


Every applet is an extension of the java.applet.Applet class. The base Applet class provides
methods that a derived Applet class may call to obtain information and services from the
browser context.
These include methods that do the following −

1. Get applet parameters


2. Get the network location of the HTML file that contains the applet
3. Get the network location of the applet class directory
4. Print a status message in the browser
5. Fetch an image
6. Fetch an audio clip
7. Play an audio clip
8. Resize the applet
Additionally, the Applet class provides an interface by which the viewer or browser obtains
information about the applet and controls the applet's execution. The viewer may −

9. Request information about the author, version, and copyright of the applet
10. Request a description of the parameters the applet recognizes
11. Initialize the applet
12. Destroy the applet
13. Start the applet's execution
14. Stop the applet's execution
The Applet class provides default implementations of each of these methods. Those
implementations may be overridden as necessary.

The "Hello, World" applet is complete as it stands. The only method overridden is the paint
method.
Lifecycle of Java Applet
6. Applet is initialized.
7. Applet is started.
8. Applet is painted.
9. Applet is stopped.
10. Applet is destroyed.
Lifecycle methods for Applet:
The java.applet.Applet class 4 life cycle methods and java.awt.Component class provides 1 life cycle
methods for an applet.

java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle methods of
applet.

1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is maximized. It is used to start the
Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser is
minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.
5. paint − Invoked immediately after the start() method, and also any time the applet needs to repaint itself
in the browser. The paint() method is actually inherited from the java.awt.

A "Hello, World" Applet


Following is a simple applet named HelloWorldApplet.java −
import java.applet.*;
import java.awt.*;

public class HelloWorldApplet extends Applet {


public void paint (Graphics g) {
g.drawString ("Hello World", 25, 50);
6. }

An applet is a Java program that runs in a Web browser. An applet can be a fully functional
Java application because it has the entire Java API at its disposal.
There are some important differences between an applet and a standalone Java application,
including the following −
1. An applet is a Java class that extends the java.applet.Applet class.
2. A main() method is not invoked on an applet, and an applet class will not define
main().
3. Applets are designed to be embedded within an HTML page.
4. When a user views an HTML page that contains an applet, the code for the
applet is downloaded to the user's machine.
5. A JVM is required to view an applet. The JVM can be either a plug-in of the
Web browser or a separate runtime environment.
12 BCS 31/BCA 31 – JAVA PROGRAMMING
7
E-NOTES / B.SC CS /BCA

 The JVM on the user's machine creates an instance of the applet class and invokes
various methods during the applet's lifetime.
 Applets have strict security rules that are enforced by the Web browser. The security
of an applet is often referred to as sandbox security, comparing the applet to a child
playing in a sandbox with various rules that must be followed.
 Other classes that the applet needs can be downloaded in a single Java Archive (JAR)
file.

4.2 LIFE CYCLE OF AN APPLET


Four methods in the Applet class gives you the framework on which you build any serious
applet −
 init − This method is intended for whatever initialization is needed for your applet. It
is called after the param tags inside the applet tag have been processed.
 start − This method is automatically called after the browser calls the init method. It
is also called whenever the user returns to the page containing the applet after having
gone off to other pages.
 stop − This method is automatically called when the user moves off the page on
which the applet sits. It can, therefore, be called repeatedly in the same applet.
 destroy − This method is only called when the browser shuts down normally.
Because applets are meant to live on an HTML page, you should not normally leave
resources behind after a user leaves the page that contains the applet.
 paint − Invoked immediately after the start() method, and also any time the applet
needs to repaint itself in the browser. The paint() method is actually inherited from
the java.awt.

A "Hello, World" Applet


Following is a simple applet named HelloWorldApplet.java −
import java.applet.*;
import java.awt.*;

public class HelloWorldApplet extends Applet {


public void paint (Graphics g) {
g.drawString ("Hello World", 25, 50);
}
12 BCS 31/BCA 31 – JAVA PROGRAMMING
8
E-NOTES / B.SC CS /BCA

}
These import statements bring the classes into the scope of our applet class −

 java.applet.Applet
 java.awt.Graphics
Without those import statements, the Java compiler would not recognize the classes Applet
and Graphics, which the applet class refers to.

STEPS FOR DEVELOPING APPLET PROGRAMS

1. Execution of applets is easy in a Web browser and does not require any
installation or deployment procedure in realtime programming (where as servlets
require).
2. Writing and displaying (just opening in a browser) graphics and animations is easier than
applications.
3. In GUI development, constructor, size of frame, window closing code etc. are not
required (but are required in applications).

How to run an Applet?


There are two ways to run an applet

1. By html file.
2. By appletViewer tool (for testing purpose).

Simple example of Applet by html file:


To execute the applet by html file, create an applet and compile it. After that create an html file and
place the applet code in html file. Now click the html file.

1. //First.java
2. import java.applet.Applet;
3. import java.awt.Graphics;
4. public class First extends Applet{
5.
6. public void paint(Graphics g){
7. g.drawString("welcome",150,150);
8. }
9.
10. }
Note: class must be public because its object is created by Java Plugin software that resides on
the browser.
myapplet.html

1. <html>
2. <body>
3. <applet code="First.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>

Simple example of Applet by appletviewer tool:


To execute the applet by appletviewer tool, create an applet that contains applet tag in comment and
compile it. After that run it by: appletviewer First.java. Now Html file is not required but it is for
testing purpose only.

1. //First.java
2. import java.applet.Applet;
3. import java.awt.Graphics;
4. public class First extends Applet{
5.
6. public void paint(Graphics g){
7. g.drawString("welcome to applet",150,150);
8. }
9.
10. }
11. /*
12. <applet code="First.class" width="300" height="300">
13. </applet>
14. */

To execute the applet by appletviewer tool, write in command prompt:

c:\>javac First.java
c:\>appletviewer First.java
Parameter in Applet
We can get any information from the HTML file as a parameter. For this purpose, Applet class
provides a method named getParameter(). Syntax:

1. public String getParameter(String parameterName)
Example of using parameter in Applet:
1. import java.applet.Applet;
2. import java.awt.Graphics;
3.
4. public class UseParam extends Applet{
5.
6. public void paint(Graphics g){
7. String str=getParameter("msg");
8. g.drawString(str,50, 50);
9. }
10.
11. }
myapplet.html
1. <html>
2. <body>
3. <applet code="UseParam.class" width="300" height="300">
4. <param name="msg" value="Welcome to applet">
5. </applet>
6. </body>
7. </html>

Graphics in Applet

java.awt.Graphics class provides many methods for graphics programming.


 public abstract void drawString(String str, int x, int y): is used to draw the specified
string.
 public void drawRect(int x, int y, int width, int height): draws a rectangle with the
specified width and height.
 public abstract void fillRect(int x, int y, int width, int height): is used to fill rectangle
with the default color and specified width and height.
public abstract void drawOval(int x, int y, int width, int height): is used to draw oval with the
specified width and height.

 public abstract void fillOval(int x, int y, int width, int height): is used to fill oval with
the default color and specified width and height.
 public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line
between the points(x1, y1) and (x2, y2).
 public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer):
is used draw the specified image.
 public abstract void drawArc(int x, int y, int width, int height, int startAngle, int
arcAngle): is used draw a circular or elliptical arc.
 public abstract void fillArc(int x, int y, int width, int height, int startAngle, int
arcAngle): is used to fill a circular or elliptical arc.
 public abstract void setColor(Color c): is used to set the graphics current color to the
specified color.
 public abstract void setFont(Font font): is used to set the graphics current font to the
specified font.

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

public void paint(Graphics g)


{ g.setColor(Color.red);
g.drawString("Welcome",50, 50);
g.drawLine(20,30,20,300);
g.drawRect(70,100,30,30);
g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);
g.setColor(Color.pink);
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);
}
}
myapplet.html
<html>
<body>
<applet code="GraphicsDemo.class" width="300" height="300">
</applet>
</body>
</html>

4.6 GUI
A program's graphical user interface presents an easy-to-use visual display to the user. It is
made up of graphical components (e.g., buttons, labels, windows) through which the user can
interact with the page or application. To make graphical user interfaces in Java, use either
Swing (older applications) or JavaFX.
Examples - Display text in different fonts
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class Main extends JPanel
{ String[] type =
{ "Serif","SansSerif"};
int[] styles = { Font.PLAIN, Font.ITALIC, Font.BOLD, Font.ITALIC + Font.BOLD };
String[] stylenames = { "Plain", "Italic", "Bold", "Bold & Italic" };
public void paint(Graphics g) {
for (int f = 0; f < type.length; f++) {
for (int s = 0; s < styles.length; s++) {
Font font = new Font(type[f], styles[s], 18);
g.setFont(font);
String name = type[f] + " " + stylenames[s];
g.drawString(name, 20, (f * 4 + s + 1) * 20);
}
}
}
public static void main(String[] a)
{ JFrame f = new JFrame();
f.addWindowListener(new WindowAdapter()
{ public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
f.setContentPane(new Main());
f.setSize(400,400);
f.setVisible(true);
}
}

4.10 DIALOG BOX:


The Dialog control represents a top level window with a border and a title used to take some
form of input from the user. It inherits the Window class.
Unlike Frame, it doesn't have maximize and minimize buttons.
Frame vs Dialog
Frame and Dialog both inherits Window class. Frame has maximize and minimize buttons
but Dialog doesn't have.
AWT Dialog class declaration
public class Dialog extends Window
Java AWT Dialog Example
import java.awt.*;
import java.awt.event.*;
public class DialogExample { private static Dialog d; DialogExample() {
Frame f= new Frame();
d = new Dialog(f , "Dialog Example", true);
d.setLayout( new FlowLayout() );
Button b = new Button ("OK");
b.addActionListener ( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
DialogExample.d.setVisible(false);
}
});
d.add( new Label ("Click button to continue."));
d.add(b);
d.setSize(300,300);
d.setVisible(true);
}
public static void main(String args[])
{
new DialogExample();
}
}

4.9 CREATING WINDOWS


The first step is to create an IDE project for the application that we are going to develop. We
will name our project NumberAddition.
1. Choose File > New Project. Alternatively, you can click the New Project icon in the
IDE toolbar.
2. In the Categories pane, select the Java node. In the Projects pane, choose Java
Application. Click Next.
3. Type NumberAddition in the Project Name field and specify a path, for example, in
your home directory, as the project location.
4. (Optional) Select the Use Dedicated Folder for Storing Libraries checkbox
and specify the location for the libraries folder. See Sharing a Library with
Other Users in Developing Applications with NetBeans IDE for more
information.
5. Deselect the Create Main Class checkbox if it is selected.
6. Click Finish.

4.11 LAYOUT MANAGER

The LayoutManagers are used to arrange components in a particular manner. LayoutManager


is an interface that is implemented by all the classes of layout managers. There are following
classes that represents the layout managers:

1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
javax.swing.SpringLayout etc.
12 BCS 31/BCA 31 – JAVA PROGRAMMING
9
E-NOTES / B.SC CS /BCA

4.5 APPLICATION
Applications Vs. Applets
You have seen two main differences between applications and applets. Let us summarize
them.

FEATURE APPLICATION APPLET

main()
method Present Not present

Requires a browser like


Execution Requires JRE Chrome

Called as stand-alone application as


application can be executed from command Requires some third party tool
Nature prompt help like a browser to execute

cannot access any thing on the


Can access any data or software available on system except browser’s
Restrictions the system services

Requires highest security for


Security Does not require any security the system as they are untrusted

Advantages of Applets of Applets Vs Applications

1. Execution of applets is easy in a Web browser and does not require any installation or
deployment procedure in realtime programming (where as servlets require).
2. Writing and displaying (just opening in a browser) graphics and animations is easier than
applications.
3. In GUI development, constructor, size of frame, window closing code etc. are not
required (but are required in applications).

13 BCS 31/BCA 31 – JAVA PROGRAMMING


0
E-NOTES / B.SC CS /BCA

4.5 Java AWT

13 BCS 31/BCA 31 – JAVA PROGRAMMING


1
E-NOTES / B.SC CS /BCA

Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based


applications in java.

Java AWT components are platform-dependent i.e. components are displayed according to
the view of operating system. AWT is heavyweight i.e. its components are using the
resources of OS.

The java.awt package provides classes for AWT api such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.

Java AWT Hierarchy

The hierarchy of Java AWT classes are given below.

13 BCS 31/BCA 31 – JAVA PROGRAMMING


2
E-NOTES / B.SC CS /BCA

Container

The Container is a component in AWT that can contain another components like buttons,
textfields, labels etc. The classes that extends Container class are known as container such as
Frame, Dialog and Panel.

Window

The window is the container that have no borders and menu bars. You must use frame, dialog
or another window for creating a window.

Panel

The Panel is the container that doesn't contain title bar and menu bars. It can have other
components like button, textfield etc.

Frame

The Frame is the container that contain title bar and can have menu bars. It can have other
components like button, textfield etc.

Useful Methods of Component class

Method Description

public void add(Component c) inserts a component on this component.

public void setSize(int width,int height) sets the size (width and height) of the component.

public void setLayout(LayoutManager defines the layout manager for the


component. m)

public void setVisible(boolean status) changes the visibility of the component, by default
false.

Java AWT Example

To create simple awt example, you need a frame. There are two ways to create a frame in
AWT.

o By extending Frame class (inheritance)


o By creating the object of Frame class (association)

13 BCS 31/BCA 31 – JAVA PROGRAMMING


3
E-NOTES / B.SC CS /BCA

4.7 AWT classes


The Event classes represent the event. Java provides us various Event classes but we will
discuss those which are more frequently used.

EventObject class
It is the root class from which all event state objects shall be derived. All Events are
constructed with a reference to the object, the source, that is logically deemed to be the
object upon which the Event in question initially occurred upon.This class is defined in

13 BCS 31/BCA 31 – JAVA PROGRAMMING


4
E-NOTES / B.SC CS /BCA

java.util package.

Class declaration
Following is the declaration for java.util.EventObject class:

public class EventObject

extends Object

implements Serializable

Field
Following are the fields for java.util.EventObject class:

 protected Object source -- The object on which the Event initially occurred.

Class constructors

S.N. Constructor & Description

1 EventObject(Object source)

Constructs a prototypical Event.

Class methods
S.N. Method & Description

1
Object getSource()

The object on which the Event initially occurred.

2
String toString()

Returns a String representation of this EventObject.

4.8 WINDOW FUNDAMENTALS


Concept of window and advanced components in java

13 BCS 31/BCA 31 – JAVA PROGRAMMING


5
E-NOTES / B.SC CS /BCA

 The AWT defines windows according to a class hierarchy that adds functionality and
specificity with each level.
 The two most common windows are those derived from Panel, which is used by
applets, and those derived from Frame, which creates a standard window.
 Much of the functionality of these windows is derived from their parent classes.

Component
 At the top of the AWT hierarchy is the Component class.
 Component is an abstract class that encapsulates all of the attributes of a visual
component.
 All user interface elements that are displayed on the screen and that interact with the
user are subclasses of Component.
 It defines over a hundred public methods that are responsible for managing events,
such as mouse and keyboard input, positioning and sizing the window, and repainting.
 A Component object is responsible for remembering the current foreground and
background colors and the currently selected text font.

Container
 The Container class is a subclass of Component.
 It has additional methods that allow other Component objects to be nested within it.
 Other Container objects can be stored inside of a Container (since they are themselves
instances of Component).
 This makes for a multileveled containment system.
 A container is responsible for laying out (that is, positioning) any components that it
contains.

Panel
 The Panel class is a concrete subclass of Container. It doesn’t add any new methods;
it simply implements Container.
 Panel is the superclass for Applet. When screen output is directed to an applet, it is
drawn on the surface of a Panel object.
 A Panel is a window that does not contain a title bar, menu bar, or border.
 When you run an applet using an applet viewer, the applet viewer provides the title
and border.
 Other components can be added to a Panel object by its add( ) method inherited from
Container.
 Once these components have been added, you can position and resize them manually
using the setLocation( ), setSize( ), or setBounds( ) methods defined by Component.

Window

13 BCS 31/BCA 31 – JAVA PROGRAMMING


6
E-NOTES / B.SC CS /BCA

 The Window class creates a top-level window. A top-level window is not contained
within any other object; it sits directly on the desktop. Generally, we don’t create
 Window objects directly. Instead, we use a subclass of Window called Frame.

Frame
 Frame encapsulates what is commonly thought of as a “window.” It is a subclass of
Window and has a title bar, menu bar, borders, and resizing corners.

Canvas
 It is not part of the hierarchy for applet or frame windows. Canvas encapsulates a
blank window upon which you can draw.

13 BCS 31/BCA 31 – JAVA PROGRAMMING


7
E-NOTES / B.SC CS /BCA

9.

13 BCS 31/BCA 31 – JAVA PROGRAMMING


8
E-NOTES / B.SC CS /BCA

Java BorderLayout

The BorderLayout is used to arrange the components in five regions: north, south, east, west
and center. Each region (area) may contain one component only. It is the default layout of
frame or window. The BorderLayout provides five constants for each region:

1. public static final int NORTH


2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER

Constructors of BorderLayout class

 BorderLayout(): creates a border layout but with no gaps between the components.
 JBorderLayout(int hgap, int vgap): creates a border layout with the given
horizontal and vertical gaps between the components.

4.12 RADIO BUTTON AND CHECK BOX


Radio buttons provide a user with a way to select one of a number of labeled options
displayed simultaneously in a window. Radio buttons are organized in a radio button group.
Only one button in a group can be selected at any given time. When the user selects a new
button, the previously selected button is automatically deselected. One button is usually
selected at program starup by default.
Check boxes are labeled options that allow the user to select multiple options at once. Thus,
any, all, or none of a set of check boxes may be selected.
Combo boxes are drop-down menus that can appear along with other widgets in the main
area of a window. The user may select one option at a time, and it then remains selected.
The next screen shots show a program that allows the user to select options from all three
types of controls. The user can then view the states of the controls by clicking the Get states
button.

4.13 BORDERS

Borders are commonly used in two situations:

An empty border on the content pane of a window.

A titled or empty border on an inner JPanel.

Avoid with other components and graphics JPanels.

As a practical matter, borders do not work with many JComponents other than JPanel.

Borders are drawn inside the graphics area of a JComponent, so subclassing JPanel for
13 BCS 31/BCA 31 – JAVA PROGRAMMING
9
E-NOTES / B.SC CS /BCA

drawing graphics must take this into account. This is one reason that subclassing JComponent
for graphics can be easier.

Good with JPanels, not good with other components, impossible with Containers

Method setBorder(). The setBorder() method is defined in the JComponent class, and is
therefore inherited by all child classes, which basically means all swing components, most
importantly JPanel.

Best on JPanels, not other JComponents. Borders are most often added to JPanels, and
somewhat less often to other JComponents, such as JLabels. Although you can add a border
to any JComponent, as a practical matter they often don't display well. If you need to add a
border to a component, put the component in a JPanel and add the border to that JPanel.

Creating borders

Creating borders:To create borders, use factory methods in the javax.swing.BorderFactory


class. This and other border classes can be used with

import javax.swing.border.*;

Reuse: A Border object describes how to draw the border. The same Border object may be
reused to set the border of many components.

Borders can be grouped into these types:

Empty border -- Empty space around a component.

Titled border -- Text on one of the other borders, usually a line border.

Line border -- Several line styles: plain, etched, or beveled.

Compound borders -- A combination of two borders.

Matte border -- Images around a component.

To create an empty border

An empty border creates empty space around a component. Give the int number of pixels of
empty space on each side: top, left, bottom, right.

JPanel content = new JPanel();


content.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
4.14 SWING:

Java Swing is a part of Java Foundation Classes (JFC) that is used to create window-based
applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely
written in java.

14 BCS 31/BCA 31 – JAVA PROGRAMMING


0
E-NOTES / B.SC CS /BCA

Unlike AWT, Java Swing provides platform-independent and lightweight components.

The javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.

UNIT IV
QUESTION BANK
PART – A (2 marks)

1. What is Applet?
2. Mention the two ways to create a Swing program.
3. Specify the use of AWT.
4. Mention the components in AWT. (Nov/Dec 2018)
5. Define the term-Panel.
6. What are the different controls provided by AWT?
7. What is Layout Manager?
8. What is the difference between local and remote applet?
9. What are Applet Classes?
10. Define Border.
14 BCS 31/BCA 31 – JAVA PROGRAMMING
1
E-NOTES / B.SC CS /BCA

11. Define Swing.


12. Give a situation where radio button can be used.(Nov/Dec 2018)
13. Define Checkbox.

PART – B (5 marks)
1. Describe the fundamentals of Applet.
2. Discuss on Border control component with example program.
3. Discuss about the Life Cycle of Applet.(Nov/Dec 2018)
4. How to create the Swing using Jpanel? Explain.
5. Write about the Advantages and Disadvantages of an Applet.
6. Explain drawRect() method in graphics class with example.
7. Write the difference between Swing and AWT.
8. What is the use of AWT Dialog box? Explain.
9. Discuss about the role of Swing in getting an interface.(Nov/Dec 2018)

PART – C (10 marks)


1. Describe any three AWT Classes with their method.(Nov/Dec 2018)
2. Describe the various methods to create graphics in an Applet.
3. Explain in detail about different Layout managers.
4. Discuss in detail about various Swing elements.

UNIT V

5.1 JDBC
 JDBC stands for Java Database Connectivity

 JDBC is used to interact with various type of Database such as Oracle, MS Access,
My SQL and SQL Server.

 JDBC can also be defined as the platform-independent interface between a relational


database and Java programming. It allows java program to execute SQL statement
and retrieve result from database.

 The JDBC library includes APIs for each of the tasks mentioned below that are
commonly associated with database usage.

Making a connection to a database.

14 BCS 31/BCA 31 – JAVA PROGRAMMING


2
E-NOTES / B.SC CS /BCA

Creating SQL or MySQL statements.

Executing SQL or MySQL queries in the database.

Viewing & Modifying the resulting records.

Use JDBC

Before JDBC, ODBC API was the database API to connect and execute query with the
database. But, ODBC API uses ODBC driver which is written in C language (i.e. platform
dependent and unsecured). That is why Java has defined its own API (JDBC API) that uses
JDBC drivers (written in Java language).

We can use JDBC API to handle database using Java program and can perform following
activities:
1. Connect to the database
2. Execute queries and update statements to the database
3. Retrieve the result received from the database.

5.2 Types of Driver


JDBC Driver is required to process SQL requests and generate result. The following are the
different types of driver available in JDBC.

 Type-1 Driver or JDBC-ODBC bridge


 Type-2 Driver or Native API Partly Java Driver
 Type-3 Driver or Network Protocol Driver
 Type-4 Driver or Thin Driver

5.2.1 JDBC-ODBC bridge driver

The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-
ODBC bridge driver converts JDBC method calls into the ODBC function calls. This is now
discouraged because of thin driver.

14 BCS 31/BCA 31 – JAVA PROGRAMMING


3
E-NOTES / B.SC CS /BCA

Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle recommends that you
use JDBC drivers provided by the vendor of your database instead of the JDBC-ODBC
Bridge.

Advantages:
 Easy to use.
 Can be easily connected to any database.

Disadvantages:
 Performance degraded because JDBC method call is converted into the ODBC
function calls.
 The ODBC driver needs to be installed on the client machine.

5.2.2 Native-API driver

The Native API driver uses the client-side libraries of the database. The driver converts
JDBC method calls into native calls of the database API. It is not written entirely in java.

14 BCS 31/BCA 31 – JAVA PROGRAMMING


4
E-NOTES / B.SC CS /BCA

Advantage:
 Performance upgraded than JDBC-ODBC bridge driver.

Disadvantage:
 The Native driver needs to be installed on the each client machine.
 The Vendor client library needs to be installed on client machine.

5.2.3 Network Protocol driver


The Network Protocol driver uses middleware (application server) that converts JDBC calls
directly or indirectly into the vendor-specific database protocol. It is fully written in java.

Advantage:
 No client side library is required because of application server that can perform many
tasks like auditing, load balancing, logging etc.

Disadvantages:
14 BCS 31/BCA 31 – JAVA PROGRAMMING
5
E-NOTES / B.SC CS /BCA

 Network support is required on client machine.


 Requires database-specific coding to be done in the middle tier.
 Maintenance of Network Protocol driver becomes costly because it requires database-
specific coding to be done in the middle tier.

5.2.4 Thin driver


The thin driver converts JDBC calls directly into the vendor-specific database protocol. That
is why it is known as thin driver. It is fully written in Java language.

Advantage:

 Better performance than all other drivers.


 No software is required at client side or server side.

Disadvantage:

 Drivers depend on the Database.

5.3 JDBC Architecture


 JDBC programming interface is found in "java.sql" and "javax.sql" packages.
 JDBC programming interface is found in "java.sql" and "javax.sql" packages.JDBC
architecture can be classified in 2 broad categories:-
14 BCS 31/BCA 31 – JAVA PROGRAMMING
6
E-NOTES / B.SC CS /BCA

 JDBC API
 Types of JDBC Drivers

5.3.1 JDBC API

This can be used in Java applications, applets, servlets or any other program where Java
codes used.

 Java codes only interact with the JDBC Application-Program Interface (API). The
JDBC API is a simple SQL-Level interface, which allows execution of SQL
statements through Java.
 The API consists of a set of interfaces and classes designed to perform actions on a
database.
 The JDBC API class DriverManager, which is used to establish the connection to the
database, is responsible for managing the different JDBC drivers.
 Other classes of JDBC API are useful when the programmer wishes to develop
specific drivers of her own.
 The JDBC-ODBC bridge performs translations of JDBC calls to an ODBC-
compatible format.
 This bridge is required to maintain compatibility with non-JDBC databases.

Some classes and interfaces which support connectivity between interface and database :-
DriverManager :-
14 BCS 31/BCA 31 – JAVA PROGRAMMING
7
E-NOTES / B.SC CS /BCA

“Driver Manger" Manages all the Drivers found in JDBC environment, load the most
appropriate driver for connectivity.
Connection:-
Connection class creates objects which represents connection and it's object also helps
in creating object of Statement, Prepared Statement and Callable Statement classes.
Statement:-
Statement object is used to execute query and also store it's value to
"Resultset" object.
PreparedStatement:-
It can be used in place of "Statement", Prepared Statement’s performance is high as
compared to "Statement" class, represents a precompiled SQL statement .
Callable Statement:-
Callable statement support stored procedure of RDBMS’, using it's object you can
execute stored procedure of database application.
ResultSet:-
Resultset object is used to store the result retrieve from database using "Statement" or
"PreparedStatement”, etc
SQLException:-
SqlException class is used to represent error or warning during access from database
or during connectivity.
Classes and interface
The JDBC API is comprised of two Java packages: java.sql and javax.sql. The following are
core JDBC classes, interfaces, and exceptions in the java.sql package:

DriverManager

The DriverManager class (java.sql.DriverManager) is one of main components of JDBC.

DriverManager manages database drivers, load database specific drivers and select the most
appropriate database specific driver from the previously loaded drivers when a new
connection is established.

Managing, loading and selecting drivers are done automatically by the DriverManager from
JDBC 4.0, when a new connection is created.

The DriverManager can also be considered as a connection factory class as it uses database
specific drivers to create connection (java.sql.Connection) objects.

DriverManager consist of only one private constructor and hence it cannot be inherited or
initialized directly.
14 BCS 31/BCA 31 – JAVA PROGRAMMING
8
E-NOTES / B.SC CS /BCA

All other members of DriverManager are static. DriverManager maintains a list of DriverInfo
objects that hold one Driver object each.

Connection

Connection interface provides a standard abstraction to access the session established with a
database server. JDBC driver provider should implement the connection interface. We can
obtain a Connection object using the getConnection() method of the DriverManager as:

Connection con = DriverManager.getConnection(url, username, password);

Before JDBC 4.0, we had to first load the Driver implementation before getting the
connection from the DriverManager as:

Class.forName(oracle.jdbc.driver.OracleDriver);

We can also use DataSource for creating a connection for better data source portability and is
the preferred way in production applications.

Statement

The Statement interface provides a standard abstraction to execute SQL statements and return
the results using the ResultSet objects.

A Statement object contains a single ResultSet object at a time. The execute method of a
Statement implicitly close its current ResultSet if it is already open. PreparedStatement and
CallableStatement are two specialized Statement interfaces. You can create a Statement
object by using the createStatement() method of the Connection interface as:

Statement st = con.createStatement();

You can then execute the statement, get the ResultSet and iterate over it:

ResultSet rs = st.executeQuery("select * from employeeList");

while (rs.next())

{ System.out.println(rs.getString("empname"));

}
PreparedStatement

PreparedStatement is a sub interface of the Statement interface. PreparedStatements are pre-


compiled and hence their execution is much faster than that of Statements. You get a
PreparedStatement object from a Connection object using the prepareStatement() method:

PreparedStatement ps1 = con.prepareStatement("insert into employeeList values


('Heartin',2)");

14 BCS 31/BCA 31 – JAVA PROGRAMMING


9
E-NOTES / B.SC CS /BCA

ps1.executeUpdate();

ResultSetMetaData

ResultSetMetaData is used to retrieve information about the count, types and the properties of
columns used in a ResultSet object. Consider an example where you are passed a ResultSet to
a method and you don’t know the number or type of columns in the ResultSet. You can use
ResultSetMetaData to get the column details and then find the corresponding row values
using the column details.

RowId

RowId maps a java object with a RowId. The RowId is a built-in datatype and is used as the
identification key of a row in a database table, especially when there are duplicate rows.

SQLException

This class is an exception class that provides information on a database access error or other
errors. JDBC 4.0 introduced following refined subclasses of SQLException:

 java.sql.SQLClientInfoException
 java.sql.SQLDataException
 java.sql.SQLFeatureNotSupportedException
 java.sql.SQLIntegrityConstraintViolationException
 java.sql.SQLInvalidAuthorizationSpecException
 java.sql.SQLSyntaxErrorException
 java.sql.SQLTransactionRollbackException
 java.sql.SQLTransientConnectionException

5.4 Working of DatabaseMetaData

DatabaseMetaData interface provides methods to get meta data of a database such as


database product name, database product version, driver name, name of total number of
tables, name of total number of views etc.

Commonly used methods of DatabaseMetaData interface

public String getDriverName()throws SQLException: it returns the name of the JDBC


driver.

public String getDriverVersion()throws SQLException: it returns the version number of


the JDBC driver.

public String getUserName()throws SQLException: it returns the username of the


database.

15 BCS 31/BCA 31 – JAVA PROGRAMMING


0
E-NOTES / B.SC CS /BCA

public String getDatabaseProductName()throws SQLException: it returns the product


name of the database.

public String getDatabaseProductVersion()throws SQLException: it returns the product


version of the database.

public ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern,


String[] types)throws SQLException: it returns the description of the tables of the specified
catalog. The table type can be TABLE, VIEW, ALIAS, SYSTEM TABLE, SYNONYM etc.

UNIT V

QUESTION BANK

PART – A (2 marks)

1. How does JDBC differ from ODBC?[Nov/Dec 2018]


2. Define the term –Pure Java driver. [Nov/Dec 2018]
15 BCS 31/BCA 31 – JAVA PROGRAMMING
1
E-NOTES / B.SC CS /BCA

3. Mention the purpose of close( ) method.[Apr/May 2019]


4. How a JDBC driver is chosen for the application? [Apr/May 2019]
5. Expand JDBC.
6. Define JDBC.
7. Define JDBC Drivers.
8. Define Meta data.

PART – B (5 marks)

1. Write the steps in developing JDBC applications. [Nov/Dec 2018]


2. Give an overview of “resultset” Metadata interface. [Nov/Dec 2018]
3. Write short note on JDBC classes and Interfaces. [Apr/May 2019]
4. Describe the types of Resultset. [Apr/May 2019]
5. Discuss 2-tier and 3-tier client server model.
6. What are the different types of JDBC driver?
7. What are the steps involved in java database connectivity?

PART – C (10 marks)

1. Discuss on the different types of JDBC drivers. [Nov/Dec 2018]


2. How to create the database and table using JDBC? Explain. [Apr/May 2019]
3. Discuss the Architecture of JDBC.
4. Briefly explain working with database metadata in JDBC.

15 BCS 31/BCA 31 – JAVA PROGRAMMING


2

You might also like