BCA Java Unit1to5
BCA Java Unit1to5
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
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
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
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
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
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
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
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.
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
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.
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
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 constantsrepresentsten values(0 to 9)
Hexa Decimal Integer constantsrepresents 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
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
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 );
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
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
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:
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;
}
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)
{
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.*;
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)
{
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");
}
}
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};
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.
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
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”
{
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
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
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
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
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
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
{
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
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)
//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
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
{
{
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
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.
{
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
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”>
</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);
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