KEMBAR78
BCA Java Unit1to5 | PDF | Class (Computer Programming) | Data Type
0% found this document useful (0 votes)
11 views79 pages

BCA Java Unit1to5

Uploaded by

poolgod2762
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views79 pages

BCA Java Unit1to5

Uploaded by

poolgod2762
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 79

OOPs through Java BCA IIIrd semester

Subject: JAVA
Unit – 1
Introduction to OOP’s:
 The primary motivation to handle the increasing complexity of programs
that are reliable and maintainable.
 Procedure oriented or Structured programming language was a powerful
tool that enabled programmers to write complex programs fairly and
easily.
 Procedure oriented programming approach the problem is viewed as a
sequence of things (reading, calculating and writing) to be done.
 Large programs are divided into no sub parts called as functions

 A number of functions are written to accomplish these tasks


 Each function may have it’s own local data
 Most of the functions share global data
 These data move openly or freely around the system from function to
function
 Therefore, there is no security of data in procedure-oriented
programming.
 It is platform dependent
 It follows top-down approach
 It does not supports OOPS
Object oriented programming approach to program organization and
development which attempts to overcome or eliminate some of the pitfalls
or drawbacks of conventional programming methods by incorporating the
best of structured programming features with several new concepts.
Some of the oops languages are
1. Smalltalk

National Degree college, Nandyal Page 1


OOPs through Java BCA IIIrd semester

2. Objective of c
3. C++, java, ADA and Objective Pascal
Object oriented approach:
 Object oriented programming is a collection of classes and objects
 OOPS treats data as a critical element in the program development and
does not allow it to flow freely around the system
 OOPS allows divide or decompose of a problem into number of entities
are called as objects and then built data and functions
1. Emphasis is on data rather than functions or procedures.
2. Programs are divided into objects.
3. Data structures are designed to characterize the objects.
4. Functions that operate on the data of an object are tied together with the
data structure.
5. Data of an object is hidden and cannot be accessed by external functions.
6. Objects communicate with each other through functions.
7. follows bottom-up approach to program design.

OOPS concepts:
 OOP allows the decomposition of a problem into a number of entities
called objects and then builds data and functions around these objects.
 Data cannot be accessed directly, they are only accessible through the
member function.
 It contain several concepts
1. Class
2. Object
3. Encapsulation

National Degree college, Nandyal Page 2


OOPs through Java BCA IIIrd semester

4. Data abstraction
5. Inheritance
6. Polymorphism
7. Dynamic binding
8. Message passing
1. Class:
 Class is a collection of data members and member functions into a
single unit is called as class
 It can be specified by class keyword
 By default the data members are private and member functions
are declared in public section
Syntax:
class classname
{
datatype variable;
datatype variable;
datatype variable;
public:
function1();
function2();
}
 Class can be represented by rectangle symbol
2. Object:
 Instance of a class or duplication of a class
 Without class we cannot create an object
Syntax:
classname object; or
classname object=new classname;
3. Encapsulation:
 The wrapping up of or combining data members and member
functions into a single unit is called as an Encapsulation
 Encapsulation is the most striking feature of a class
 The data is not accessible to the outside the class

National Degree college, Nandyal Page 3


OOPs through Java BCA IIIrd semester

4. Data abstraction:
 Data abstraction refers to the act of representing an essential
features without including background details is called as Data
abstraction
 The class use the concept of data abstraction, they are known as
abstract data types
5. Inheritance:
 The process of deriving or acquiring the properties from one class to
another class is called as inheritance
 The newly created class is called the derived class or child class or
subclass and the class from which the new class is created is class
base class or parent class or super-class.
6. Polymorphism:
 Polymorphism is another important concept in oops
 poly means many and morphism means types.
 Polymorphism means ability to take more than one form

7. Dynamic binding:
 Binding refers to the linking of procedure called to the code to be
executed in response to the call
 Dynamic binding means that the code is associated with a given
procedure call is not now until the time of call at runtime
 It is associated with polymorphism and inheritance
8. Message passing:
 The process of programming in an object oriented language.
 Objects communicate with from one object to another object by
sending and receiving information
National Degree college, Nandyal Page 4
OOPs through Java BCA IIIrd semester

Applications of OOPS:
 Real time systems
 Simulation and modeling
 Object oriented databases
 Hyper text as Hyper media(Internet)
 Networking and parallel programming
 CAD systems
Introduction to Java:
 Java is a general purpose object oriented programming language
 It was developed by James Gosling and Patrick Naughton designed with
sun micro systems
 Initially it was called as OAK, later it was renamed as Java in 1995
 The primary motivation of java is Platform Independent (Architectural
Neutral).
 It could be used to create a software for consumer electronic devices
such as TV, Micro ovens, remote controllers etc
 The problems or troubles with c and c++ is that they are designed to
compiled for a specific target
 These compilers or interpreters are expensive and time consuming
 Java enhances these features of object oriented programming(c++)
 Java was divided into no of sub parts
1. J2SE(Java Standard Edition)standard applications and applets
2. J2EE(Java Enterprise Edition)J2SE along with business solutions
3. J2ME(Java Micro Edition)Portable devices(cellular phones,PDA)
Features of java:
 Java has several features. Such as
1. Simple
2. Secure
3. Portable
4. Object oriented
5. Platform independent
6. Robust
7. Compiled and Interpreted
8. Multithreaded
9. Distributed
10. Dynamic

National Degree college, Nandyal Page 5


OOPs through Java BCA IIIrd semester

1. Simple:
 Java inherits the C/C++ syntax and many object oriented features of C++
that makes the programmers to learn java easy
2. Secure:
 When a java is compatible with web browser is used ,it is safe to
download java applets without fear of virus
3. Portable:
 Write once and run anywhere is slogan for java
 Portable means lightweight. The same java program will run without
change on windows and linux,unix
4. Object oriented:
 Java is purely object oriented programming because everything in java is
a collection of classes and objects is called as object oriented
5. Platform independent:
 The java programs are written and run in different operating systems is
called as platform independent or Architectural neutral
6. Robust:
 Robust means strong. Java is strong with the following features
 It supports in-built exception handling mechanism
 Memory management to extend in the middle of the program to a
variable
7. Compiled and Interpreted:
 Usually computer language is either compiled or interpreted but java is
both compiled and interpreted
 First java compiler translates the Source code to Byte code instructions
 Second java Interpreter translates Byte code into Machine code
8. Multi threaded:
 Java supports multithreaded programming ,which allows that do many
things simultaneously
9. Distributed:
 Java information is distributed across the network using TCP/IP
protocols. It also supports Remote method invocation(RMI)
10. Dynamic:
 Java is dynamic language. Java is capable of dynamically linking a new
class libraries, methods and objects
Java Environment:
 Java environment includes a large number of development tools and
hundreds of classes and methods
National Degree college, Nandyal Page 6
OOPs through Java BCA IIIrd semester

 The development tools are part of the system known as Java


development Tool kit(JDK)
 The classes and methods are the path of the java standard library(JSL)
also known as the Application program interface
Java development tool kit:
 JDK is a software package that the sun micro system has made
available to the public as free
 This package gives you all the tools we need to start writing and
running java programs
 Java development kit includes the following tools
Tools Meaning
Javac Java compiler converts source code into byte code(.class file)
Java The java interpreter executes java byte code directly and
convert byte code to machine code
Appletviewer A java interpreter that executes java applet classes hosted by
HTML files
Javah Generates ‘C’ header files that can be used to make ‘C’ runtime
that can be called byte java programs
Javadoc Create HTML format documentation from java source files
Javap Java disassemble which helps enables us to convert byte code
files into a program description
Jdb Java debugger, which helps us to find errors in our program
Rmic Creates class file that supports remote method programs
Jar Helps us distributing java classified in compressed mode
Java standard library(JSL/API):
 JSL or API includes hundreds of classes and methods grouped into
several function packages most commonly used packages are
1. Language support packages:
A collection of classes and methods required for implementing basic
features of java
2. I/O packages:
A collection of classes for I/O manipulation
3. Utilitiy packages:
A collection of classes to provide utility functions such as date and time
functions

National Degree college, Nandyal Page 7


OOPs through Java BCA IIIrd semester

4. Network package:
A collection of classes for communicating with other computers via
internet
5. AWT packages:
AWT kit packages contain class that implements platform independent
graphical user interface
6. Applet package:
This includes a set of classes that allows us to create java applets
JVM(Java Virtual Machine):
 JVM stands for Java Virtual Machine
 It is the heart of java program. which is responsible for taking .class file
and converting byte code instructions into Machine code instructions
 First of all .java program is converted into a .class file consisting of byte
code instructions by the java compiler
 Java compiler is outside of JVM. Now the .class file is given to jvm, there
is module called class loader sub system,which performs the following
operations
 First of all ,it loads the .class file into memory
 Then it verifies whether all byte code instructions are proper or
not. If it finds any instructions suspicious , it rejects the execution
 If the byte code instructions are proper, then it allocates the
necessary to execute the program
This memory is divided into 5 parts
1. Method area
2. Heap
3. Java stacks
4. PC register
5. Native method stacks

National Degree college, Nandyal Page 8


OOPs through Java BCA IIIrd semester

1. Method area:
 Method area is the memory block, which stores the class code, variables,
methods in the java program
2. Heap:
 This is the area where objects are created. Whenever jvm loads a class,
method and a heap area are immediately created
3. Java stacks:
 Method code is stored on method area. But while running a method it
needs some memory to store the data and results. This memory is
allocated to java stacks
4. PC register:
 It contains memory address of the instructions of the methods
5. Native method stacks:
 Java methods are executed on java stacks. Similarly, native methods
(C/C++ functions) are executed on native method stacks.
Parts of java program or structure of java program:
 Java is an object-oriented programming
 Java program may contain many classes of which only one class define a
main method.
 Class is a collection of data members(variables) & methods(functions)
 That operate on the data members of a class
 Structure of java program is divided into no of sections

Documentations section:
 The documentation section is an important section but optional for a
Java program.
 It includes basic information about a Java program such as author name,
created date and description of the program.
 It consists comment lines. Comment lines are ignored by the compiler

National Degree college, Nandyal Page 9


OOPs through Java BCA IIIrd semester

 These comment lines are represented by single-line, multi-line


comments
 Single-line Comment: It starts with a pair of forwarding slash (//).
 //First Java Program
 Multi-line Comment: It starts with a /* and ends with */.
Package statement:
 Package statement also an optional. Which is used to create user
defined package
 Package is a collection of classes and interfaces
 Note that there can be only one package statement in a Java program.
 It must be defined before any class and interface declaration.
Ex: package packagename;
Import statement:
 This is similar to #include<stdio.h> in c
 We use the import keyword to import the class.
 It includes classes and interfaces of a particular package
Ex: import java.io.*;
import java.lang.*;
Interface statement:
 It is an optional
 Interface is a collection of operations which can be specified a service
from a class
 It contains only constants and method declarations
Ex:
interface car
{
void start();
void stop();
}
Class definition section:
 It is vital part of a Java program. Without the class, we cannot create
any Java program.
 A Java program may conation more than one class definition. We use
the class keyword to define the class.
 Every Java program has at least one class that contains the main()
method.
class Student //class definition
{
String sname; //variable
int id;

National Degree college, Nandyal Page 10


OOPs through Java BCA IIIrd semester

double percentage;
}
Main method class:
 It is essential for all Java programs. Because the execution of all Java
programs starts from the main() method.
 It is an entry point of the class. It must be inside the class.
 Inside the main method, we create objects and call the methods.
Ex:
import java.io.*;
class Hello
{
public static void main(String[] args)
{
System.out.println("welcome to Java");
}
}
Exaplantion:
import java.io.- Import is a keyword that includes the class we use in the code.
This is used to import all the classes of the io package. Java's io package
includes a set of input and output streams used to read or write files and input
or output.
public class-The data and methods that need to be used in the program are
included in the class. Methods define the behavior of the class.
static-Static methods do not require objects to get called. They can be
executed using the dot operator with the class name.
void- Does not return any value. It's an empty void.
main()- Name of the method. Entry point method where JVM runs the
program.
(String[ ] args)- These are used as command-line arguments and are passed as
strings.
System.out.println- This command prints the contents provided within the
print statement.
Naming conventions:
 Java naming convention is a rule to follow as you decide what to name
your identifiers such as class, package, variable, constant, method, etc.
 But, it is not forced to follow. So, it is known as convention not rule.
 All the classes, interfaces, packages, methods and fields of Java
programming language are given according to the Java naming
convention.

National Degree college, Nandyal Page 11


OOPs through Java BCA IIIrd semester

 All the classes, interfaces, methods should start with the uppercase
letter.
 Variables , packages must be in lower case letters
 Constants must be in upper case letters only
Java Tokens:
 The smallest individual unit of a program is called as Token
 Tokens are classified into several types
1. Keywords
2. Identifiers
3. Datatypes
4. Variables
5. Constants
1. Keywords:
 The keywords are also called as pre-defined words or reserved
words
 It contains a specific meaning
 It should not use for other purpose
 C language supports 32 keywords
 All the keywords must be specified in Lower case letters only
 Some of the keywords are additional to the c language are
public, private, protected and class, interface, extends, try ,throw
and catch
2. Identifiers:
 Identifiers are the user defined words
 Which is used to identify the unique names of the variables
 Keywords should not be used as an identifers
 To create an identifier it must follow some rules or naming conventions
Rules:
 It must start with alphabet or underscore(_).
 It consists of alphabets, digits, or underscore.
 It should not contain any special character except underscore(_).
 It should not contain white spaces.
 It should not exceed more than 32 characters of length
Note: Identifiers are case-sensitive so names like variable and Variable will be
treated as different.
3. Data types:
 Data type represents type of the data. What type of data we want to
store with in a variable
 Java data types are classified into two types

National Degree college, Nandyal Page 12


OOPs through Java BCA IIIrd semester

1. Primitive data types: The primitive data types include boolean, char,
byte, short, int, long, float and double.
2. Non-primitive data types: The non-primitive data types are strings,
arrays ,classes and interfaces.

Primitive Data Types:


 Primitive data types includes byte, short, int, long, char, double, float,
and boolean.
Data Type Size Description
Byte 1 byte Stores whole numbers from -128 to 127
Short 2 bytes Stores whole numbers from -32,768 to 32,767
Int 4 bytes Stores whole numbers from -2,147,483,648 to
2,147,483,647
Long 8 bytes Stores whole numbers from -9,223,372,036,854,775,808
to 9,223,372,036,854,775,807
Float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7
decimal digits
double 8 bytes Stores fractional numbers. Sufficient for storing 15
decimal digits
boolean 1 bit Stores true or false values
Char 2 bytes Stores a single character/letter or ASCII values
Non-Primitive data types:
 Non-Primitive Data types in Java include String, Array, Class, and
Interface.
 We can also call them as Reference Data Types.

National Degree college, Nandyal Page 13


OOPs through Java BCA IIIrd semester

String:
 String is a collection of characters or sequence of characters.
 It must be specified with in double-quotes(” “).
Array:
 An array is a collection of similar data elements are stored into a single
common variable
Ex: int[] num = {3,6,12,89,24};
Class:
 Class is a collection of data members and member functions into a single
unit
 It can be specified by class keyword
Interface:
 Interface is a collection of operations which can be specified a service
from the class
Variables:
 A variable is a named memory location
 Which can store the specific value and memory depends on it’s data
type is called as a variable
 It is also defined as collection of data type and identifier
Syntax
The syntax to declare a variable
data_type variable_name = value; // defining single variable
or
data_type variable_name1, variable_name2; // defining multiple variable
Here,
 data_type: Type of data that a variable can store.
 variable_name: Name of the variable given by the user.
 value: value assigned to the variable by the user.
Example
int sno; // integer variable
String sname; // String variable
float avg; // float variables
Example
int sno; // variable definition
sno = 10; // initialization
or
int sno = 10; // variable declaration and definition
Scope of variables:
 variables are classified into 3 types
1. instance variables

National Degree college, Nandyal Page 14


OOPs through Java BCA IIIrd semester

2. class variables
3. local variables
 instance variables and class variables are declared inside a class
 instance variables are created when the objects are initialized and
therefore they are associated with the objects
 the class variables are global to a class and belong to the entire set of
objects that the class creates
 variables are declared and used inside the methods are called as local
variables
Constants:
 A constant represents fixed value.
 Which cannot change or modify the value through out of an entire
program is called as a constant
 It can be specified by final keyword

Ex:
final float PI=3.14f;
 Constants are again classified into several types
 Numerical constants
 Character constants
Numerical constants:
 Numerical constants represents the number type of data with or without
decimal points
 Again Numerical constants are classified into two types such as integer
constants and real constants
 Integer constants represents number type of data without decimal
points
Octal Integer constants represents eight values (0 to 7)
Decimal Integer constantsrepresentsten values(0 to 9)
Hexa Decimal Integer constantsrepresents fifteen values(0 to F)
 Real constants represents number type of data with decimal points
Standard real constants  represents number with decimal points
National Degree college, Nandyal Page 15
OOPs through Java BCA IIIrd semester

Scientific constants  represents log values like 3.4e


Character constants:
 Character constants represents a letter or alphabets or text type of data
Single Character constants refers a single letter must be represent in
single quotes
String constants refers a collection of characters must be specified
with in double quotes
Type casting:
 Type casting is a method or process that converts a data type into
another data type in both ways manually and automatically.
 The automatic conversion is done by the compiler and manual
conversion performed by the programmer.

 There are two types of type casting:


1. Widening Type Casting(Implicit Typecasting)
2. Narrowing Type Casting(Explicit Typecasting)
1. Widening Type Casting
 Converting a lower data type into a higher one is called widening type
casting. It is also known as implicit conversion or casting down.
 It is done automatically. It is safe because there is no chance to lose
data.
 It takes place when:
 Both data types must be compatible with each other.
 The target type must be larger than the source type.
2. Narrowing Type Casting
 Converting a higher data type into a lower one is called narrowing type
casting.
 It is also known as explicit conversion or casting up. It is done manually
by the programmer.
 If we do not perform casting then the compiler reports a compile-time
error.
short to byte, short to char
short input = 65 ;
byte b = (byte) input ;
char c = (char) input ;
National Degree college, Nandyal Page 16
OOPs through Java BCA IIIrd semester

char to byte, char to short


char input = 65 ;
byte b = (byte) input ;
short s = (short) input ;
int to byte, int to short, int to char
int input = 12 ;
byte b = (byte) input ;
short s = (short) input ;
char c = (char) input;
long to byte, long to short, long to char, long to int
long input = 12 ;
byte b = (byte) input ;
short s = (short) input ;
char c = (char) input ;
int i = (int) input ;
float to byte, float to short, float to char, float to int, float to long
float input = 12.0f ;
byte b = (byte) input ;
short s = (short) input ;
char c = (char) input ;
int i = (int) input ;
double to byte, double to short, double to char, double to int, double to long,
double to float
double input = 65.25 ;
byte b = (byte) input ;
short s = (short) input ;
char c = (char) input ;
int i = (int) input ;
long l = (long) input ;
float f = (float) input ;
public class TypeCasting
{
public static void main(String[] args)
{
float input = 65.0f ;
byte b = (byte) input ;
short s = (short) input ;
char c = (char) input ;
int i = (int) input ;
System.out.printIn("Examples of Narrowing primitive Type casting...!!");
System.out.printIn("float to short : "+b);
National Degree college, Nandyal Page 17
OOPs through Java BCA IIIrd semester

System.out.printIn("float to byte : "+s);


System.out.printIn("float to char : "+c);
System.out.printIn("float to int : "+i);
}
}
Output:
Examples of Narrowing primitive Type casting…!!
float to short: 65
float to byte: 65
float to char: A
float to int: 65
Operators:
 Java operators are symbols that are used to perform operations on
variables and manipulate the values of the operands. Each operator
performs specific operations.
 Java supports different types of operators
 Arithmetic operators
 Relational operators
 Logical operators
 Bitwise operators
 Assignment operators
 Increment/Decrement operators
 Conditional operators
 Special operators
Arithmetic Operators:
 Arithmetic operators are used to perform simple arithmetic operations
such as simple addition, substraction, multiplication, division and
module, exponent etc.,
Symbol Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Module
Ex:
import java.io.*;
class arithex
{
public static void main ( String[] args )
{
int a = 10;
int b = 20;
National Degree college, Nandyal Page 18
OOPs through Java BCA IIIrd semester

System.out.println( a + b );
System.out.println( a – b );
System.out.println( a * b );
System.out.println( a / b );
System.out.println( a % b );
}
}
Relational operators:
 Relational operators are also called as comparision operators.
 It is used to compare one variable with one value or one variable with
another variable
Symbol Meaning
< less than
<= less than or equals to
> greater than
>= greater than or equals to
== double equals to
!= not equals to
Ex:import java.io.*;
class realtionex
{
public static void main ( String[] args )
{
int a = 10;
int b = 20;
System.out.println ( a < b );
System.out.println( a > b );
System.out.println ( a <= b );
System.out.println (a >= b );
System.out.println ( a == b );
System.out.println ( a != b );
} }
Logical operators:
 Logical operators are also called as combining operators
 Logical operators are used to combining two or more conditions
Symbol Meaning
&& Logical AND
|| Logical OR
! Logical NOT

National Degree college, Nandyal Page 19


OOPs through Java BCA IIIrd semester

Logical AND: Logical OR


A B A && B A B A ||B
T T T T T T
T F F T F T
F T F F T T
F F F F F F

Logical NOT:
A !A
T F
F T
import java.io.*;
class logicalex
{
public static void main ( String args[] )
{
int a = 5;
System.out.println ( a<5 && a<20 );
System.out.println ( a<5 || a<20 );
System.out.println ( ! ( a<5 && a<20 ));
}
}
Bitwise operators:
 Bitwise operation is also known as bit-level programming.
 The bitwise operator operates on bit string, binary number
Symbol Meaning
& Bitwise AND
| Bitwise OR
~ Bitwise NOT
<< Bitwise left shift
>> Bitwise right shift
import java.io.*;
class bitwiseex
{
public static void main ( String args[] )
{
int a = 5;
int b=10;
System.out.println ( a & b );
System.out.println ( a | b );

National Degree college, Nandyal Page 20


OOPs through Java BCA IIIrd semester

System.out.println ( ! ( a ~ b ));
System.out.println ( a<<2 );
System.out.println ( a>>2 );
}
}
Assignment operators:
 Assignment operators are used to assigning the value to it’s variable
 It assign RHS value to LHS variable
L.H.S=R.H.S
Symbol Meaning
= Equals to
+= Plus equals to
-= Minus equals to
*= Multiplication equals to
/= Division equals to
%= Module equals to
import java.io.*;
class assignex
{
public static void main ( String[] args )
{
int a = 10;
int b = 20;
int c;
System.out.println ( c = a );
System.out.println ( b += a );
System.out.println ( b -= a);
System.out.println ( b *= a );
System.out.println ( b /= a );
System.out.println ( b %= a );
}}
Increment and Decrement operators:
 Increment operators are used to increment one value to it’s variable.
These are again classified into two types
1. Pre increment
2. Post increment
 Decrement operators are used to decrement one value to it’s variable.
These are again classified into two types
1. Pre decrement
2. Post decrement

National Degree college, Nandyal Page 21


OOPs through Java BCA IIIrd semester

Symbol Meaning
++ Increment
-- Decrement
import java.io.*;
class indecex
{
public static void main ( String[] args )
{
int a = 10;
System.out.println ( a++ );
System.out.println ( ++a );
System.out.println ( a-- );
System.out.println ( --a );
}
}
Conditional operator:
 It is also called as ternary operator
 It requires 3 operands to perform a specific operation
Syntax : ( Condition ) ? ( Statement1 ) : ( Statement2 );
import java.io.*;
class conditionex
{
public static void main ( String args[] )
{
int a = 4;
int b = 9;
int min = ( a<b ) ? a : b;
System.out.println ( min );
}
}
Special operator:
 instanceof operator is used to test whether the object is an instance of
the specified type (class or subclass or interface).
 It returns either true or false.
import java.io.*;
class Main
{
public static void main(String[] args)
{
// create a variable of string type

National Degree college, Nandyal Page 22


OOPs through Java BCA IIIrd semester

String name = "ram";


// checks if name is instance of String
boolean result1 = name instanceof String;
System.out.println("name is an instance of String: " + result1);
}
}
Reading input using scanner class:
 It is the simplest way to get input in Java
 Scanner is an input function to accept data from the user
 Scanner class is available in java.util package.
 Java provides various ways to read input from the keyboard, the
java.util.Scanner class is one of them.
Syntax:
Scanner in = new Scanner(System.in);
 Java Scanner class provides nextXXX() methods to return the type of
value such as nextInt(), nextByte(), nextShort(), next(), nextLine(),
nextDouble(), nextFloat(), nextBoolean(), etc.
 To get a single character from the scanner, you can call next().charAt(0)
method which returns a single character.
Method Description
next() reads a word from the user
nextInt() reads an int value from the user
nextFloat() reads a float value form the user
nextBoolean() reads a boolean value from the user
nextLine() reads a line of text from the user
nextByte() reads a byte value from the user
nextDouble() reads a double value from the user
//program to get student details
import java.io.*;
import java.util.Scanner;
class StudentDetails
{
public static void main(String args[])
{
String name;
int roll, math, phy, comp;
Scanner SC=new Scanner(System.in);
System.out.print("Enter Name: ");
name=SC.nextLine();
System.out.print("Enter Roll Number: ");

National Degree college, Nandyal Page 23


OOPs through Java BCA IIIrd semester

roll=SC.nextInt();
System.out.print("Enter marks in Maths, Physics and computers: ");
math=SC.nextInt();
phy=SC.nextInt();
comp=SC.nextInt();
int total=math+comp+phy;
float perc=(float)total/300*100;
System.out.println("Roll Number:" + roll +"\tName: "+name);
System.out.println("Marks (Maths, Physics, Computers): " +math+","+phy+","+comp);
System.out.println("Total: "+total +"\tPercentage: "+perc);
}
}
Command line 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.
 args.length is used to count the no of values as input
 args[index] is used to access or display the values
import java.io.*;
class CommandLineExample
{
public static void main(String args[])
{
System.out.println("Your first argument is: "+args[0]);
}
}
compile by > javac CommandLineExample.java
run by > java CommandLineExample ramakrishna
ex2:
import java.io.*;
class A
{
public static void main(String args[])
{
for(int i=0;i<args.length;i++)
System.out.println(args[i]);
} }
compile by > javac A.java
run by > java A ram bcom national 99
National Degree college, Nandyal Page 24
OOPs through Java BCA IIIrd semester

Unit - 2
Control statements:

 control statements are used to change the order of execution based on


user requirements is called as control statements
 A program is a collection of statements. Which are executed in
sequential order in which order they will appear that are executed in
same order. some times we don’t want to execute all the statements in
a program
 if you want to change the order of execution based on the user
requirements that it can be implemented by control statements

 control statements are classified into 3 types


1. Decision making and branching statements
2. Decision making and looping statements
3. Jumping statements
Decision making and branching statements or Conditional Statements:
 Decision making and branching statements are used to execute only
some particular statements based on the condition is true or false.
 Decision making and branching statements again classified into several
types
1. If statements
2. Switch statements
If statements:
If statements are again classified into several types
 Simple if
 If else
 Elseif ladder
 Nested if
Simple if:

National Degree college, Nandyal Page 25


OOPs through Java BCA IIIrd semester

 Simple if is used to check only one condition if the specified condition is


true it allows to execute only true block statements otherwise it will not
allow to execute the statements.
if (condition)
{
code to be executed if condition is true;
}

If Else:
 It is also used to check only one condition
 In simple If the specified condition is true it will execute the true block
statements. otherwise it is not execute anything we can’t understand
whether the program contain any error or system failure. That it can be
implemented by using if else
 If else statement if the specified condition is true allow to execute true
block and if the condition is false allow to execute false block
Syntax:
if (condition)
{
code to be executed if condition is true;
}
else
{
code to be executed if condition is false;
}

National Degree college, Nandyal Page 26


OOPs through Java BCA IIIrd semester

Else if ladder:
 Else if ladder is used to check more than one condition if the specified
condition is true then the associated true block statements are executed
otherwise if all the conditions are false the false block statements are
executed.
Syntax:
if (condition)
{
code to be executed if this condition is true;
}
else if (condition)
{
code to be executed if first condition is false and this condition is true;
}
else
{
code to be executed if all conditions are false;
}
Ex:
import java.io.*;
class WriteExample
{
public static void main(String []args)
{
int a=2; int b=3; int c=4;
if(a>b)
{
System.out.print(“a is bigger than b”);
}
else if(a>c)
{
System.out.print(“a is bigger than c”);
}
else{
System.out.print(“a is small”);
}
}}
Switch:
 switch statement is an alternative to the if-elseif-else statement, which
does almost the same thing.
 It is used to select only one particular statement from list of values
National Degree college, Nandyal Page 27
OOPs through Java BCA IIIrd semester

 It consists Case
Braek
Default keywords.
Syntax:
switch (n)
{
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}
import java.io.*;
class switchDemo
{
public static void main(String args[])
{
int i=2;
switch(i)
{
case 0:
System.out.println("monday");
break;
case 1:
System.out.println("tuesday");
break;
case 2:
System.out.println("wednes day");
break;
case 3:
System.out.println("thursday");
break;
National Degree college, Nandyal Page 28
OOPs through Java BCA IIIrd semester

case 4:
System.out.println("friday");
break;
case 5:
System.out.println("saturday");
break;
case 4:
System.out.println("sunday");
break;
default:
System.out.println("invalid day");
break;
}
}
}
Decision making and Looping statements:
 Decision making and Looping statements are used to execute the group
of statements repeatedly until the specified condition become false.
 Decision making and Looping statements are again classified into several
types
 While
 Do
 For
 For each
While:
 While loop is used to execute the group of statements repeatedly until
the specified condition become false
 It consists 3 parts
1. Initialization
2. Condition checking
3. Increment/ decrement
 While is an entry controlled loop. First it will checks the condition if the
specified condition is true it allows to enter into body of the loop.
Otherwise it will not allow to enter into body of the loop.
Syntax:
Initialization;
while (condition is true)

National Degree college, Nandyal Page 29


OOPs through Java BCA IIIrd semester

{
code to be executed;
Increment/decrement;
}
Ex:
import java.io.*;
class whileLoopTest
{
public static void main(String args[])
{
int j = 1;
while (j <= 10)
{
System.out.println(j);
j = j+2;
}
}
}
Do loop:
 Do loop is used to execute the group of statements repeatedly until the
specified condition become false
 It consists 3 parts
1. Initialization
2. Condition checking
3. Increment/ decrement
 Do loop is an exit controlled loop. First it will execute the statements
atleast once later it checks the condition if the specified condition is true
it allows to enter into body of the loop. Otherwise it will not allow to
enter into body of the loop.
Syntax:
do
{
code to be executed;
} while (condition is true);
Ex:
import java.io.*;

National Degree college, Nandyal Page 30


OOPs through Java BCA IIIrd semester

class dowhileLoopTest
{
public static void main(String args[])
{
int j = 10;
do
{
System.out.println(j);
j = j+1;
} while (j <= 10)
}
}
For loop:
 for loop is used to execute the group of statements repeatedly until the
specified condition become false
 It consists 3 parts
1. Initialization
2. Condition checking
3. Increment/ decrement
 for is an entry controlled loop. First it will checks the condition if the
specified condition is true it allows to enter into body of the loop.
Otherwise it will not allow to enter into body of the loop.
for (init counter; test counter; increment counter)
{
code to be executed for each iteration;
}
import java.io.*;
class forLoopTest
{
public static void main(String args[])
{
for (int j = 1; j <= 5; j++)
System.out.println(j);
}
}
Foreach:
 for each loop is used to execute the list of values in an array
foreach ($array as $value)

National Degree college, Nandyal Page 31


OOPs through Java BCA IIIrd semester

{
code to be executed;
}
import java.io.*;
class foreachDemo
{
public static void main(String args[])
{
int a[] = {10,15,20,25,30};
for (int i : a)
{
System.out.println(i);
}
}
Jumping statements:
 jumping statements are used to skip a specific part of the loop
 these are classified into several types
1. break
2. continue
1. break:
 break statement is used to immediately exit from middle of the loop
 it can be used in switch and looping statements.
import java.io.*;
class breakTest
{
public static void main(String args[])
{
for (int j = 0; j < 5; j++)
{
// come out of loop when i is 4.
if (j == 4)
break;
System.out.println(j);
}
System.out.println("After loop");
}
}

National Degree college, Nandyal Page 32


OOPs through Java BCA IIIrd semester

2. continue:
 continue statement is used to skip the following statements and
continue the next iteration
 it is mainly used in loops.
import java.io.*;
class continueTest
{
public static void main(String args[])
{
for (int j = 0; j < 10; j++)
{
// If the number is odd then bypass and continue with next value
if (j%2 != 0)
continue;
// only even numbers will be printed
System.out.print(j + " ");
}
}}
Arrays:
 An array is a special kind of variable. Which can store more than one
value into a single common variable
 The collection of similar data elements are stored into a single common
variable
 These similar data elements can be either integer or character or float
 These values are identified by their index or position
 An index or position starts from 0 to n-1
 An array consists 3 properties
1. Declaration of an array
2. Creating memory locations
3. Putting their values into their memory
1. Declaration of an array:
 To declare an array it follows a specific syntax
Syntax:
datatype arrayname[ ];
int marks[ ];
marks= new int[5];
or
int marks[ ]=new int[5];
initialization of an array:
int marks[ ]={10,20,30,40,50};

National Degree college, Nandyal Page 33


OOPs through Java BCA IIIrd semester

2. Creating memory locations:


 Based on the declaration of an array size it will create the memory
locations index
0
1
2
3
4

3. Putting their values into their memory


locations index
10 0
20 1
30 2
40 3
50 4

One-dimensional Array:
 An array contains only one subscription operator is called as an one
dimensional array
 It represents the data in collection of rows.
For example:

Syntax:
int marks[ ]={10,20,30,40,50};
or
int marks[ ];
marks= new int[5];
or
int marks[ ]=new int[5];
ex:
//Java Program to illustrate how to declare, instantiate, initialize
//and traverse the Java array.
import java.io.*;
class Testarray
{
public static void main(String args[])
National Degree college, Nandyal Page 34
OOPs through Java BCA IIIrd semester

{
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}
Ex2:
import java.io.*;
class Testarray1
{
public static void main(String args[])
{
int a[]={33,3,4,5};
for(int i=0;i<a.length;i++)
System.out.println(a[i]);
}
}
Two-dimensional Array:
 An array contains two subscription operators
 Two-dimensional arrays store the data in rows and columns:

Multi-dimensional Array:
This is a combination of two or more arrays or nested arrays. We can even use
more than two rows and columns using the following code:
Ex3:
//Java Program to demonstrate the addition of two matrices in Java
import java.io.*;
class AddMatrix
{
public static void main(String args[])
National Degree college, Nandyal Page 35
OOPs through Java BCA IIIrd semester

{
int row, col,i,j;
Scanner in = new Scanner(System.in);
System.out.println("Enter the number of rows");
row = in.nextInt();
System.out.println("Enter the number columns");
col = in.nextInt();
int mat1[][] = new int[row][col];
int mat2[][] = new int[row][col];
int res[][] = new int[row][col];
System.out.println("Enter the elements of matrix1");
for ( i= 0 ; i < row ; i++ )
{
for ( j= 0 ; j < col ;j++ )
mat1[i][j] = in.nextInt();
System.out.println();
}
System.out.println("Enter the elements of matrix2");
for ( i= 0 ; i < row ; i++ )
{
for ( j= 0 ; j < col ;j++ )
mat2[i][j] = in.nextInt();
System.out.println();
}
for ( i= 0 ; i < row ; i++ )
for ( j= 0 ; j < col ;j++ )
res[i][j] = mat1[i][j] + mat2[i][j] ;
System.out.println("Sum of matrices:-");
for ( i= 0 ; i < row ; i++ )
{
for ( j= 0 ; j < col ;j++ )
System.out.print(res[i][j]+"\t");
System.out.println();
}
}
}
Class:
 Class is a mandatory in java programming language
 A class is a group of objects which have common properties.
 Class is a collection of data members and functions into a single unit.

National Degree college, Nandyal Page 36


OOPs through Java BCA IIIrd semester

 Here data members are also called as field/variable and functions are
method
 A class in Java can contain:
 Fields
 Methods
 Constructors
 Blocks
 Nested class and interface
Syntax:
class <class_name>
{
Field[variable declarations];
Method declarations;
{
------}body of the fnction
}
}
Ex:
class Student
{
//defining fields
int id;//field or data member or instance variable
String name;
void display()
{
System.out.println(“hello my id is ”+id);
System.out.println(“hello my name is ”+sname);
}
}
Object creation:
 Instance of a class or duplication of a class
 Without class we cannot create an object
 To create an object it follows syntax
Syntax:
classname object; or
classname object=new classname;
 The new keyword is used to allocate memory at runtime. All objects get
memory in Heap memory area.
 All the data members and functions can be accessed through it’s objects

National Degree college, Nandyal Page 37


OOPs through Java BCA IIIrd semester

Obj.method();
Obj.variable;
Instance variable :
 A variable which is created inside the class but outside the method is
known as an instance variable.
 Instance variable doesn't get memory at compile time.
 It gets memory at runtime when an object or instance is created.
 That is why it is known as an instance variable.
Ex:
class Student
{
//defining fields
int id;//field or data member or instance variable
String name;
}
Ex:
class Student
{
int id;
String name;
public static void main(String args[])
{
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}
Ex2:
class Student
{
int id;
String name;
}
class TestStudent1
{
public static void main(String args[])
{
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
National Degree college, Nandyal Page 38
OOPs through Java BCA IIIrd semester

}
 There are 3 ways to initialize object in Java.
1. By reference variable
2. By method
3. By constructor
1. Initialization through reference variable
Initializing an object means storing data into the object.
Ex:
class Student
{
int id;
String name;
}
class TestStudent2
{
public static void main(String args[])
{
Student s1=new Student();
s1.id=101;
s1.name="Ramakrishna";
System.out.println(s1.id+" "+s1.name);
}
}
2. Initialization through method:
In this example, we are creating the two objects of Student class and initializing
the value to these objects by invoking the get method. Here, we are displaying
the state (data) of the objects by invoking the display () method.
Ex:
class Student
{
int rollno;
String name;
void get(int r, String n)
{
rollno=r;
name=n;
}
void display ()
{
System.out.println(rollno+" "+name);
}
National Degree college, Nandyal Page 39
OOPs through Java BCA IIIrd semester

}
class TestStudent4
{
public static void main(String args[])
{
Student s1=new Student();
Student s2=new Student();
s1.get (111,"Saanvi");
s2.get(222,"Krishna");
s1.display();
s2.display();
}
}
Access modifiers:
Access modifiers help to restrict the scope of a class, constructor, variable,
method, or data member.
It provides security, accessibility, etc to the user depending upon the access
modifier used with the element.
There are four types of access modifiers available in Java:
1. Default – No keyword required
2. Private
3. Protected
4. Public
Default Access Modifier
 When no access modifier is specified for a class, method, or data
member – It is said to be having the default access modifier by default.
 The data members, classes, or methods that are not declared using any
access modifiers i.e. having default access modifiers are accessible only
within the same package.
Private Access Modifier
 It can be specified by private keyword.
 The private access modifier can be accessible only within the class in
which they are declared.
 Any other class of the same package will not be able to access these
members.
 Top-level classes or interfaces can not be declared as private because
 private means “only visible within the enclosing class”.
 protected means “only visible within the enclosing class and any
subclasses”

National Degree college, Nandyal Page 40


OOPs through Java BCA IIIrd semester

Protected Access Modifier


 It can be specified by protected keyword.
 The methods or data members declared as protected are accessible
within the same package or subclasses in different packages.
Public Access modifier
 It can be specified by public keyword
 The public access modifier has the widest scope among all other access
modifiers.
 Classes, methods, or data members that are declared as public are
accessible from everywhere in the program.
 There is no restriction on the scope of public data members.
Constructors:
 It is a special type of method which contains same name as it’s class
name is called as Constructor
 It may or may not have parameters
 It does not contain any return type even void also
 Constructors are initiated automatically whenever the object of class is
created
Rules:
1. Constructor name must be the same as its class name
2. A Constructor does not have return type
3. A Java constructor cannot be abstract, static, final, and synchronized
Syntax:
class classname
{
------
classname()
{
Statements;
}
}
 Constructors are classified into 2 types
1. Default constructor
2. Parameterized constructor
Default Constructor:
 Default constructor does not have any parameters
 Constructors can also define with default arguments
 If any argument value not specify during the creation of an object then
the compiler will select the suitable constructor or default values
class Student

National Degree college, Nandyal Page 41


OOPs through Java BCA IIIrd semester

{
int sno;
String sname;
Student()
{
sno = 111;
sname = “Ramakrishna”;
}
void display()
{
System.out.println(sno+" "+sname);
}
public static void main(String args[])
{
Student s1 = new Student();
Student s2 = new Student();
s1.display();
s2.display();
}
}
Parameterized constructor:
 Parameterized constructor contains parameters
 It is necessary to initialize the various data members or elements to
different objects with different values when they are created
 It is achieved by passing parameters to that constructor functions when
the objects are created
class Student
{
int sno;
String sname;
Student(int n,String s)
{
sno = n;
sname = s;
}
void display()
{
System.out.println(sno+" "+sname);
}
public static void main(String args[])
{
National Degree college, Nandyal Page 42
OOPs through Java BCA IIIrd semester

Student s1 = new Student(111,"national");


Student s2 = new Student(222,"Ramakrishna");
s1.display();
s2.display();
}
}
Local and global variables:
 The variables which is declared inside the functions are called as local
variables
 The variables which is declared inside the class outside the functions are
called as global variables
Ex:
import java.io.*;
class sample
{
private double num1,num2;
sample(double x,double y)
{
num1=x;
num2=y;
}
void sum()
{
double res=num1+num2;
System.out.println(“sum=”+res);
}
}
class Methods
{
public static void main(String args[])
{
Sample s=new sample(10,22.5);
s.sum();
}
}
Unit - 3
Inheritance:
 Inheritance is a process of deriving or acquiring or inheriting the
properties from one class to another class is called as inheritance

National Degree college, Nandyal Page 43


OOPs through Java BCA IIIrd semester

 The class which inherits the properties of other is known as derived


class and the class whose properties are inherited is known as base
class.
 Base class, also known as parent class or super class.
 Derived class also called as child or sub class
 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
{
.....
.....
}
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.
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.
Reusability:
 As the name specifies, reusability is a mechanism which facilitates you to
reuse the fields and methods of the existing class when you create a new
class.
 You can use the same fields and methods already defined in the previous
class.
Single Inheritance
 Single inheritance consists of one parent class and one child class.
 The child class inherits parent class methods and data members.

National Degree college, Nandyal Page 44


OOPs through Java BCA IIIrd semester

Ex:
class Father //Base
{
public void house()
{
System.out.println("Have Own 2BHK House.");
}
}
class Son extends Father //Derived
{
public void car()
{
System.out.println("Have Own Car.");
}
}
public class single
{
public static void main(String args[])
{
Son o =new Son();
o.car();
o.house();
}
}
Multi-Level Inheritance
 It is a level by level inheritance
 Multi-level inheritance is like a parent-child inheritance relationship—
the difference is that a child class inherits another child class.

Ex:
//Multilevel Inheritance in Java
class GrandFather
{
National Degree college, Nandyal Page 45
OOPs through Java BCA IIIrd semester

public void house()


{
System.out.println("3 BHK House.");
}
}
class father extends GrandFather
{
public void land()
{
System.out.println("5 Arcs of Land..");
}
}
class son extends father
{
public void car()
{
System.out.println("Own Audi Car..");
}
}
public class multilevel
{
public static void main(String args[])
{
son o = new son();
o.car();
o.house();
o.land();
}
}
Hierarchical Inheritance
 Hierarchical inheritance is a represented in tree structure.
 The only difference is that multiple child classes inherit one parent class.

National Degree college, Nandyal Page 46


OOPs through Java BCA IIIrd semester

Hybrid Inheritance
 Hybrid inheritance can be a combination of any of the three types of
inheritances supported in Java.

Multiple Inheritance
 More than one base class and one derived class, but it is not supported
in Java, as multiple class inheritance causes ambiguities.

Polymorphism:
 Polymorphism is a greek word
 Poly means many and morphism means forms
 Polymorphism is nothing but ability to take more than one forms
(or) ability to exist in different forms
 Thus performing various tasks depending on the context. Because same
variable or same method can perform different tasks
Polymorphism using variables:
System.out.println(a+b);
Java compiler decides the data type of the result of expression a+b
depending on the data types of a,b
It may be a,b are integers and the result is integer or a,b are float returns
float or a,b are double it returns double
Polymorphism using method:
 Polymorphism using method overloading. i.e., same method name
different no of parameters or different type of parameters is called as
method overloading
 Same method performs different tasks
 When a method is called ,the control jumps to the method body at the
time of running program dynamically
Ex:
class sample
National Degree college, Nandyal Page 47
OOPs through Java BCA IIIrd semester

{
void add(int a,int b)
{
System.out.println(“sum of two is”+(a+b));
}
void add(int a,int b,int c)
{
System.out.println(“sum of three is”+(a+b+c));
}
}
class poly
{
public static void main(String args[])
{
sample s=new sample();
s.add(10,20);
s.add(10,20,30);
}
}
Ex2:
class OverloadDemo
{
void area(int a, int b, int c)
{
double temp = (a + b + c);
double s= temp/2;
double triarea = Math.sqrt(s*(s-a)*(s-b)*(s-c));
System.out.println( "\n Area of triangle with lenght of sides "+a+","
+b+ " and " +c+" is : "+ triarea);
}
void area(float x)
{
System.out.println("the area of the square is "+Math.pow(x, 2)+" sq units");
}
void area(float x, float y)
{
System.out.println("the area of the rectangle is "+x*y+" sq units");
}
void area(double x)
{
double z = 3.14 * x * x;
National Degree college, Nandyal Page 48
OOPs through Java BCA IIIrd semester

System.out.println("the area of the circle is "+z+" sq units");


}
}
class Overload
{
public static void main(String args[])
{
OverloadDemo ob = new OverloadDemo();
Ob.area(5,4,3);
ob.area(5);
ob.area(11,12);
ob.area(2.5);
}
}
Method overriding:
 When super class and sub class contains same function name and same
parameters is called as method overriding
 In method overriding , the java compiler does not decide which method
is called by the user, since it has to wait till an object to it’s sub class is
created
 After creating the object
 JVM has to bind the method call to an appropriate method
class one
{
void calculate(double x)
{
System.out.println(“square value = ”+(x*x));
}
}
class two extends one
{
void calculate(double x)
{
System.out.println(“square root = ”+Math.sqrt(x));
}
}
class poly
{
public static void main(String args[])
{
two t=new two();
National Degree college, Nandyal Page 49
OOPs through Java BCA IIIrd semester

t.calculate(25);
}
}
Polymorphism with static methods:
 A static method is a method whose single copy in memory is shared by
all the objects of the class
 Static method belongs to the class rather than to the objects
 So they are also called class methods
 When static methods are overloaded or overridden, since they do not
depend on objects
 The java compiler need not wait till the objects are created to
understand which method is called
Ex:
class one
{
static void calculate(double x)
{
System.out.println(“square value = ”+(x*x));
}
class two extends one
{
static void calculate(double x)
{
System.out.println(“square root = ”+Math.sqrt(x));
}
}
class poly
{
public static void main(String args[])
{
one o=new two();
o.calculate(25);
}
}
Polymorphism with private methods:
 Private methods are the methods which are declared by using the access
specifier “private”
 This access specifier makes the method not to be available outside the
class
 So other programmers cannot access the private methods
Polymorphism with final methods:
National Degree college, Nandyal Page 50
OOPs through Java BCA IIIrd semester

 Methods which are declared as “final” are final methods


 Final methods cannot be overridden, because they are not available to
the sub classes
 Therefore only method over loading is possible with final methods
Ex:
class A
{
final void method1()
{
System.out.println(“hello”);
}
}
class B
{
void method2()
{
A.method1();
}
}
Abstract Method in Java
 An abstract method does not contain any method body. It contains only
Method header
 An abstract class is a class that generally contains some abstract
methods and non-abstract methods (method with the body).
 Both abstract class and abstract methods should be declared by using
keyword abstract
 Since abstract classes contains incomplete methods. So it is not possible
to estimate the total memory required to create the object
 So JVM cannot create object to abstract classes
 We should create sub classes and all abstract methods should be
implemented in the sub classes
 Then it is possible to create object to sub classes
 A method which is declared as abstract and does not have
implementation is known as an abstract method.
 It can have constructors and static methods also.
 It can have final methods which will force the subclass not to change the
body of the method
Syntax:
abstract class classname
{
abstract void method();//no method body and abstract
National Degree college, Nandyal Page 51
OOPs through Java BCA IIIrd semester

Ex1:
abstract class Shape
{
abstract void draw();
}
class Rectangle extends Shape
{
void draw()
{
System.out.println("drawing rectangle");
}
}
class Circle1 extends Shape
{
void draw()
{
System.out.println("drawing circle");
}
}
class TestAbstraction1
{
public static void main(String args[])
{
Shape s=new Circle1();
s.draw();
}
}
Ex2:
abstract class Bank
{
abstract int getRateOfInterest();
}
class SBI extends Bank
{
int getRateOfInterest()
{
return 7;
}
}
National Degree college, Nandyal Page 52
OOPs through Java BCA IIIrd semester

class PNB extends Bank


{
int getRateOfInterest()
{
return 8;
}
}
class TestBank
{
public static void main(String args[])
{
Bank b;
b=new SBI();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
b=new PNB();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
}
}
Interface:
 An interface is a collection of operations which can be specified a service
from class is called as an interface
 An interface contains only abstract methods. Which are all incomplete
methods
 So it is not possible to create an object to interfaces
 In this case we create separate classes where we can implement all
methods of the interface
 These classes are called as implementation classes
 Implementation classes will have all the methods body
 So it is possible to create an object to implementation classes
 All the methods of an interface should be public
 It can be specified by an interface keyword. It uses implements through
classes by using implements keyword
1. It is used to achieve abstraction.
2. By interface, we can support the functionality of multiple inheritance.
3. It can be used to achieve loose coupling.
interface <interface_name>
{
// declare constant fields
// declare methods that abstract
// by default.
}
National Degree college, Nandyal Page 53
OOPs through Java BCA IIIrd semester

interface Drawable
{
void draw();
}
//Implementation: by second user
class Rectangle implements Drawable
{
public void draw()
{
System.out.println("drawing rectangle");
}
}
class Circle implements Drawable
{
public void draw()
{
System.out.println("drawing circle");
}
}
//Using interface: by third user
class TestInterface1
{
public static void main(String args[])
{
Drawable d=new Circle();//In real scenario, object is provided by method e.g.
getDrawable()
d.draw();
}
}
Ex2:
interface Bank

National Degree college, Nandyal Page 54


OOPs through Java BCA IIIrd semester

{
float rateOfInterest();
}
class SBI implements Bank
{
public float rateOfInterest()
{
return 9.15f;
}
}
class PNB implements Bank
{
public float rateOfInterest()
{
return 9.7f;
}
}
class TestInterface2
{
public static void main(String[] args)
{
Bank b=new SBI();
System.out.println("ROI: "+b.rateOfInterest());
}
}

interface Printable
{
void print();
}
interface Showable
{
void show();
}
class A7 implements Printable,Showable
National Degree college, Nandyal Page 55
OOPs through Java BCA IIIrd semester

{
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();
}
}
String:
 String is a sequence of characters or collection of characters.
 java.lang.String class is used to create a string object.
 There exists a primitive data type char in Java which is used to declare
character-type variables.
 It represents or stores a single character.
 But if we need to store any name or a sequence of characters used
String class
 There are two ways to create String object:
1. By string literal
2. By new keyword
String Literal:
 A literal, in computer science used for representing a value.
 Java String literal can be created and represented using the double-
quotes
 Java String literal is created by using double quotes.
For Example:
String s="welcome";
String s1="Welcome";
String s2="Welcome";//It doesn't create a new instance
 In the above-given example, we have declared a string variable called s
or s1 or s2 and initialized it with the string value "welcome".
 Now we will see the memory management of Strings in Java. The Strings
in Java are stored in a special place in heap called "String Constant Pool"
or "String Pool".
National Degree college, Nandyal Page 56
OOPs through Java BCA IIIrd semester

 string object created in the string constant pool when two strings are
created using the string literal method
 When s1 is initialized, the JVM checks the string constant pool for the
string value "welcome". If it's not present, a new string object is created
and stored in the pool.
 When s2 is initialized, the JVM checks the string constant pool for the
string value "welcome". Since it's already present (due to s1), a new
string value is not created. Instead, s2 points to the existing value.
new keyword:
 Strings can indeed be created using the new keyword in Java. When a
string is created with new, a new object of the String class is created in
the heap memory, outside the string constant pool.
 Unlike string literals, these objects are allocated separate memory space
in the heap, regardless of whether the same value already exists in the
heap or not.
String s=new String("Welcome");//creates two objects and one reference
variable
class StringExample
{
public static void main(String args[])
{
String s1="java";//creating string by Java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating Java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}
}
Ex2:
import java.io.*;
import java.util.*;
class strread
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
String str1[]=new String[10];
int n;
System.out.println(“enter how many strings”);
National Degree college, Nandyal Page 57
OOPs through Java BCA IIIrd semester

n=sc.nextInt();
for(int i=0;i<n;i++)
{
System.out.println(“enter a string”);
str1[i]=in.next();
}
System.out.println(“the entered strings are”);
for(String k:str1)
System.out.println(k);
}
}
String methods:
 The string class defines a no of methods that allow us to accomplish a
variety of string manipulations tasks
 The following table show s existing methods on string in a string class

Method Description
length() It returns the length of the string
charAt(int index) It returns the char value of the particular index as
mentioned.
substring(int It returns substring, which starts from begin index.
beginIndex)
substring(int It returns substring for given start index position and ends
beginIndex, int index.
endIndex)
equals(Object It checks the equality of string. It does so with the given
another) object.
String It concatenates the specified string like the above
concat(String str) example.
String replace(char It replaces all occurrences of the specified old char value.
old, char new) With new value.
indexOf(int ch) It returns the selected char value index.
contains() used to check if a string contains a specified substring.
join() used to join a group of strings using the joiner between
them.
compareTo() compares the given strings in the order of occurrence in
the dictionary

National Degree college, Nandyal Page 58


OOPs through Java BCA IIIrd semester

toUpperCase() used to convert the lowercase characters of the string to


the uppercase(or capital) characters.
toLowerCase() used to convert all the characters of the string to the
lowercase(or small) characters.
trim() used to trim (or remove) the extra white spaces from the
specified string from both the ends.
format() used to format the string as per the passed argument
import java.io.*;
class strdemo
{
public static void main(String args[])throws IOException
{
String s1,s2,s3;
Scanner sc=new Scanner(System.in);
System.out.println(“enter first string”);
s1=sc.next();
System.out.println(“enter second string in uppercase ”);
s2=sc.next();
System.out.println(“first string is”+s1);
System.out.println(“second string is”+s1);
System.out.println(“length of first string is”+s1.length());
System.out.println(“character at specified string s1 is”+.s1.charAt(2));
System.out.println(“concatenated string s1 and s2 is”+s1.concat(s2));
System.out.println(“substring with begin and end index”+s1.substring(3,6));
System.out.println(“substring with only begin index”+s1.substring(3));
System.out.println(“convert to uppercase is”+s1.toUpperCase());
System.out.println(“convert to lowercase is”+s1.toLowerCase());
System.out.println(“index of a string is”+s1.indexOf(‘a’));
System.out.println(“join of strings is”+String.join(“ -
”,”hai”,”welcome”,”to”,”java”);
System.out.println(“equals of s1 and s2 is”+s1.equals(s2));
System.out.println(“compare of s1 and s2 is”+s1.compareTo(s2));
}
}
Immutable:
 A String is an unavoidable type of variable while writing any application
program.
 String references are used to store various attributes like username,
password, etc.

National Degree college, Nandyal Page 59


OOPs through Java BCA IIIrd semester

 In Java, String objects are immutable. Immutable simply means not


allow to modifiable or unchangeable.
 Once String object is created its data or state can't be changed but a new
String object is created.
class Testimmutablestring
{
public static void main(String args[])
{
String s="Sachin";
s.concat(" Tendulkar");//concat() method appends the string at the end
System.out.println(s);//will print Sachin because strings are immutableobjects
}
}
String buffer:
 Java StringBuffer class is used to create mutable (modifiable) String
objects.
 The StringBuffer class in Java is the same as String class except it is
mutable i.e. it can be changed.
 It can be specified by StringBuffer
Syntax:
StringBuffer obj=new StringBuffer();
StringBuffer obj=new StringBuffer(“string”);
import java.io.*;
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
sb.delete(5,9);
System.out.println(sb);//prints Hello
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
sb.reverse();
System.out.println(sb);//prints reverse
}
}

National Degree college, Nandyal Page 60


OOPs through Java BCA IIIrd semester

StringBuffer methods:
Method Description
append(String s) It is used to append the specified string with this string.
The append() method is overloaded like append(char),
append(boolean), append(int), append(float),
append(double) etc.
insert(int offset, It is used to insert the specified string with this string at
String s) the specified position. The insert() method is
overloaded like insert(int, char), insert(int, boolean),
insert(int, int), insert(int, float), insert(int, double) etc
replace(int startIndex, It is used to replace the string from specified startIndex
int endIndex, String and endIndex.
str)

delete(int startIndex, It is used to delete the string from specified startIndex


int endIndex) and endIndex.
reverse() is used to reverse the string.
capacity() It is used to return the current capacity.
Unit - 4
Package:
 A package is nothing but a physical folder structure (directories) that
contains a group of related classes, interfaces, and sub-packages
according to their functionality.
 It provides a convenient way to organize your work.
 A java package is a collection of classes, interfaces and sub-packages.
 Package are classified into 2 types
1. Built-in package
2. User-defined package.
1.Built-in-package:
 Built-in Packages are already created by the system
 It is also called as pre defined packages
 There are many built-in packages such as java, lang, awt, javax, swing,
net, io, util, sql etc.
 These packages contain large numbers of classes and interfaces that
we used in java are known as Built-in packages.
java.sql: Provides the classes for accessing and processing data stored in a
database. Classes like Connection, DriverManager, PreparedStatement,
ResultSet, Statement, etc. are part of this package.

National Degree college, Nandyal Page 61


OOPs through Java BCA IIIrd semester

java.lang: Contains classes and interfaces that are fundamental to the


design of the Java programming language. Classes like String, StringBuffer,
System, Math, Integer, etc. are part of this package.
java.util: Contains the collections framework, some internationalization
support classes, properties, random number generation classes. Classes like
ArrayList, LinkedList, HashMap, Calendar, Date, Time Zone, etc. are part of
this package.
java.net: Provides classes for implementing networking applications.
Classes like Authenticator, HTTP Cookie, Socket, URL, URLConnection,
URLEncoder, URLDecoder, etc. are part of this package.
java.io: Provides classes for system input/output operations. Classes like
BufferedReader, BufferedWriter, File, InputStream, OutputStream,
PrintStream, Serializable, etc. are part of this package.
java.awt: Contains classes for creating user interfaces and for painting
graphics and images. Classes like Button, Color, Event, Font, Graphics,
Image, etc. are part of this package.

2. User defined package:


 The package keyword is used to create a package in java.
 The package which is defined by the user is called a User-defined
package.
 It contains user-defined classes and interfaces.
Syntax:
package packageName;
Here, packageName is the name of package. The package statement must
be the first line in a java source code file followed by one or more classes.
package myPackage;
public class A
{
// class body
}
National Degree college, Nandyal Page 62
OOPs through Java BCA IIIrd semester

//save as Simple.java
package mypack;
public class Simple
{
public static void main(String args[])
{
System.out.println("Welcome to package");
}
}
To Compile: javac -d . Simple.java
To Run: java mypack.Simple
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.
Accessing package:
 There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
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.
//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[])
{
National Degree college, Nandyal Page 63
OOPs through Java BCA IIIrd semester

A obj = new A();


obj.msg();
}
}
Ex:
package arithmetic;
public class MyMath
{
public int add(int x,int y)
{
return x+y;
}
public int sub(int x,int y)
{
return x-y;
}
public int mul(int x,int y)
{
return x*y;
}
public double div(int x,int y)
{
return (double)x/y;
}
public int mod(int x,int y)
{
return x%y;
}
}
Compile:d:/java>javac –d . MyMath.java
 Now package is created in current directory
 After that import this package into another program or application
Ex2:save as b.java
import arithmetic.*;
class Test
{
public static void main(String as[])
{
MyMath m=new MyMath();
System.out.println(m.add(8,5));

National Degree college, Nandyal Page 64


OOPs through Java BCA IIIrd semester

System.out.println(m.sub(8,5));
System.out.println(m.mul(8,5));
System.out.println(m.div(8,5));
System.out.println(m.mod(8,5));
}
}
To Compile:
d:\java> set classpath=
d:\java> javac b.java
another
d:\java> java b
d:\java> javac -d c:\classes Simple.java
To Run:
To run this program from e:\source directory, you need to set classpath of the
directory where the class file resides.
d:\java> set classpath=c:\classes;.;
d:\java> java mypack.Simple
Another way to run this program by -classpath switch of java:
d:\java> java -classpath c:\classes mypack.Simple
Thread:
 Threads are light weight process because they utilize minimum
resources of the system i.e., it takes less memory and less processor
time
 Thread represents a separate path of execution of a group of statements
 The java program is a collection of statements, which are executed by
JVM in one by one
 This execution is called as Thread. Because JVM uses a thread to execute
these statements
 This means every java program always a thread running internally
 This thread is used by JVM to execute the program statements
 It allows to execute more than one thread at a time is called as multi
threading
 Multi threading is a powerful programming tool that makes java
distinctly different from programming languages
 It enables program to do multiple things at a time
 They can be divide the large program into threads and execute them in
parallel
Ex:
class current
{

National Degree college, Nandyal Page 65


OOPs through Java BCA IIIrd semester

public static void main(String args[])


{
System.out.println(“let us find current thread”);
Thread t=Thread.currentThread();
System.out.println(“current thread=”+t);
System.out.println(“its name is =”+t.getName());
}
}
 A thread represents execution of statements in two ways
1. Single tasking
2. Multi tasking
1. Single tasking:
 A task means doing some calculation, processing etc
 Generally a task involves execution of a group of statements
For example in single tasking environment only one task is given to the
processor at a time. A student who goes to lab to write some programs . He
types his first program. It may takes some 10 minutes when we is typing
program the micro processor sitting idle without any work. After typing is
completed we gives the program to processor. The processor executes
within a fraction of milliseconds even 100 lines of program. similarly type
second program takes 10 to 15 minutes then again it goes to idle state.
In a single tasking only one task is given to the processor i.e., we are
wasting a lot of processing time.
To overcome this problem that are implemented multi tasking
2. Multi tasking
 To use the processor’s time in an optimum way, we can give it
several jobs at a time.
 To execute more than one task at a time is called as multi tasking
Suppose there are 4 tasks that we want to execute. We load them into
memory then the memory is divided into 4 parts and the jobs are loaded there
, the micro processor has to execute them all at a time
 Multi tasking is of two types
a. Process based multi tasking
b. Thread based multi tasking
 In process based multi tasking, several programs are executed at a time
by the micro processor
 In thread based multi tasking several parts of the same program is
executed at a time, by the micro processor
Creating a thread:
 It is simple. Threads are implemented in the form of objects that contain
a method called run()
National Degree college, Nandyal Page 66
OOPs through Java BCA IIIrd semester

 The run() method is the heart and soul of any thread


 It makes up the entire body of a thread and is the only method in which
thread and is the only method in which threads behavior can be
implemented
Syntax:
public void run()
{
Statements;
}
 We can create a thread in two different ways
1. Extends Thread class
2. Implements Runnable
1. Extends Thread class:
 To create a thread is to create a new class that extends Thread
 And then create an instance of that class
 The extending class must override run() method
 The run() method which is entry point for new thread
 It must also call start() function to begin execution of the new thread
Syntax:
class mythread extends Thread
{
public void run()
{
Statements;
}
}
Starting a thread:
mythread mt=new mythread();
mt.start();
class A extends Thread
{
public void run()
{
For(int i=1;i<=5;i++)
{
System.out.println(“from thread A “+i);
}
System.out.println(“exit from A “);
}
}
class B extends Thread
National Degree college, Nandyal Page 67
OOPs through Java BCA IIIrd semester

{
public void run()
{
For(int j=1;j<=5;j++)
{
System.out.println(“from thread B “+j);
}
System.out.println(“exit from B “);
}
}
class threadtest
{
public static void main(String args[])
{
A a=new A();
a.start();
B b=new B();
b.start();
}
}
Starting a thread:
mythread mt=new mythread();
mt.start();
2. Implements Runnable:
 The easiest way to create a thread is to create a class that implements
Runnable interface
 Runnable abstract a unit of executable code
 We can construct a thread runnable, a class need only implement a
single method called run() which is declared like following
Syntax:
class mythread implements Runnable
{
public void run()
{
Statements;
}
}
Ex:
class X implements Runnable
{
public void run()
National Degree college, Nandyal Page 68
OOPs through Java BCA IIIrd semester

{
for(int i=1;i<=5;i++)
{
System.out.println(“from thread X “+i);
}
System.out.println(“exit from X “);
}
}
class runnabletest
{
public static void main(String args[])
{
X obj=new X();
Thread t1=new Thread(obj);
t1.start();
System.out.println(“end of main thread”);
}
}
Thread lifecycle:
 Thread exists in different states which are collectively called thread life
cycle
1. New born state
2. Runnable state
3. Running state
4. Blocked state
5. Dead state

National Degree college, Nandyal Page 69


OOPs through Java BCA IIIrd semester

1. New born state:


 When we create a thread object, the thread is born and is said to be in
new born state
 Thread is not yet scheduled for running
 At this state we can do only one of the following things with it
 Schedule is for running using start() method
 Kill it is using stop() method
2. Runnable state:
 The runnable state means that the thread is ready for execution and is
waiting for the availability of the processor
 i.e., the thread has joined the queue of threads that are waiting for
execution
 if all threads have equal priority , then they are given time slots for
execution in round robin fashion(FirstComeFirstServe) manner.
 This process of assigning time to threads is known as time-slicing
3. Running state:
 Running means that the processor has given it’s time to thread for it’s
execution
 The thread runs until it complete control on it’s preempted by a higher
priority thread
 At this state running thread in any one of the following situations
1. Suspend() 2. Resume() 3. Sleep() 4. Wait() 5. Notify()
4. Blocked state:
 This happens when the thread is suspended , sleeping or waiting in
order to satisfy certain requirements
 A blocked thread is considered “not runnable” but not dead and
therefore fully qualified to run again
5. Dead state:
 Every thread has a life cycle. A running thread ends it’s life when it is
completed executing it’s run() thread
 It is a natural death, however we can kill it by sending the stop message
to it at any state once dead this thread is not runnable again
Thread priority:
 In java each thread is assigned priority, which effects the order in which
it is scheduled for running
 The threads of the same priority are given equal to assign by the java
scheduler and therefore share the processor on a FirstComeFirstServe
manner
 Java permits us to set priority of a thread using the setPriority() method
Syntax:

National Degree college, Nandyal Page 70


OOPs through Java BCA IIIrd semester

Threadname.setPriority(int number);
Where int number is an integer value to which the thread priority is set
value 1 to 10.
The thread class define several priority constants
MIN_PRIORITY=1
NORM_PRIORITY=5
MAX_PRIORITY=10
Unit-5
Exception Handling:
 An Exception is a run time error
 An exception is an error event that can happen during the execution of a
program and disrupts its normal flow.
Types of Errors:
 Errors are classified into two types
Compile time errors
 All syntax errors will be detected and displayed by java compiler
therefore these errors are called as compile time errors
 missing semi-colon(s),
 missing parenthesis,
 Misspelling of identifiers
 Missing double quotes in string
 Use of undeclared variables
 Incompatible types in assignment/initialization
Run time errors
 An error which is ocuured while executing or running the program is
called as runtime errors
 Such as dividing an integer by zero,
 Accessing that element that is out of the bounds of an array
 Trying to store a value into an array of incompatible class or type
 Passing parameters that is not a valid range or value for a method
 Trying to illegally change the state of a thread
 Attempting to use negative size of an array
 It can handle by using some keywords
1. try
2. throw
3. catch
 The try statement allows you to define a block of code to be tested for
errors while it is being executed.
 The throw statement allows you to create a custom error.
 The throw statement is used together with an exception type.

National Degree college, Nandyal Page 71


OOPs through Java BCA IIIrd semester

 There are many exception types available in Java: ArithmeticException,


FileNotFoundException, ArrayIndexOutOfBoundsException,
SecurityException, etc:
 The catch statement allows you to define a block of code to be executed,
if an error occurs in the try block.
 The try and catch keywords come in pairs:
Syntax:
try {
// Block of code to try
}
catch(Exception e) {
// Block of code to handle errors
}
public class Main
{
public static void main(String[ ] args)
{
Try
{
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
}
catch (Exception e)
{
System.out.println("index out of bound.");
}
}
}
Finally:
 The finally statement lets you execute code, after try...catch, regardless
of the result:
public class Main
{
public static void main(String[] args)
{
try
{
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
}
catch (Exception e)
National Degree college, Nandyal Page 72
OOPs through Java BCA IIIrd semester

{
System.out.println("Something went wrong.");
}
finally
{
System.out.println("The 'try catch' is finished.");
}
}
}
Sr.No. Exception & Description

1 ArithmeticException
Arithmetic error, such as divide-by-zero.

2 ArrayIndexOutOfBoundsException
Array index is out-of-bounds.

3 IllegalThreadStateException
Requested operation not compatible with the current thread state.

4 NegativeArraySizeException
Array created with a negative size.

5 NullPointerException
Invalid use of a null reference.

6 NumberFormatException
Invalid conversion of a string to a numeric format.

7 StringIndexOutOfBounds
Attempt to index outside the bounds of a string.
class Ex1
{
public static void main (String [] args)
{
try
{
String s1=args[0];
String s2=args[1];
int n1=Integer.parseInt (s1);
int n2=Integer.parseInt (s2);
National Degree college, Nandyal Page 73
OOPs through Java BCA IIIrd semester

int n3=n1/n2;
System.out.println ("DIVISION VALUE = "+n3);
}
catch (ArithmeticException Ae)
{
System.out.println ("DONT ENTER ZERO FOR DENOMINATOR...");
}
catch (NumberFormatException Nfe)
{
System.out.println ("PASS ONLY INTEGER VALUES...");
}
catch (ArrayIndexOutOfBoundsException Aioobe)
{
System.out.println ("PASS DATA FROM COMMAND PROMPT...");
}
finally
{
System.out.println ("I AM FROM FINALLY...");
}
}
}
Applet:
 An applet is a special type of program to create GUI and that runs inside
the web browser
Or
 An applet is a special type of program that embedded in the web page
 An applet is a GUI(Graphical User Interface)
 Applets are designed to be embedded with in an HTML page using
<applet> tag
 Applets are small programs that are primarily used in internet
computing
 It can perform an arithmetic operations, display graphics, play sounds
accept user input create animation etc
 An applet can be transported over the internet from one computer to
another computer and run using appletviewer or any web browser
 Applets can be run in two different ways
i. By html file
ii. By appletviewer
 It can run inside the web browser
 We can embed applets into web pages in two ways
1. We can write our own applets and embed them into web apges
National Degree college, Nandyal Page 74
OOPs through Java BCA IIIrd semester

2. We can download an applet from remote computer system and then


embed them into web browser
 An applet developed locally and stored in local system is known as local
applet. When a web page trying to find a local applets and therefore the
local system does not require internet connection
 A remote applet, which is developed by someone else and stored on a
remote computer connected to the internet. We can download remote
applet into our system via internet and run it
Applet = java byte code + HTML page

 Any applet in java class that extends the java.applet.*


 To create an applet we need to write a java program and compile
it to get byte code. Then it should embed into a HTML page
 An applet class does not have any main() method
 It is viewed by using JVM. The JVM can use either a plug-in of the
web browser
 JVM creates an instance of the applet class and invokes init()
method to initialize an applet

Ex:
Step 1:
import java.awt.*;
import java.applet.*;
public class simple extends Applet
{
public void paint(Graphics g)
{
g.drawString(“a simple applet”,50,50);
}
}
Step 2: create by executing applet(.class file)
javac simple.java
Step 3: design a web page using HTML(create.html)
<html>
<head>
<title> sample applet</title>
</head>
<body>
<applet code=”simple.class” width=”200” height=”200”>

National Degree college, Nandyal Page 75


OOPs through Java BCA IIIrd semester

</applet>
</body>
</html>
Step 4: appletviewer create.html
Or
import java.awt.*;
import java.applet.*;
/*
<applet code=”simple.class” width=”200” height=”200”>
</applet>
*/
public class simple extends Applet
{
public void paint(Graphics g)
{
g.drawString(“welcome to applet”,50,50);
}
}
D:/java>javac simple.java
D:/java>appletviewer simple
Ex;
import java.awt.*;
import java.applet.*;
public class national extends Applet
{
Public void init()
{
setName(“National degree college”);
}
public void paint(Graphics g)
{
setBackground(Color.GREEN);
setForeground(Color.RED);
g.drawRoundRect(10,30,120,120,2,3);
g.drawString(“National jr and Degree colleges”,50,100);
}}
D:/java>javac national.java
<html>
<body>
<applet code=”national.class” width=”300” height=”300”></applet>
</body>
National Degree college, Nandyal Page 76
OOPs through Java BCA IIIrd semester

</html>
Common methods used in displaying output:
Java Graphics class includes methods for drawing many different types of
shapes from simple lines to polygon, oval, Recatangle, string etc.,
drawLine() Drawing a straight line from the point
drawArc() Draws a arc bounded by the rectangle with the upper left
drawPolygon() Draws a polygon
drawRect() Draws a rectangle
drawOval() Draws a oval
drawRoundRect() Draws arounded rectangle with corners
drawstring() Displays a text string
fillOval() Darw a filled oval
fillPolygon() Draw a filled polygon
fillRect() Draw a filled rectangle
fillRoundRect() Drawing a filled Rounded Rectangle
getColor() Retrieves the current drawing color
setColor() Set the drawing color
Ex:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class add extends Applet implements ActionListener
{
TextField t1=new TextField(10);
TextField t2=new TextField(10);
TextField t3=new TextField(10);
Label l1=new Label(“first no”);
Label l2=new Label(“second no”);
Label l3=new Label(“sum”);
Button b=new Button(“ADD”);
public void init()
{
t1.setForeground(Color=Red);
add(l1);
add(t1);
add(l2);
add(t2);
add(l3);
add(t3);
add(b);

National Degree college, Nandyal Page 77


OOPs through Java BCA IIIrd semester

b.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b)
{
int n1=Integer.ParseInt(t1.getText());
int n2=Integer.ParseInt(t2.getText());
t3.setText(“ ”+(n1+n2));
}
}
Step 2:
<html>
<body>
<applet code=”add.class” width=”300” height=”300”></applet>
</body>
</html>
Applet life cycle ex:
import java.awt.*;
import java.applet.*;
public class lifecycle extends Applet
{
private static int initcall,startcall,paintcall,destroycall;
public void init()
{
setBackground(Color.cyan);
setForeground(Color.red);
initcall=initcall+1;
}
public void start()
{
startcall=startcall+1;
}
public void paint(Graphics g)
{
paintcall=paintcall+1;
g.drawString(“init method is called for :”+initcall,0,14);
g.drawString(“start method is called for :”+startcall,0,30);
g.drawString(“paint method is called for :”+paintcall,0,46);
g.drawString(“stop method is called for :”+stopcall,0,62);
g.drawString(“destroy method is called for :”+destroy,0,78);
National Degree college, Nandyal Page 78
OOPs through Java BCA IIIrd semester

showStatus(“demo applet life cyle”);


public void stop()
{
stopcall=stopcall+1;
}
public void destroy()
{
destroycall=destroycall+1;
}
}
Applet life cycle:
There are various stages of an applet lifecycle.
1. Born or init state
2. Running state
3. Idle state
4. Dead or destroy state
5. Paint
1. init():
init() is initial state when new applet is born or created. An applet is
initialized only once in it’s life time
2. Running:
Start() method is called after init(). An applet achieves the running state
when the system calls the start() method. An applet may also start when
it is in idle state
3. Idle state:
An applet comes in Idle state when it’s execution has been stopped
either implicitly. An applet is explicitly stopped when we call stop()
method to stop it’s execution
4. Dead state:
An applet is in dead state when it has been removed from the memory.
This can be done by using destroy() method
5. Paint():
Applet moves to the display state whenever it has to perform some
output operations on the screen. This happens immediately after the
applet enters into the running state to paint() method
The paint() method must carry Graphics object

National Degree college, Nandyal Page 79

You might also like