Java New Complete Notes NEP With Programs - Processed
Java New Complete Notes NEP With Programs - Processed
Java New Complete Notes NEP With Programs - Processed
UNIT – 1
Introduction to JAVA
OBJECT ORIENTED PROGRAMMING (OOP) :-
The major motivating factor in the invention of object oriented is to remove some of the
flaws encountered in the procedural oriented approach. Object oriented programming
treats data as a critical element in the program development and does not allow it to flow
freely around the system. It ties data more closely to the functions that operate on it, and
protects it from accidental modifications from outside functions.
Object oriented programming allows a decomposition of a problem into a number
entity called objects and then builds data and functions around these objects. The data of an
object can be accessed only by the functions associated with that object. However, functions
of one object can access the functions of other objects.
CONCEPTS OF OOP’S
The prime purpose of Java programming was to add object orientation to the C
programming language, which is in itself one of the most powerful programming
languages.
The core of the pure object-oriented programming is to create an object, in code, that
has certain properties and methods. While designing Java modules, we try to see whole
world in the form of objects. For example, a car is an object, which has certain properties
such as color, number of doors, and the like. It also has certain methods such as accelerate,
brake, and so on.
There are a few principle concepts that form the foundation of object-oriented
programming:
1. Object.
2. Classes.
3. Inheritance.
4. Data Abstraction.
5. Data Encapsulation.
6. Polymorphism.
7. Dynamic Binding.
8. Message Passing
Message
Dynamic Passing
Binding
OBJECT:
Any real world entity which can have some characteristics or which can perform
some work is called as Object. Object is the basic unit of object-oriented programming.
Objects are identified by its unique name. An object represents a particular instance of a
class. There can be more than one instance of a class. Each instance of a class can hold its
own relevant data.
For example consider we have a Class of Cars under which Santro Xing, Alto and Wagener
represents individual Objects. In this context each Car Object will have its own, Model, Year
of Manufacture, Color, Top Speed, Engine Power etc., which form Properties of the Car class
and the associated actions i.e., object functions like Start, Move, and Stop form the Methods
of Car Class.
No memory is allocated when a class is created. Memory is allocated only when an object is
created, i.e., when an instance of a class is created.
DATA ABSTRACTION:
Data abstraction refers to providing only essential information to the outside world
and hiding their background details, i.e., to represent the needed information in program
without presenting the details.
Data abstraction is a programming (and design) technique that relies on the
separation of interface and implementation.
Let's take one real life example of a TV, which you can turn on and off, change the
channel, adjust the volume, and add external components such as speakers, VCRs, and DVD
players, BUT you do not know its internal details, that is, you do not know how it receives
signals over the air or through a cable, how it translates them, and finally displays them on
the screen.
Thus, we can say a television clearly separates its internal implementation from its
external interface and you can play with its interfaces like the power button, channel
changer, and volume control without having zero knowledge of its internals.
Example:
TV operation
It is encapsulated with cover and we can operate with remote and no need to
open TV and change the channel.
Here everything is in private except remote so that anyone can access not to operate and change the
things in TV.
INHERITANCE OR REUSABILITY
The mechanism that allows us to extend the definition of a class without making any
physical changes to the existing class is inheritance.
Inheritance lets you create new classes from existing class. Any new class that you create
from an existing class is called derived class; existing class is called base class.
The inheritance relationship enables a derived class to inherit features from its base
class. Furthermore, the derived class can add new features of its own. Therefore, rather than
create completely new classes from scratch, you can take advantage of inheritance and
reduce software complexity.
Multiple Inheritance: It is the inheritance hierarchy wherein one derived class inherits from
multiple base classes. But java does not support multiple inheritance.
Multilevel Inheritance: It is the inheritance hierarchy wherein subclass acts as a base class
for other classes.
Hybrid Inheritance: The inheritance hierarchy that reflects any legal combination of other
four types of inheritance.
Example1:
A Teacher behaves to student.
A Teacher behaves to his/her seniors.
Here teacher is an object but attitude is different in different situation.
Example2:
Below is a simple example of the above concept of polymorphism:
6 + 10
The above refers to integer addition.
The same + operator can also be used for floating point addition:
7.15 + 3.78
TYPES OF POLYMORPHISM
There are two types of polymorphism one is compile time polymorphism and the
other is run time polymorphism. Compile time polymorphism is functions and operators
overloading. Runtime time polymorphism is done using inheritance and virtual functions.
Here are some ways how we implement polymorphism in Object Oriented programming
languages.
Method/Function overloading
METHOD/FUNCTION OVERLOADING
Using a single function name to perform different types of tasks is known as function
overloading. Using the concept of function overloading, design a family of functions with one
function name but with different argument lists. The function would perform different
operations depending on the argument list in the function call. The correct function to be
invoked is determined by checking the number and type of the arguments but not on the
function type.
Run-time:
The appropriate member function could be selected while the programming is
running. This is known as run-time polymorphism. The run-time polymorphism is
implemented with inheritance.
Method/Function overriding
METHOD/FUNCTION OVERRIDING
If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in java.
In other words, if subclass provides the specific implementation of the method that
has been provided by one of its parent class, it is known as method overriding.
DYNAMIC BINDING
Binding refers connecting the function call to a function definition/implementation.
Or It is a link between the function call and function definition.
Types of Binding
Static Binding.
Dynamic Binding.
STATIC BINDING:
By default, matching of function call with the correct function definition happens at
compile time. This is called static binding or early binding or compile-time binding. Static
binding is achieved using function overloading and operator overloading. Even though
DYNAMIC BINDING:
Java provides facility to specify that the compiler should match function calls with
the correct definition at the run time; this is called dynamic binding or late binding or run-
time binding. Dynamic binding is achieved using virtual functions. Base class pointer points
to derived class object. And a function is declared virtual in base class, then the matching
function is identified at run-time using virtual table entry.
MESSAGE PASSING
Message passing nothing but sending and receiving of information by the objects
same as people exchange information. So this helps in building systems that simulate real
life. Following are the basic steps in message passing.
Creating classes that define objects and its behaviour.
Creating objects from class definitions
Establishing communication among objects
In OOPs, Message Passing involves specifying the name of objects, the name of the function,
and the information to be sent.
For example: student.mark (name). Here student is object, mark is message, and name is
information.
APPLICATIONS OF OOP:
Applications of OOP are beginning to gain importance in many areas. The most
important application is user interface design. Real business systems are more complex and
contain many attributes and methods, but OOP applications can simplify a complex
problem.
1. User interface design such as windows, menu.
2. Real Time Systems
3. Simulation and Modeling
4. Object oriented databases
5. AI and Expert System
6. Neural Networks and parallel programming
7. Decision support and office automation system
8. Computer animation
9. To design Compiler
10. To access relational data base
11. To develop administrative tools and system tools
12. To develop computer games
ABSTRACTION ENCAPSULATION
1. Abstraction solves the problem in the 1. Encapsulation solves the problem in the
design level. implementation level.
2. Abstraction is used for hiding the 2. Encapsulation means hiding the code
unwanted data and giving relevant data. and data into a single unit to protect the
data from outside world.
3. Abstraction lets you focus on what the 3. Encapsulation means hiding the
object does instead of how it does it internal details or mechanics of how an
object does something.
Introduction to Java
Java is a programming language and a platform. Java is a high level, robust, object-oriented
and secure programming language.
History of Java
The history of Java is very interesting. Java was originally designed for interactive
television, but it was to advanced technology for the digital cable television industry at the
time.
1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project
in June 1991. The small team of sun engineers called Green Team.
2) Initially it was designed for small, embedded systems in electronic appliances like set-top
boxes.
3) Firstly, it was called "Greentalk" by James Gosling, and the file extension was .gt.
4) After that, it was called Oak and was developed as a part of the Green project.
5) Why Oak? Oak is a symbol of strength and chosen as a national tree of many countries
like the U.S.A., France, Germany, Romania, etc.
6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies.
Features of Java
1. Compiled and Interpreted
2. Platform Independent and Portable
3. Object-Oriented
4. Robust and Secured
5. Distributed
6. Simple, Small and Familiar
7. Multithreaded & Interactive
8. High Performance
9. Dynamic & Extensible
10. Scalability and Performance
Here the MyFirstProgram.class generated on any machine(OS) can be run on any other
machine having same or different OS. This is why we call java is a platform independent
language.
Object Oriented
We Know that is purely OOP Language that is all the Code of the java Language is Written
into the classes and Objects So For This feature java is Most Popular Language because it
also Supports Code Reusability, Maintainability etc. Java is not pure object oriented
language because it supports primitive data types (byte, int, float etc) which are not objects.
Distributed
Java is also called a distributed language. This means java programs running on one
machine can easily access the resources (files, java objects etc) of other machine on
internet/network. Java provides class libraries for high-level support of networking. We
can also say, same or different applications running on different JVM on different machines
can interact with each other for sharing data over the internet. RMI and EJB are mostly used
for distributed programming.
High Performance
Java architecture is defined in such a way that it reduces overhead during the
runtime and at some time java uses Just In Time (JIT) compiler where the compiler
compiles code on-demand basics where it only compiles those methods that are called
making applications to execute faster.
C vs C++ vs Java
The languages are based on each other but still, they are different in design and
philosophy. The following table describes the major differences between C, C++, and Java.
It will help you to select which language you have to learn.
The first reason is that the Object oriented programming language should only have
objects whereas java contains 8 primitive data types like char, boolean, byte, short,
int, long, float, double which are not objects. These primitive data types can be used
without the use of any object. (Eg. int x=10; System.out.print(x.toString());)
The second reason related to the static keyword. In pure object oriented language,
we should access everything by message passing (through objects). But java contains
static variables and methods which can be accessed directly without using objects.
That means, when we declare a class as 'static' then it can be referenced without the
use of an object.
The Virtual machine code is not machine specific. The machine specific code is generated
by Java interpreter by acting as an intermediary between the virtual machine and real
machines as shown above diagram.
For compiling and running the program, we have to use following commands:
a) javac (Java compiler) In java, we can use any text editor for writing program and
then save that program with “.java” extension. Java compiler is a platform independent. Java
compiler convert the source code or program in bytecode and interpreter convert “.java”
file in “.class” file. Syntax: C:\javac filename.java If my filename is “abc.java” then the
syntax will be
C:\javac abc.java
b) java (Java Interpreter) As the Java compiler compiles the source code into the Java
bytecode. In the same way, the Java interpreter converts or translates the bytecode into the
machine-understandable format i.e. machine code, after that the machine code interacts
with the operating system. Java interpreter is a platform dependent.
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 20 of 215
Object Oriented Concepts using Java
C:\java ab
Overview of Java
Java is a general purpose, object oriented programming language
Stand-alone program
Stand-alone programs are simple programs
They written in java to carry out certain tasks on a standalone local computer
Where it is used?
According to Sun, 3 billion devices run java. There are many devices where java is
currently used. Some of them are as follows:
1. Desktop Applications such as acrobat reader, media player, antivirus etc.
2. Web Applications such as irctc.co.in, javatpoint.com etc.
Documentation Section
It is used to improve the readability of the program. It consists of comments in Java
that include basic information such as the method’s usage or functionality to make it easier
for the programmer to understand it while reviewing or debugging the code. A Java
comment is not necessarily limited to a confined space, it can appear anywhere in the code.
The compiler ignores these comments during the time of execution and is solely meant for
improving the readability of the Java program.
There are three types of comments that Java supports
Single line Comment
Multi-line Comment
Documentation Comment
Let us look at an example to understand how we can use the above-mentioned comments in
a Java program.
// a single line comment is declared like this
/* a multi-line comment is declared like this
and can have multiple lines as a comment */
/** a documentation comment starts with a delimiter and ends with */
This statement declares that all the classes and interfaces defined in this source file are a part
of the student package. Only one package can be declared in the source file.
Import Statement
Many predefined classes are stored in packages in Java, an import statement is used
to refer to the classes stored in other packages. An import statement is always written after
the package statement but it has to be before any class declaration.
We can import a specific class or classes in an import statement. Take a look at the example
to understand how to import statement works in Java.
Interface Section
This section is used to specify an interface in Java. It is an optional section which is
mainly used to implement multiple inheritances in Java. An interface is a lot similar to a class
in Java but it contains only constants and method declarations.
An interface cannot be instantiated but it can be implemented by classes or extended by other
interfaces.
interface stack
{
void push(int item);
void pop();
}
Class Definition
A Java program may contain several class definitions, classes are an essential part of
any Java program. It defines the information about the user-defined classes in a program.
A class is a collection of variables and methods that operate on the fields. Every program in
Java will have at least one class with the main method.
Let’s analyse the above program line by line to understand how it works.
Comments
To improve the readability, we can use comments to define a specific note or
functionality of methods, etc for the programmer.
Braces
The curly brackets are used to group all the commands together. To make sure that
the commands belong to a class or a method.
String[] args
It is an array where each element is a string, which is named as args. If you run the
Java code through a console, you can pass the input parameter. The main() takes it as an
input.
System.out.println();
The statement is used to print the output on the screen where the system is a
predefined class, out is an object of the PrintWriter class. The method println prints the text
on the screen with a new line. All Java statements end with a semicolon.
Step2: The Java programs are store with the extension of mainclassname.java
Step4: For compiling programs always use javac filename.java in the command prompt
The Java compiler also recognizes and subsequently removes comments and whitespaces.
Example:
public class Hello
{
public static void main(String args[])
{
System.out.println(“Welcome in Java”); //print welcome in java
}
}
In above Example,
The source code contains tokens such as public, class, Hello, {, public, static, void,
main, (, String, [], args, {, System, out, println(, “welcome in Java”, }, }.
The resulting tokens· are compiled into Java bytecodes that is capable of being run
from within an interpreted java environment.
Token are useful for compiler to detect errors.
When tokens are not arranged in a particular sequence, the compiler generates an
error message.
Identifiers are,
Sequence of Uppercase letters(A to Z)
Sequence of Lowercase letters (a to z)
Numbers (0 to 9)
Underscore (_)
Dollar Symbol ($)
Valid Invalid
$age #age (does not begin with any other symbol except _ $ )
You cannot use keywords like int, for, class, etc as variable name (or identifiers) as they are
part of the Java programming language syntax. Here is the complete list of all keywords in
Java programming.
JAVA
CONSTANTS
Non-Numeric or
NUMERIC
CHARACTER
CONSTANTS CONSTANTS
SINGLE
INTEGER REAL/FLOAT STRING
CHARACTER
CONSTANTS CONSTANTS CONSTANTS CONSTANTS
Integer constants
An integer constant refers to a sequence of digits. It includes,
1. Decimal integer
2. Octal integer
3. Hexadecimal integer
1. Decimal Integer
It consists of a set of digits, 0 through 9, preceded by an optional minus sign.
Valid examples of integer constants are, 123, -321, 0 ,654321
Embedded spaces, commas & non-digit characters are not permitted b/w
digits.
Mantissa e exponent
Character constants
Single Character constants
A single character constant or simply character constant contains a single character
enclosed within a pair of single quote marks.
The characters may be alphabets, digits, special characters and blank spaces.
String constants
A string constant is a sequence of characters enclosed between double quotes. The
characters may be alphabets, digits, special characters and blank spaces.
EXAMPLE PROGRAM:
class Simple
{
public static void main(String[] args)
{
int a=10;
int b=10;
int c=a+b;
System.out.println(c);
}
}
Where static and final are the non-access modifiers. The double is the data type and PRICE
is the identifier name in which the value 432.78 is assigned.
In the above statement, the static modifier causes the variable to be available without an
instance of its defining class being loaded and the final modifier makes the variable fixed.
Here a question arises that why we use both static and final modifiers to declare a
constant?
If we declare a variable as static, all the objects of the class (in which constant is defined)
will be able to access the variable and can be changed its value. To overcome this problem,
we use the final modifier with a static modifier.
When the variable defined as final, the multiple instances of the same constant value will
be created for every different object, which is not desirable.
When we use static and final modifiers together, the variable remains static and can be
initialized once. Therefore, to declare a variable as constant, we use both static and final
modifiers. It shares a common memory location for all objects of its containing class.
short
Short data type is a 16-bit signed two's complement integer
Minimum value is -32,768 (-2^15)
Maximum value is 32,767 (inclusive) (2^15 -1)
Short data type can also be used to save memory as byte data type. A short is 2 times
smaller than an integer
Default value is 0.
Example: short s = 10000, short r = -20000
int
Int data type is a 32-bit signed two's complement integer.
Minimum value is - 2,147,483,648 (-2^31)
Maximum value is 2,147,483,647(inclusive) (2^31 -1)
Integer is generally used as the default data type for integral values unless there is a
concern about memory.
The default value is 0
Example: int a = 100000, int b = -200000
long
Long data type is a 64-bit signed two's complement integer
Minimum value is -9,223,372,036,854,775,808(-2^63)
Maximum value is 9,223,372,036,854,775,807 (inclusive)(2^63 -1)
This type is used when a wider range than int is needed
Default value is 0L
Example: long a = 100000L, long b = -200000L
float
Float data type is a single-precision 32-bit IEEE 754 floating point
Float is mainly used to save memory in large arrays of floating point numbers
Default value is 0.0f
Float data type is never used for precise values such as currency
Example: float f1 = 234.5f
double
double data type is a double-precision 64-bit IEEE 754 floating point
This data type is generally used as the default data type for decimal values, generally
the default choice
Double data type should never be used for precise values such as currency
Default value is 0.0d
Example: double d1 = 123.4
boolean
boolean data type represents one bit of information
There are only two possible values: true and false
This data type is used for simple flags that track true/false conditions
Default value is false
Example: boolean one = true
char
char data type is a single 16-bit Unicode character
Variables are nothing but reserved memory locations to store values. This means that
when you create a variable you reserve some space in the memory.
Local Variables
Local variables are declared in methods, constructors, or blocks.
Local variables are created when the method, constructor or block is entered and the
variable will be destroyed once it exits the method, constructor, or block.
Access modifiers cannot be used for local variables.
Local variables are visible only within the declared method, constructor, or block.
There is no default value for local variables, so local variables should be declared
and an initial value should be assigned before the first use.
Example
class Functionoverloading
{
public void add(int x, int y)
{
int sum; //local variables
sum=x+y;
System.out.println(sum);
}
class Mainfunover
{
public static void main(String args[])
{
Functionoverloading obj = new Functionoverloading();
obj.add(10,20);
obj.add(10.40,10.30);
}
}
Output:
Instance Variables
Instance variables are declared in a class, but outside a method, constructor or any
block.
When a space is allocated for an object in the heap, a slot for each instance variable
value is created.
Instance variables are created when an object is created with the use of the keyword
'new' and destroyed when the object is destroyed.
Instance variables can be accessed directly by calling the variable name inside the
class.
import java.io.*;
public class Employee
{
// this instance variable is visible for any child class.
public String name;
// salary variable is visible in Employee class only.
private double salary;
name = empName;
}
// The salary variable is assigned a value.
public void setSalary(double empSal)
{
salary = empSal;
}
// this method prints the employee details.
public void printEmp()
{
System.out.println("name : " + name );
System.out.println("salary :" + salary);
}
Class/Static Variables
Class variables also known as static variables are declared with the static keyword
in a class, but outside a method, constructor or a block.
There would only be one copy of each class variable per class, regardless of how
many objects are created from it.
Static variables are created when the program starts and destroyed when the
program stops.
Visibility is similar to instance variables. However, most static variables are declared
public since they must be available for users of the class.
Static variables can be accessed by calling with the class
name ClassName.VariableName.
Example
/* Program with class variable that is available for all instances of a class. Use static
variable declaration. Observe the changes that occur in the object’s member variable
values.*/
class StaticDemo
{
static int count=0; //static variable declaration
public void increment()
{
count++;
}
public static void main(String args[])
{
StaticDemo obj1=new StaticDemo ();
StaticDemo obj2=new StaticDemo ();
obj1.increment();
obj2.increment();
System.out.println("Obj1: count is="+obj1.count);
System.out.println("Obj2: count is="+obj2.count);
}
}
Output:
Operators
An operator is a special symbol that tells the compiler to perform a specific
mathematical or logical operation on one or more operands where an operand can be an
expression. An operation is an action(s) performed on one or more operands that evaluates
mathematical expressions or change the data.
There are many types of operators in java, which are given below:
Arithmetic Operators:
Arithmetic operators are used to perform arithmetic operations on the operands. The
following operators are known as Java arithmetic operators.
+ Addition 10+20 = 30
- Subtraction 20-10 = 10
/ Division 20/10 = 2
Example:
class OperatorExample
{
public static void main(String args[])
{
System.out.println(10*10/5+3-1*4/2);
}
}
Output: 21
Example
public class Test
{
public static void main(String args[])
{
int a = 10,b = 20;
System.out.println("a == b = " + (a == b) );
System.out.println("a != b = " + (a != b) );
System.out.println("a > b = " + (a > b) );
System.out.println("a < b = " + (a < b) );
System.out.println("b >= a = " + (b >= a) );
}
}
Output
a == b = false
a != b = true
a > b = false
a < b = true
b >= a = true
Bitwise Operators:
Bitwise operators are used to performing the manipulation of individual bits of a
number. They can be used with any integral type (char, short, int, etc.).
= Assign 10+10 = 20
Syntax:
variable = Expression ? expression1 : expression2
// ternary operator
result = (februaryDays == 28) ? "Not a leap year" : "Leap year";
System.out.println(result);
}
}
Output
Leap year
In the above example, we have used the ternary operator to check if the year is a leap year
or not.
Other operators
Besides these operators, there are other additional operators in Java.
Operator Description
Expressions
Expressions are a combination of variables, constants & operators arranged as per
the syntax of the language.
Java can handle any complex mathematical expressions.
Evaluation of expression:
Expressions are evaluated using an assignment statement of the form
Variable=expression;
Variable is any valid java variable name.
When the statement is encountered, the expression is evaluated first & the result then
replaces the previous value of the variable on the left-hand side.
Ex:
X=a*b-c;
Y=b/c*a;
Z=a-b/c + d;
The blank spaces around an operator are optional & it is added only to improve
readability.
The variables a, b, c, d must be defined before they are used in the expression.
Example:
class OperatorExample
{
public static void main(String args[])
{
System.out.println(10*10/5+3-1*4/2); //expression
}
}
Output:
21
o if statement
o if-else statement
o Nested if-else statement
o if-else-if ladder
Syntax:
if(condition)
{
//code to be executed
}
Example:
public class IfExample
{
public static void main(String[] arg)
{
Syntax:
if(Boolean_expression 1)
{
// Executes when the Boolean expression 1 is true
if(Boolean_expression 2)
{
// Executes when the Boolean expression 2 is true
}
}
Example:
public class Test
{
public static void main(String args[])
{
int x = 30;
int y = 10;
if( x == 30 )
{
if( y == 10 )
{
System.out.print("X = 30 and Y = 10");
}
}
}
}
The if-else-if ladder statement executes one condition from multiple statements.
Syntax:
if(condition1)
{
//code to be executed if condition1 is true
}
else if(condition2)
{
//code to be executed if condition2 is true
}
else if(condition3)
{
//code to be executed if condition3 is true
}
...
Else
{
//code to be executed if all the conditions are false
}
Output:
C grade
Syntax:
switch(expression)
{
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
code to be executed if all cases are not matched;
}
Output: 20
Iteration Statement:
Syntax:
for(initialization;condition;incr/decr)
{
//code to be executed
}
import java.util.*;
class Prime
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter the no");
int n = sc.nextInt();
int i=1,c=0;
for(i=1;i<=n;i++)
{
if(n%i==0)
{
c++;
}
}
if(c==2)
{
System.out.println(n+" is a PRIME no");
}
else
{
System.out.println(n+" is a NOT a prime no");
}
}
}
Output:
Syntax:
while(condition)
{
//code to be executed
}
Example:
/* Program to list the factorial of the
numbers 1 to 10. To calculate the factorial
value, use while loop.*/
do-while Loop
The Java do-while loop is used to iterate a part of the program several times. If the
number of iteration is not fixed and you must have to execute the loop at least once, it is
recommended to use do-while loop. The Java do-while loop is executed at least once because
condition is checked after loop body.
Syntax:
do
{
//code to be executed
}while(condition);
Example:
public class DoWhileExample
{
public static void main(String[] args)
{
int i=1;
do
{
System.out.println(i);
i++;
}while(i<=8);
}
}
Output:
12345678
Statements or loops perform a set of operations continually until the control variable
will not satisfy the condition.
But if we want to break the loops when condition will satisfy then Java give a
permission to jump from one statement to end of loop or beginning of loop as well
as jump out of a loop.
“break” keyword use for exiting from loop and “continue” keyword use for
continuing the loop.
Break statement is used to terminate from a loop while a test condition is true.
1. Break statement
2. Continue statement
Break Statement
The Java break is used to break loop or switch statement. It breaks the current flow of
the program at specified condition. In case of inner loop, it breaks only inner loop.
Syntax:
jump-statement;
break;
Example:
public class BreakExample
{
public static void main(String[] args)
{
for(int i=1;i<=10;i++)
{
if(i==5)
{
break;
}
System.out.println(i);
}
}
}
Output:
1234
Syntax:
jump-statement;
continue;
Example:
public class ContinueExample
{
public static void main(String[] args)
{
for(int i=1;i<=10;i++){
if(i==5)
{
continue;
}
System.out.println(i);
}
}
}
Output:
1 2 3 4 6 7 8 9 10
Java Methods
A method is a block of code or collection of statements or a set of code grouped
together to perform a certain task or operation. It is used to achieve the reusability of code.
We write a method once and use it many times. We do not require to write code again and
again. It also provides the easy modification and readability of code, just by adding or
removing a chunk of code. The method is executed only when we call or invoke it.
Method Declaration :
In general, method declarations has six components:
1. Modifier: It defines the access type of the method i.e. from where it can be accessed in
your application. In Java, there 4 types of access specifiers.
public: It is accessible in all classes in your application.
protected: It is accessible within the class in which it is defined and in its subclass/es
private: It is accessible only within the class in which it is defined.
2. The return type: The data type of the value returned by the method or void if does not
return a value.
3. Method Name: the rules for field names apply to method names as well, but the
convention is a little different.
4. Parameter list: Comma-separated list of the input parameters is defined, preceded with
their data type, within the enclosed parenthesis. If there are no parameters, you must use
empty parentheses ().
5. Exception list: The exceptions you expect by the method can throw, you can specify
these exception(s).
6. Method body: it is enclosed between braces. The code you need to be executed to
perform your intended operations.
1. Predefined Method: In Java, predefined methods are the method that is already defined
in the Java class libraries is known as predefined methods. It is also known as the standard
library method or built-in method. We can directly use these methods just by calling
them in the program at any point. Some pre-defined methods are length(), equals(),
compareTo(), sqrt(), etc.
2. User-defined Method: The method written by the user or programmer is known as a
user-defined method. These methods are modified according to the requirement.
1. Static Method
A method that has static keyword is known as static method. In other words, a
method that belongs to a class rather than an instance of a class is known as a static
method. We can also create a static method by using the keyword static before the method
name.
The main advantage of a static method is that we can call it without creating an
object. It can access static data members and also change the value of it. It is used to create
an instance method. It is invoked by using the class name. The best example of a static
method is the main() method.
2. Instance Method
The method of the class is known as an instance method. It is a non-static method
defined in the class. Before calling or invoking the instance method, it is necessary to create
an object of its class.
3. Abstract Method
The method that does not has method body is known as abstract method. In other
words, without an implementation is known as abstract method. It always declares in
the abstract class. It means the class itself must be abstract if it has abstract method. To
create an abstract method, we use the keyword abstract.
/* Program to add two integers and two float numbers. When no arguments are supplied,
give a default value to calculate the sum. Use function overloading.*/
class Functionoverloading
{
public void add(int x, int y)
{
int sum;
sum=x+y;
System.out.println(sum);
}
public void add(double a, double b)
{
double total;
total=a+b;
System.out.println(total);
}
}
class Mainfunover
{
public static void main(String args[])
{
Functionoverloading obj = new Functionoverloading();
obj.add(10,20);
obj.add(10.40,10.30);
}
}
Output:
/* Program to add two integers and two float numbers. When no arguments are supplied,
give a default value to calculate the sum. Use function overloading.*/
class Functionoverloading
{
public void add(int x, int y)
{
int sum;
sum=x+y;
System.out.println(sum);
}
public void add(int a, int b, int c)
{
int total;
total=a+b+c;
System.out.println(total);
}
}
class Mainfunover
{
public static void main(String args[])
{
Functionoverloading obj = new Functionoverloading();
obj.add(10,20);
obj.add(10,20,30);
}
}
Output:
30
60
The class Math contains methods for performing basic numeric operations such as
the elementary exponential, logarithm, square root, and trigonometric functions. Unlike
some of the numeric methods of class StrictMath, all implementations of the equivalent
functions of class Math are not defined to return the bit-for-bit the same results. This
relaxation permits better-performing implementations where strict reproducibility is not
required.
// return a power of 2
System.out.println("exp of a is: " +Math.exp(x));
Java array is an object, which contains elements of a similar data type. Additionally, the
elements of an array are stored in a contiguous memory location. It is a data structure where
we store similar elements. We can store only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd
element is stored on 1st index and so on.
Advantages
o Code Optimization: It makes the code optimized; we can retrieve or sort the data
efficiently.
o Random access: We can get any data located at an index position.
Disadvantages
o Size Limit: We can store only the fixed size of elements in the array. It does not grow
its size at runtime. To solve this problem, collection framework is used in Java, which
grows automatically.
Creation of arrays
To allocate space for an array element use below general form or syntax.
arrayName = new type[size];
Where arrayName is the name of the array and type is a valid java datatype
and size specifies the number of elements in the array.
Example: physics = new int[10];
Above statement will create an integer of an array with ten elements that can be
accessed by physics.
physics[0]
Structure of one dimensional array physics[1]
Note that array indexes begins with zero.
physics[2]
That means if you want to access 1st element of an array use zero as
physics[3]
an index.
To access 3rd element refer below example. physics[4]
physics[2] = 10; // it assigns value 10 to the third element of an array. physics[5]
java also allows an abbreviated syntax to declare an array. General physics[6]
form or syntax of is is as shown below.
physics[7]
physics[8]
physics[9]
Initialization of an Array
The final step is to put values into the array created. This process is known as
initialization.
Syntax:
arrayname[subscript] = value;
Example:
physics[0]=12;
physics[1]=15;
physics[2]=16;
physics[3]=18;
physics[4]=20;
physics[5]=23;
physics[6]=25;
physics[7]=27;
physics[0] 12
physics[1] 15
physics[2] 16
physics[3] 18
physics[4] 20
physics[5] 23
physics[6] 25
physics[7] 27
physics[8] 30
physics[9] 35
Example Program:
class Testarray
{
public static void main(String args[])
{
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}
Output:
10
20
70
40
50
Syntax:
DataType ArrayName[][];
ArrayName = new DataType[][];
(or)
DataType ArrayName[][] = new DataType[][];
Data_type:
This will decide the type of elements it will accept.
For example, If we want to store integer values then, the Data Type will be declared
as int, If we want to store Float values then, the Data Type will be float etc.
Array_Name:
This is the name you want to give it to array.
For example Car, students, age, marks, department, employees etc
Intialization of Array:
int[][] a = {
{1, 2, 3},
{4, 5, 6, 9},
{7},
};
Example:
class MultidimensionalArray
{
public static void main(String[] args)
{
int[][] a = {
{1, 2, 3},
{4, 5, 6, 9},
{7},
};
System.out.println("Length of row 1: " + a[0].length);
System.out.println("Length of row 2: " + a[1].length);
System.out.println("Length of row 3: " + a[2].length);
}
}
Output:
Length of row 1: 3
Length of row 2: 4
Length of row 3: 1
UNIT 2
OBJECTS AND CLASSES
Introduction
Java is an object-oriented programming language. Anything we wish to represent in
java program must be encapsulated in a class that defines the state and behavior of program
components known as objects. Classes create objects and objects use methods to
communicate between them. The core concept of the object-oriented approach is to break
complex problems into smaller objects.
An object is any entity that has a state and behavior. For example, a bicycle is an object. It
has
Java Class
A class is a user defined blueprint or template for which objects are created. Before
we create an object, we first need to define the class. We can think of the class as a sketch
(prototype) of a house. It contains all the details about the floors, doors, windows, etc. Based
on these descriptions we build the house. House is the object. Since many houses can be
made from the same description, we can create many objects from a class.
Defining a Class
Java provides a reserved keyword class to define a class. The keyword must be
followed by the class name. Inside the class, we declare methods and variables.
Example:
Fields Declaration:
Data is encapsulated in a class by placing data fields inside the body of the class.
These variables called instance variable.
Because they created whenever an object of the class is instantiated.
Ex:
class Rectangle
{
int length;
int width; [also can declare as int length , width;]
}
Methods Declaration:
A class with only data fields (no methods) has no life.
Add methods that are necessary for manipulating the data in the class.
Methods are declared inside the body of the class after the declaration of instance
variables.
Syntax:
return_type methodname(parameter-list)
{
Method–body;
}
Method declarations have four basic parts:
1. The name of the method (method name).
2. The type of the value the method returns(type).
3. A list of parameters(parameter – list).
4. The body of the method.
The type specifies the type of value the method world return. It could be void type,
if the method does not return any value.
The method name is a valid identifier.
The parameter list is always enclosed in parenthesis. The list contains variable and
its types.
Ex: void getdata (int a, int b);
The body actually describes the operation to be performed on the data.
Example:
Class Rectangle
{
int length;
int width; // field declaration
void getdata(int x, int y) // method declaration
{
length = x;
width = y;
}
}
Return type is void because it does not return any value.
We pass two integer values to the method, which are then assigned to the instance variable.
Ex:
class Access
{
int x;
void method1()
{
int y;
x = 10; //legal
y= x; // legal
}
void method2()
{
int z;
x=5; // legal
z =10; // legal
y =1; // illegal couldn’t access y.
}
}
CREATING OBJECTS:
An object in java is essentially a block of memory that contains space to store all the
instance variable.
Objects in java are created using the new operation or operator or keyword.
The new operator creates an object of the specified class and returns a reference to
that object.
Example:
Rectangle rect1; // Declare the object.
Rect1 = new Rectangle(); // instantiate the object.
Syntax:
objectname.variablename = value;
objectname.methodname(parameter-list);
Where,
object name = object.
variable name = name of the instance variable.
Two object rect1 and rect2 store different values as shown below.
rect1 rect2
rect1.length 15 rect2.length 20
rect1.width 10 rect2.width 12
Output:
Area1=150
Area2=240
Example2:
Class employee //class declaration
{
int id; //Field declaration (Instance variable)
string name; //Field declaration (Instance variable)
float salary; //Field declaration (Instance variable)
void insert(int i,string n,float s) //Method1 declared
{
id=i;
name=n;
salary=s;
}
void display ( ) //Method2 declared
{
system.out.println(id+” “+name” “+salary);
}
public class Emp
{
public static void main (string [ ]args)
{
Employee e1= new Employee (); //Object1 declared
Employee e2=new employee (); //Object2 declared
Employee e3=new employee (); //Object3 declared
output:
101 ajeet 45000
102 irfan 25000
103 nakul 55000
CONSTRUCTOR:
Java constructors or constructors in Java is a terminology been used to construct
something in our programs.
Constructor in java is a special type of method that is used to initialize the object.
Java constructor is invoked at the time of object creation. It constructs the values i.e.
provides data for the object that is why it is known as constructor.
Constructs construct the values for object.
Constructors are invoked implicitly when you instantiate objects.
A constructor can be overloaded but cannot be overridden.
2. No argument/Parameter Constructor
A constructor that don’t have parameters is known as no parameterized constructor.
No Parameter constructor is used to provide default values to the distinct objects.
If a constructor does not accept any parameters, it is known as a no-argument
constructor.
Output:
Bike is created
Syntax:
<class_name>(parameter list)
{
Constructor body
}
Example: (parameterized constructor)
In this example, we have created the constructor of Student class that have two
parameters. We can have any number of parameters in the constructor.
class Student
{
int id;
String name;
Student(int i, String n)
{
id = i;
name = n;
}
void display()
{
System.out.println(id+" "+name);
Note : A lot of people mix up the default constructor for the no-argument constructor, but they are
not the same in Java. Any constructor created by the programmer is not considered a default
constructor in Java.
There are many differences between constructors and methods. They are given below.
Java Constructor Java Method
Constructor must not have return type. Method must have return type.
Constructor name must be same as the Method name may or may not be same as
class name. class name.
obj1.getName();
obj2.getName();
}
}
Finalize is an Object class method in Java. The finalize() method is a non-static and
protected method of java.lang.object class. In java, the Object class is superclass of all java
classes. Being an object class method finalize() method is available for every class in Java.
Hence, Garbage Collector can call finalize() method on any java object for clean-up activity.
Finalize method in java is used to release all the resources used by the object before it is
deleted/destroyed by the Garbage collector. finalize() is not a reserved keyword in java, it's
a method. Once the clean-up activity is done by the finalize() method garbage collector
immediately destroys the java object. Java Virtual Machine(JVM) permits invoking
of finalize() method only once per object. Once object is finalized JVM sets a flag in the object
header to say that it has been finalized, and won't finalize it again. If user tries to
use finalize() method for the same object twice, JVM ignores it.
Before starting with syntax and coding of finalize() method in Java. Let's first see the terms
like Garbage collector, Clean up activity related to the method.
@Override
protected void finalize()
{
System.out.println("Finalize method is called.");
}
}
Output:
Garbage collector is called
Garbage Collector
The garbage collector is a part of Java Virtual Machine(JVM). Garbage
collector checks the heap memory, where all the objects are stored by JVM, looking for
unreferenced objects that are no more needed. And automatically destroys those objects.
Garbage collector calls finalize() method for clean up activity before destroying the object.
Java does garbage collection automatically; there is no need to do it explicitly, unlike other
programming languages.
The garbage collector in java can be called explicitly using the following method:
System.gc();
System.gc() is a method in java that invokes garbage collector which will destroy the
unreferenced objects. System.gc() calls finalize() method only once for each object.
The major advantage of performing clean-up before garbage collection is data resources or
network connections that are linked to unreferenced object are revoked and can be used
again. Cleanup ensures resources are not linked to objects unnecessary and helps JVM in
boosting memory optimization and speed.
Private
Any method, property or constructor with the private keyword is accessible from the
same class only. This is the most restrictive access modifier and is core to the concept of
encapsulation. All data will be hidden from the outside world. Private signifies “just visible
inside the enclosing class“.
Protected
If we declare a method, property or constructor with the protected keyword, we can
access the member from the same package (as with package-private access level) and in
addition from all subclasses of its class, even if they lie in other packages. Protected
signifies “just noticeable inside the enclosing class and any subclasses“.
Public
If we add the public keyword to a class, method or property then we're making it
available to the whole world, i.e. all other classes in all packages will be able to use it. This
is the least restrictive access modifier:
class MemberAccess
{
public static void main(String args[])
{
sub t=new sub();
t.setValue(1,2,3,4);
t.base_view();
t.derived_view();
}
}
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
1) String Literal
Java String literal is created by using double quotes. For Example:
1. String s="welcome";
Each time you create a string literal, the JVM checks the "string constant pool" first. If the
string already exists in the pool, a reference to the pooled instance is returned. If the string
doesn't exist in the pool, a new string instance is created and placed in the pool.
For example:
1. String s1="Welcome";
2. String s2="Welcome";//It doesn't create a new instance
In the above example, only one object will be created. Firstly, JVM will not find any string
object with the value "Welcome" in string constant pool that is why it will create a new
object. After that it will find the string with the value "Welcome" in the pool, it will not create
a new object but will return the reference to the same instance.
Note: String objects are stored in a special memory area known as the "string constant
pool".
Why Java uses the concept of String literal?
To make Java more memory efficient (because no new objects are created if it exists already
in the string constant pool).
2) By new keyword
1. String s=new String("Welcome");//creates two objects and one reference variable
In such case, JVM will create a new string object in normal (non-pool) heap memory, and
the literal "Welcome" will be placed in the string constant pool. The variable s will refer
to the object in a heap (non-pool).
public class StringExample
{
Character class
The Character class is a wrapper that is used to wrap a value of the primitive type
char in an object. An object of class Character contains a single field whose type is char.
This class provides a large number of static methods for determining a character's
category (lowercase letter, digit, etc.) and for converting characters from uppercase to
lowercase and vice versa. This class is located into java.lang package.
Files Class
The File class is an abstract representation of file and directory pathname. A
pathname can be either absolute or relative.
The File class have several methods for working with directories and files such as
creating new directories or files, deleting and renaming directories or files, listing the
contents of a directory etc.
this keyword
The this keyword refers to the current object in a method or constructor. The most
common use of the this keyword is to eliminate the confusion between class attributes and
parameters with the same name (because a class attribute is shadowed by a method or
constructor parameter). If you omit the keyword in the example above, the output would
be "0" instead of "5".
UNIT-3
INHERITANCE AND POLYMORPHISM
Inheritance:
Inheritance in java is a mechanism in which one object acquires all the properties and
behaviours of parent object. Inheritance represents the IS-A relationship, also known
as parent child relationship.
The mechanism of deriving a new class from an old class is called inheritance.
The old class is known as the Base class or Parent class or Super class
The new class is called the Derived class or Child class or Sub class
The inheritance allows subclasses to inherit all the variables and methods of their
parent classes.
Inheritance allows us to reuse of code, it improves reusability in your java application.
Syntax
class Subclass-name extends Superclass-name
{
//methods and fields
}
The extends keyword indicates that you are making a new class that derives from an
existing class. The meaning of "extends" is to increase the functionality
Example:
class Employee
{
float salary=40000;
}
class Programmer extends Employee
{
int bonus=10000;
public static void main(String args[])
{
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Output:
Programmer salary is:40000.0
Bonus of programmer is:10000
Types of Inheritance:
On the basis of class, there can be three types of inheritance in java
1. Single
2. Multilevel
3. Hierarchical
Multiple and hybrid inheritance is supported through interface only.
class TestInheritance2
{
public static void main(String args[])
{
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}
}
Hierarchical Inheritance:
As in the below diagram that a class has more than one child classes (sub classes).
In other words more than one child classes have the same parent class then such kind
of inheritance is known as hierarchical.
Class A is a parent class of class B, class C and class D.
One Parent class has many sub classes.
Example:
class Animal // PARENT CLASS
{
void eat()
{
System.out.println("eating...");
}
}
class TestInheritance3
{
public static void main(String args[])
{
Cat c=new Cat();
c.meow();
c.eat();
}
}
Output:
meowing...
eating...
Benefits of Inheritance
Inheritance helps in code reuse. The child class may use the code defined in the
parent class without re-writing it.
Inheritance can save time and effort as the main code need not be written again.
Inheritance provides a clear model structure which is easy to understand.
An inheritance leads to less development and maintenance costs.
With inheritance, we will be able to override the methods of the base class so that the
meaningful implementation of the base class method can be designed in the derived
class. An inheritance leads to less development and maintenance costs.
In inheritance base class can decide to keep some data private so that it cannot be
altered by the derived class.
In this example, we have defined the run method in the subclass as defined in the
parent class but it has some specific implementation.
The name and parameter of the method is same and there is IS-A relationship
between the classes, so there is method overriding.
class Test2
{
public static void main(String args[])
{
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 100 of 215
Object Oriented Concepts using Java
}
}
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9
Polymorphism
"Poly" means "many" and "morph" means "form". Polymorphism is the ability of an
object (or reference) to assume (be replaced by) or become many different forms of object.
Example: method/function overloading & method/function overriding.
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 101 of 215
Object Oriented Concepts using Java
Example1:
A Teacher behaves to student.
A Teacher behaves to his/her seniors.
Here teacher is an object but attitude is different in different situation.
Example2:
Below is a simple example of the above concept of polymorphism:
6 + 10
The above refers to integer addition.
The same + operator can also be used for floating point addition:
7.15 + 3.78
Types of Polymorphism
There are two types of polymorphism one is compile time polymorphism and the
other is run time polymorphism. Compile time polymorphism is method/function
overloading. Runtime time polymorphism is done using inheritance and method/function
overriding. Here are some ways how we implement polymorphism in Object Oriented
programming languages.
Method/Function Overloading
Using a single function name to perform different types of tasks is known as function
overloading. Using the concept of function overloading, design a family of functions with one
function name but with different argument lists. The function would perform different
operations depending on the argument list in the function call. The correct function to be
invoked is determined by checking the number and type of the arguments but not on the
function type.
Run-time polymorphism
The appropriate member function could be selected while the programming is
running. This is known as run-time polymorphism. The run-time polymorphism is
implemented with inheritance.
Method/Function overriding
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 102 of 215
Object Oriented Concepts using Java
Method/Function Overriding
If subclass (child class) has the same method as declared in the parent class, it is
known as method overriding in java.
In other words, if subclass provides the specific implementation of the method that
has been provided by one of its parent class, it is known as method overriding.
Generic Programming
Generics means parameterized types. The idea is to allow type (Integer, String, …
etc., and user-defined types) to be a parameter to methods, classes, and interfaces. Using
Generics, it is possible to create classes that work with different data types. An entity such
as class, interface, or method that operates on a parameterized type is a generic entity.
Why Generics?
The Object is the superclass of all other classes, and Object reference can refer to any
object. These features lack type safety. Generics add that type of safety feature. We will
discuss that type of safety feature in later examples.
Generics in Java are similar to templates in C++. For example, classes like HashSet,
ArrayList, HashMap, etc., use generics very well. There are some fundamental differences
between the two approaches to generic types.
Generic Method: Generic Java method takes a parameter and returns some value after
performing a task. It is exactly like a normal function, however, a generic method has type
parameters that are cited by actual type. This allows the generic method to be used in a
more general way. The compiler takes care of the type of safety which enables
programmers to code easily since they do not have to perform long, individual type
castings.
Generic Classes: A generic class is implemented exactly like a non-generic class. The only
difference is that it contains a type parameter section. There can be more than one type of
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 103 of 215
Object Oriented Concepts using Java
parameter, separated by a comma. The classes, which accept one or more parameters, are
known as parameterized classes or parameterized types.
Casting of Objects
Typecasting is the assessment of the value of one primitive data type to another type.
In java, there are two types of casting namely upcasting and downcasting as follows:
2. Downcasting refers to the procedure when subclass type refers to the object of the
parent class is known as downcasting. If it is performed directly compiler gives an
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 104 of 215
Object Oriented Concepts using Java
error as ClassCastException is thrown at runtime. It is only achievable with the use
of instanceof operator the object which is already upcast, that object only can be
performed downcast.
In order to perform class type casting we have to follow these two rules as follows:
1. Classes must be “IS-A-Relationship “
2. An object must have the property of a class in which it is going to cast.
Instance of operator
The instanceof operator checks whether an object is an instanceof a particular class.
The instanceof in java is also known as type comparison operator because it compares the
instance with type. It returns either true or false. If we apply the instanceof operator with
any variable that has null value, it returns false.
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 105 of 215
Object Oriented Concepts using Java
Properties of Abstract Class
• A class with one or more abstract methods is automatically abstract and it cannot be
instantiated.
• A class declared abstract, even with no abstract methods cannot be instantiated.
• A subclass of an abstract class can be instantiated if it overrides all abstract methods
by implementing them.
• A subclass that does not implement all of the superclass abstract methods is itself
abstract; and it cannot be instantiated.
• We cannot declare abstract constructors or abstract static methods.
Syntax:
abstract class ClassName
{
...
…
abstract DataType MethodName1();
…
…
DataType Method2()
{
// method body
}
}
EXAMPLE:
abstract class Bike
{
abstract void run();
}
class Honda4 extends Bike
{
void run()
{
System.out.println("running safely..");
}
public static void main(String args[])
{
Bike obj = new Honda4();
obj.run();
}
}
OUTPUT:
running safely..
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 106 of 215
Object Oriented Concepts using Java
In this example, Bike the abstract class that contains only one abstract method run. It
implementation is provided by the Honda class.
Interface
An interface in java is a blueprint of a class. It has static constants and abstract
methods.
The interface in java is a mechanism to achieve abstraction.
There can be only abstract methods in the java interface not method body.
It is used to achieve abstraction and multiple inheritance in Java.
It cannot be instantiated just like abstract class.
A class implements an interface, thereby inheriting the abstract methods of the
interface.
An interface is written in a file with a .java extension, with the name of the
interface matching the name of the file.
The byte code of an interface appears in a .class file.
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 107 of 215
Object Oriented Concepts using Java
<<Interface>>
Speaker
speak()
Declaring Interface:
The interface keyword is used to declare an interface. Here is a simple
example to
declare an interface −
Syntax:
public interface NameOfInterface
{
// Any number of final, static fields
// Any number of abstract method declarations
}
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 108 of 215
Object Oriented Concepts using Java
Example:
Interface ItemConstants //interface declared
{
int code = 1001; // Variable
declared in interface string name = “Fan”;
void display(); // Method declared in interface
}
Variable Declaration:
Method Declaration:
Implementing Interface:
Interfaces are used as “Super classes” whose properties are inherited by classes.
Example:
interface Drawable // Interface declared
{
void draw();
}
class Rectangle implements Drawable //class implements interface
{
public void draw()
{
System.out.println("drawing rectangle");
}}
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 109 of 215
Object Oriented Concepts using Java
Example:
interface Printable // Interface 1 declared
{
void print();
}
interface Showable // Interface 2 declared
{
void show();
}
class A7 implements Printable,Showable // implementing interface
{
public void print()
{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");
}
public static void main(String args[])
{
A7 obj = new A7(); // object declaration
obj.print();
obj.show();
}
}
OUTPUT:
Hello
Welcome
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 110 of 215
Object Oriented Concepts using Java
Extending Interface:
An interface can extend another interface in the same way that a class can extend
another class.
The extends keyword is used to extend an interface, and the child interface
inherits the methods of the parent interface.
As shown in the figure given below, a class extends another class, an interface
extends another interface but a class implements an interface.
Syntax:
Example:
Interface ItemConstants
{
int code =
1001; string
name = “Fan”;
}
Interface Item extends ItemConstants
{
void display();
}
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 111 of 215
Object Oriented Concepts using Java
Final Keyword:
The final keyword in java is used to restrict the user.
We can prevent an inheritance of classes by other classes by declaring them as final
classes.
Any attempt to inherit these classes will cause an error.
The java final keyword can be used in many
context. Final can be:
1. Variable/field
2. Method
3. class
Example:
In the below example there is a final variable speedlimit, we are going to change the
value of this variable, but It can't be changed because final variable once assigned a value
can never be changed.
class Bike9
{
final int speedlimit=90;//final variable
void run()
{
speedlimit=400;
}
public static void main(String args[])
{
Bike9 obj=new Bike9();
obj.run();
}
}//end of class
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 112 of 215
Object Oriented Concepts using Java
Final method:
If the java Method made as final, then it won’t be overridden.
Final class:
We can prevent an inheritance of classes by other classes by declaring them as final
classes.
If the class has final, then the properties of that class couldn’t inherits.
Any attempt to inherit these classes will cause an error.
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 113 of 215
Object Oriented Concepts using Java
honda.run();
}
}
JAVA PACKAGES:
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two types,
1. Java API package (Built-in package)
2. User-defined package. (Defined by user)
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util,
sql etc.
Here, we will have the detailed learning of creating and using user-defined
packages.
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 114 of 215
Object Oriented Concepts using Java
PACKAGE CONTENTS
NAME
The above statement imports class color and therefore the class name can now be
directly used in the program.
The below statement imports every class contained in the specified package.
import java.awt.*;
The above statement will bring all classes of java.awt package.
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 115 of 215
Object Oriented Concepts using Java
Syntax:
package <package_name>
// Class definition
public class <classname1>
{
// Body of the class.
}
Example:
package land.vehicle;
public class Car
{
String brand;
String color;
int wheels;
}
import land.vehicle.Car;
public class MarutiCar extends Car
{
// Body of the class.
}
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 116 of 215
Object Oriented Concepts using Java
//Example program to implement user defined packages
package student.fulltime.BCA;//creating new package
import java.util.Scanner;
public class Studentpkg
{
public String name,sex;
public int age;
public void accept()
{
System.out.print("Enter the name ");
Scanner scan=new Scanner(System.in);
name=scan.nextLine();
System.out.print("Enter the sex ");
sex=scan.nextLine();
System.out.print("Enter the age ");
Scanner scan1=new Scanner(System.in);
age=scan1.nextInt();
}
public void display()
{
System.out.println("\nStudent Information\n") ;
System.out.println("Name:"+name+"\n"+"Sex"+sex+"\n"+"Age"+age+"\n");
}
}
Compile the above program and save in the directory.
Studentp.java
package student.fulltime.BCA;
import student.fulltime.BCA.Studentpkg;
public class Studentp
{
public static void main(String[] args)
{
Studentpkg s1=new Studentpkg();
s1.accept();
s1.display();
}
}
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 117 of 215
Object Oriented Concepts using Java
One mark questions
1. What is inheritance?
2. Why do we need inheritance?
3. Which keyword is used to do inheritance?
4. Define base class and derived class.
5. Write syntax for inheritance
6. Write types of inheritance available in java.
7. What is single inheritance? Give example
8. What is Multi-level inheritance? Give example
9. What is hierarchical inheritance? Give example
10. Can we inherit from more than base class in java?
11. What is interface?
12. Can we implement multiple inheritance in java? Justify
13. Write any two advantages of inheritance.
14. What do you mean by ambiguity situation?
15. What is polymorphism? Give example
16. What is method overriding? Give example
17. Define dynamic binding.
18. What is generic programming?
19. Write types of java generics
20. What is casting of objects?
21. What is upcasting and downcasting?
22. Write use of instance of operator.
23. What is abstract class?
24. Write syntax to declare abstract class?
25. What is abstract methods?
26. What is the use of abstract methods?
27. Which keyword is used to define interface?
28. What is the use of final keyword?
29. What is final class?
30. What is package?
31. Write any 2 built in package available in java.
32. Mention types of packages?
33. Write syntax for creating user defined packages.
34. Write syntax for importing packages in java
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 118 of 215
Object Oriented Concepts using Java
Five mark questions
1. What is inheritance? Explain single inheritance with example
2. Write advantages of inheritance.
3. Write a short note on inheritance.
4. Differentiate between method overriding and method overloading
5. Write Difference between inheritance and interface
6. With syntax and example explain interface.
7. Write a short note on java generics.
8. Explain any 2 built in packages of java?
9. Explain final field and final method?
10. Write properties of abstract class?
11. Write the features of method overriding.
12. Write advantages of packages.
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 119 of 215
Object Oriented Concepts using Java
Unit – 4
Event and GUI Programming
Event:
A GUI application program contains several graphical components the user controls
the application by interacting with the graphical components doing things such as:
Clicking on a button to choose a program option.
Making a choice from a menu.
Entering text in a text field.
Dragging a scroll bar.
An action such as clicking on a button is called as event.
Event Handling:
When you perform an action on a graphical component you generate an event. In
event-driven programming the program responds to these events. The order of events
is determined by the user, not the program.
This is different from programs where user interaction is done through the console.
In these programs, prompts or written to the console, and the user responds to the
prompts. The order of the Proms is determined by the program.
An event can be defined as changing the state of an object or behavior by performing
actions. Actions can be a button click, cursor movement, keypress through keyboard
or page scrolling, etc.
Responding on Events:
A user interacts with a GUI application by causing events. Each time the user interacts
with a component, an event is sent to the application.
Different events are sent to different parts of the application and application usually
ignores events that are not relevant to its purpose.
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 120 of 215
Object Oriented Concepts using Java
Event types: where Type represents the type of event.
Example 1: For KeyEvent we use addKeyListener() to register.
Example 2: that For ActionEvent we use addActionListener() to register.
Note: As Interfaces contains abstract methods which need to implemented by the registered class
to handle events. Abstract methods which need to implemented by the registered class to handle
events.
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 121 of 215
Object Oriented Concepts using Java
Different interfaces consists of different methods which are specified below.
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 122 of 215
Object Oriented Concepts using Java
Mouse and Keyboard events:
The mouse and keyboard input is handled in basically the same way as other
listeners. We select the component that we want to handle a listener and implement the
mouse or keyboard interfaces. When a mouse or keyboard event occurs, the appropriate
method is invoked in the interface.
Mouse Listeners:
To catch mouse events we import java.awt.event.MouseListener and the class we
want to handle events should implement the MouseListener interface. This interfaces
requires that we define the following methods:
mouseClicked
mouseEntered
mousePressed
mouseReleased
mouseExited
Keyboard Listeners:
It is a similar drill for keyboard listeners. We just have to learn what interface to
implement and what methods need to be defined.
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 123 of 215
Object Oriented Concepts using Java
GUI Basics:
GUI Programming:
Graphical User Interface (GUI) programming.
User interact with modern application programs using graphical components such
as:
windows,
buttons,
textboxes menus and other several components.
Graphical user interface GUI is implemented by using the classes from the standard
javax.swing and java.awt packages.
There are 2 set of GUI components in Java:
Components from abstract windowing toolkit.
Components from swing.
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 124 of 215
Object Oriented Concepts using Java
CheckBox
Choice
List etc.
Component:
Component is an abstract class that contains various classes such as Button,
Label,Checkbox,TextField, Menu and etc.
Container:
The Container is a component in AWT that can contain another components like
buttons, textfields, labels etc. The Container class extends Frame and Panel.
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 125 of 215
Object Oriented Concepts using Java
Panels:
Panel is the simplest container class. A panel provides space in which an application
can attach any other component, including other panels. The default layout manager
for a panel is the FlowLayout layout manager.
The Panel is the container that doesn't contain title bar and menu bars. It can have
other
components like button, textfield etc
Frames:
The Frame is the container that contain title bar and can have menu bars. It can have
other
components like button, textfield etc.
In java Frames == Windows
What you usually call a “window” Java calls a “frame”.
Like all software objects, a frame object holds information and methods.
GUI application programs are usually organized one or more frames.
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 126 of 215
Object Oriented Concepts using Java
The setBounds(int xaxis, int yaxis, int width, int height) method is used in the above
example that sets the position of the awt button.
Output:
Layout Manager
The LayoutManagers are used to arrange components in a particular manner.
LayoutManager is an interface that is implemented by all the classes of layout managers.
BorderLayout:
The BorderLayout is used to arrange the components in five regions: north, south,
east, west and center. Each region (area) may contain one component only. It is the default
layout of frame or window. The BorderLayout provides five constants for each region:
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 127 of 215
Object Oriented Concepts using Java
Constructors of BorderLayout class:
BorderLayout(): creates a border layout but with no gaps between the components.
JBorderLayout(int hgap, int vgap): creates a border layout with the given horizontal
and vertical gaps between the components.
import java.awt.*;
import javax.swing.*;
public class Border
{
JFrame f;
Border()
{
f=new JFrame();
JButton b1=new JButton("NORTH");;
JButton b2=new JButton("SOUTH");;
JButton b3=new JButton("EAST");;
JButton b4=new JButton("WEST");;
JButton b5=new JButton("CENTER");;
f.add(b1,BorderLayout.NORTH);
f.add(b2,BorderLayout.SOUTH);
f.add(b3,BorderLayout.EAST);
f.add(b4,BorderLayout.WEST);
f.add(b5,BorderLayout.CENTER);
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args)
{ new Border(); }
}
GridLayout:
The GridLayout is used to arrange the components in rectangular grid. One
component is displayed in each rectangle.
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 128 of 215
Object Oriented Concepts using Java
Constructors of GridLayout class:
1. GridLayout(): creates a grid layout with one column per component in a row.
2. GridLayout(int rows, int columns): creates a grid layout with the given rows and
columns but no gaps between the components.
3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with
the given rows and columns alongwith given horizontal and vertical gaps.
import java.awt.*;
import javax.swing.*;
public class MyGridLayout
{
JFrame f;
MyGridLayout()
{
f=new JFrame();
JButton b1=new JButton("1");
JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4");
JButton b5=new JButton("5");
JButton b6=new JButton("6");
JButton b7=new JButton("7");
JButton b8=new JButton("8");
JButton b9=new JButton("9");
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
f.add(b6);f.add(b7);f.add(b8);f.add(b9);
f.setLayout(new GridLayout(3,3));
//setting grid layout of 3 rows and 3 columns
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args)
{ new MyGridLayout(); }
}
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 129 of 215
Object Oriented Concepts using Java
FlowLayout
The FlowLayout is used to arrange the components in a line, one after another (in a
flow). It is the default layout of applet or panel.
FlowLayout(int align): creates a flow layout with the given alignment and a default 5 unit
horizontal and vertical gap.
FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given alignment
and the given horizontal and vertical gap.
import java.awt.*;
import javax.swing.*;
public class MyFlowLayout
{
JFrame f;
MyFlowLayout()
{
f=new JFrame();
JButton b1=new JButton("1");
JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4");
JButton b5=new JButton("5");
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 130 of 215
Object Oriented Concepts using Java
f.setLayout(new FlowLayout(FlowLayout.RIGHT));
//setting flow layout of right alignment
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args)
{ new MyFlowLayout(); }
}
BoxLayout class:
The BoxLayout is used to arrange the components either vertically or horizontally.
For this purpose, BoxLayout provides four constants.
They are as follows:
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 131 of 215
Object Oriented Concepts using Java
import java.awt.*;
import javax.swing.*;
public BoxLayoutExample1 ()
{
buttons = new Button [5];
for (int i = 0;i<5;i++)
{
buttons[i] = new Button ("Button " + (i + 1));
add (buttons[i]);
}
setLayout (new BoxLayout (this, BoxLayout.Y_AXIS));
setSize(400,400);
setVisible(true);
}
import java.awt.*;
import javax.swing.*;
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 132 of 215
Object Oriented Concepts using Java
buttons = new Button [5];
for (int i = 0;i<5;i++)
{
buttons[i] = new Button ("Button " + (i + 1));
add (buttons[i]);
}
CardLayout class
The CardLayout class manages the components in such a manner that only one
component
is visible at a time. It treats each component as a card that is why it is known as CardLayout.
Constructors of CardLayout class:
1. CardLayout(): creates a card layout with zero horizontal and vertical gap.
2. CardLayout(int hgap, int vgap): creates a card layout with the given horizontal and
vertical gap.
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 133 of 215
Object Oriented Concepts using Java
Example of CardLayout class:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 134 of 215
Object Oriented Concepts using Java
GUI Components:
1. Button
The button class is used to create a labeled button that has platform independent
implementation. The application result in some action when the button is pushed.
java.awt.Button class is used to create a labelled button. GUI component that
triggers a certain programmed action upon clicking it.
Syntax:
Button b=new Button(“Text");
(Or) Button b1,b2; b1=new Button(“Text”);
b.setBounds(50,100,80,30);
setBounds(int x,int y,int width,int height)
This method is used to declare location, width & height of all components of AWT.
X Y Example: setBounds(50,100,80,30); width Height
2. Check Box: The Checkbox class is used to create a checkbox. It is used to turn an
option on (true) or off (false). Clicking on a Checkbox changes its state from "on" to
"off" or from "off" to "on".
Syntax:
Checkbox c1=new Checkbox(“Text”);
(or) Checkbox c1,c2; c1=new Checkbox(“Text”);
Example:
3. RadioButtons:
The JRadioButton class is used to create a radio button. It is used to choose one
option from multiple options. It is widely used in exam systems or quiz.
It should be added in ButtonGroup to select one radio button only.
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 135 of 215
Object Oriented Concepts using Java
Syntax:
Choice c=new Choice();
c.add("Item 1");
c.add("Item 2");
c.add("Item 3");
Example:
4. Labels: The Label class is a component for placing text in a container. It is used to display
a single line of read only text. The text can be changed by an application but a user cannot
edit it directly. A Label object is a component for placing text in a container. A label
displays a single line of read-only text. The text can be changed by the application, but a
user cannot edit it directly. The java.awt.Label class provides a descriptive text string
that is visible on GUI. An AWT Label object is a component for placing text in a container.
Syntax:
Label l1=new Label(“First Label”);
(or) Label l1,l2; l1=new Label(“Text”);
Example:
5. Text Fields: The object of a TextField class is a text component that allows a user to enter
a single line text and edit it. It inherits TextComponent class, which further inherits
Component class. A java.awt. TextField class creates a single-line text box for users to
enter texts.
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 136 of 215
Object Oriented Concepts using Java
Syntax:
TextField t1=new TextField(“Text”);
(or) TextField t1,t2; t1=new TextField(“Text”);
Example:
6. Text Areas: The object of a TextArea class is a multiline region that displays text. It allows
the editing of multiple line text. It inherits TextComponent class.
Syntax:
TextArea t1=new TextArea(“Text”);
(or) TextArea t1,t2; t1=new TextArea(“Text”);
Example:
7. Combo Boxes: A combo box is a combination of a text field and a drop-down list from
which the user can choose a value.
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 137 of 215
Object Oriented Concepts using Java
Example:
8. Lists: List is a component that displays a set of Objects and allows the user to select one
or more items.
Syntax:
List ls=new List(Size);
ls.add("Item 1");
ls.add("Item 2");
ls.add("Item 3");
Example:
9. Scroll Bars: The object of Scrollbar class is used to add horizontal and vertical scrollbar.
Scrollbar is a GUI component allows us to see invisible number of rows and columns.
Example:
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 138 of 215
Object Oriented Concepts using Java
10. Sliders: The Java JSlider class is used to create the slider. By using JSlider, a user can
select a value from a specific range.
Example:
11. Window: A Window object is a top-level window with no borders and no menubar. The
default layout for a window is BorderLayout . A window must have either a frame, dialog,
or another window defined as its owner when it's constructed.
Example:
12. Menus: The object of MenuItem class adds a simple labeled menu item on menu. The
items used in a menu must belong to the MenuItem or any of its subclass. The object of
Menu class is a pull down menu component which is displayed on the menu bar. It
inherits the MenuItem class.
Example:
13. Dialog Box: Dialog boxes are graphical components that are usually used to display
errors or give some other information to the user.
Example:
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 139 of 215
Object Oriented Concepts using Java
Applet:
Applet is a special type of program that is embedded in the webpage to generate the
dynamic content. It runs inside the browser and works at client side. Applet is a special
type of Java program that is used in web applications.
Applets are embedded within a HyperText Markup Language (HTML) document.
Applets provide a way to give life to a web page.
Applets can be used to handle client-side validations.
Browsers are required for their execution.
Applets allow event-driven programming.
Types of Applets:
Web pages can contain two types of applets which are named after the
location at which they are stored.
1. Local Applet
2. Remote Applet APPLET
LOCAL REMOTE
Local Applets:
A local applet is the one that is stored on our own computer system.
When the Web-page has to find a local applet, it doesn't need to retrieve
information from the Internet.
A local applet is specified by a path name and a file name as shown below in which the
codebase attribute specifies a path name, whereas the code attribute specifies the name of
the byte-code file that contains the applet's code.
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 140 of 215
Object Oriented Concepts using Java
Remote Applets:
A remote applet is the one that is located on a remote computer system.
This computer system may be located in the building next door or it may
be on the other side of the world.
No matter where the remote applet is located, it's downloaded onto
our computer via the Internet.
The browser must be connected to the Internet at the time it needs
to display the remote applet.
To reference a remote applet in Web page, we must know the applet's URL (where it's
located on the Web) and any attributes and parameters that we need to supply.
Advantage of Applet
There are many advantages of applet. They are as follows:
It works at client side so less response time.
Secured
It can be executed by browsers running under many platforms, including Linux, Windows,
Mac OS etc.
Drawback of Applet
Plugin is required at client browser to execute applet.
Hierarchy of Applet
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 141 of 215
Object Oriented Concepts using Java
As displayed in the above diagram, Applet class extends Panel. Panel class extends
Container, which is the subclass of Component.
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 142 of 215
Object Oriented Concepts using Java
Syntax:
Running State:
After initialization, this state will automatically occur by invoking the start
method of applet.
The running state can be achieved from idle state when the applet is reloaded.
This method may be called multiple times when the Applet needs to be started
or restarted.
If the user leaves the applet and returns back, the applet may restart its running.
We can override this method.
Syntax:
public void start()
{
Statements
}
Idle State:
The idle state will make the execution of the applet to be halted temporarily.
Applet moves to this state when the currently executed applet is
minimized or when the user switches over to another page. At this point
the stop method is invoked.
From the idle state the applet can move to the running state.
The stop() method can be called multiple times in the life cycle of applet.
We can override this method.
Syntax:
Dead State:
When the applet programs terminate, the destroy function is invoked
which brings anapplet to its dead state.
The destroy() method is called only one time in the life cycle of Applet like init()
method.
In this state, the applet is removed from memory.
We can override this to cleanup resources.
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 143 of 215
Object Oriented Concepts using Java
Syntax:
public void destroy()
{
Statements
}
Display State:
The applet is said to be in display state when the paint or update method is called.
This method can be used when we want to display output in the screen.
This method can be called any number of times.
Overriding paint() method is a must when we want to draw something
on the applet window.
paint() method takes Graphics object as argument
paint() method is automatically called each time the applet window is
redrawn i.e. when it is maximized from minimized state or resized or
when other windows uncover overlapped portions.
It can also be invoked by calling “repaint()” method.
Syntax:
public void paint(Graphics g)
{
Statements
}
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 144 of 215
Object Oriented Concepts using Java
Step 2: Extend the Applet class:
Then, a class must be defined that inherits from the class ‘Applet’.
It contains the methods to paint the screen.
The inherited class must be declared public.
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet
{
public void paint(Graphics g)
{
g.drawString("Name : Vindhya Rani",150,150);
g.drawString("Age : 20",200,200);
g.drawString("Course : BCA",250,250);
g.drawString("Percentage : 85",300,300);
}
}
/*
<applet code="First.class" width="300" height="300">
</applet>
*/
********************OUTPUT********************
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 145 of 215
Object Oriented Concepts using Java
Step 4: Compiling the Program:
After writing the program, we compile it using the command "javac
MyApplet.java".
This command will compile our code so that we now have MyApplet.class file.
Step 5: Adding applet to HTML document:
To run the applet we need to create the HTML document.
The BODY section of the HTML document allows APPLET tag.
The HTML file looks something like this:
<HTML>
<BODY>
<APPLET codebase="MyAppPath" code="MyApp.class" width=200
height=200>
</APPLET>
</BODY>
</HTML>
Step 6: Running an applet:
The applet can be run in two ways
1. Using appletviewer: To run the appletviewer, type appletviewer filename.html
2. Using web browser: Open the web browser, type in the full address of html file
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 146 of 215
Object Oriented Concepts using Java
height), coordinates of the top left corner, the bottom
right corner will be at (x+width,y+height)
fillRect (int x, int y, int width, int
height)
drawOval (int x, int y, int width,
int height), fillOval (intx, int y, int
Draws (fills) an oval bounded by the
width, int height) rectangle specified by these parameters.
Draws (fills) a rectangle with shaded sides
draw3DRect(), fill3DRect()
that provide a 3-D appearance.
drawRoundRect(), fillRoundRect() Draws (fills) a rectangle with rounded corners.
An arc is formed by drawing an oval
drawArc() between a start angle and a finish angle.
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 147 of 215
Object Oriented Concepts using Java
********************OUTPUT********************
Introduction to Swing
Swing:
It is used to create window-based applications. It is built on the top of AWT (Abstract
Windowing Toolkit) API and entirely written in java.
Unlike AWT, Java Swing provides platform-independent and lightweight
components.
The javax.swing package provides classes for java swing API such as JButton,
JTextField, JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 148 of 215
Object Oriented Concepts using Java
One mark questions
1. What event?
2. Expand GUI & API
3. What is event handling?
4. Mention types of events in java.
5. Which packages are required for GUI programming in java?
6. Write any two mouse events.
7. Write any two keyboard events.
8. What is frame
9. Define window
10. Expand AWT
11. Difference between textfield and textarea
12. Define list
13. What is label? Write syntax to create label in a frame
14. What is container?
15. What is layout manager? Mention types of layout manager
16. What is swing?
17. what is button?
18. What is menu? When we use it
19. What is applet?
20. Mention types of applets.
21. Write advantages of applets.
22. What is the use of init() and paint() method in applets
23. Which class is required to import to draw different shapes in applet.
24. What is the use of drawString() method?
25. Mention 2 methods of executing applet programs in java.
26. Write any 2 graphical methods of applet.
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 149 of 215
Object Oriented Concepts using Java
Five mark questions
1. What is event? Explain different types of event in java?
2. Write difference between AWT & Swings
3. Write advantages of packages in java?
4. Why do we need GUI programming? Justify
5. Explain any 2 different layout manager?
6. Explain any two GUI components in java
7. Write a short note on AWT package
8. Mention methods of creating frame in java?
9. Explain different types of applets in java?
10. Write a short note on swings
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 150 of 215
Object Oriented Concepts using Java
UNIT - 6
MULTITHREADING IN JAVA
Multithreaded Programming
In modern operating systems such as Windows XP we can execute several programs
simultaneously
This ability is known as multitasking
In system’s terminology it is called multithreading
A thread is a part of any task
When there are many parts are available of a work then it will called as multithreads
In multithreading a task is divided in to different parts
Each part is working in parallel with others & their own work
A thread has a single flow of control
Thread has a beginning, a body, and an end
Every program in java will have at least one thread
Java also supports the multithreading concept
Java enables us to use multiple flows of control in developing programs
Each flow of control may thought of as a separate tiny program known as thread that
runs parallel to others
A program that contains multiple flows of control is known as multithreaded
program
Threads in java are subprograms of a main application program & share the same
memory space
These are known as “lightweight threads”
All threads are running on a single processor, the flow of execution is shared between
the threads
Creating Threads
Creating the threads in java is simple
Threads are implemented in the form of objects that contain a method called run()
The run() method is the heart & soul of any thread
By using this method thread’s behaviour can be implemented & it’s make entire body
of a thread
The run() would appear as follows:
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 151 of 215
Object Oriented Concepts using Java
public void run( )
{
………………..
……………….. (statements for implementing thread)
………………..
}
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 152 of 215
Object Oriented Concepts using Java
3. Starting New Thread
To create & run an instance of our thread class, we must write the following code:
MyThread aThread = new MyThread
aThread.start( );
The first line instantiates a new object of class MyThread
The second line calls the start() method causing the thread to move into the runnable
state
Then, the java runtime will schedule the thread to run by invoking its run() method
Here the thread is said to be in the running state
Before coming to running state the thread will always in runnable state
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 153 of 215
Object Oriented Concepts using Java
//Program to implement creating threads using runnable interface
class Multi3 implements Runnable // Implementing Runnable interface
{
public void run()
{
System.out.println("thread is running...");
}
public static void main(String args[])
{
Multi3 m1=new Multi3(); // object initiated for class
Thread t1 =new Thread(m1); // object initiated for thread
t1.start();
}
}
Blocking a Thread
A thread can also be temporarily suspended from entering in to the runnable by
using the either of the following methods:
sleep( )
suspend( )
wait( )
These methods cause the thread to go into the blocked state
The thread will return to runnable state by using any one of the following methods:
When the specified time is elapsed
resume( )
notify( )
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 154 of 215
Object Oriented Concepts using Java
Life Cycle of a Thread
A thread is also having its own life cycle
During this, a thread can enter in many states to complete its life cycle
They include:
1. Newborn state
2. Runnable state
3. Running state
4. Blocked state
5. Dead state
Newborn State
A thread is said in to newborn state when it was just created
The thread is not yet scheduled for running
At this state we can do only one of the following
Scheduled it for running using start( ) method
Kill it using stop( ) method
If scheduled, it moves to the runnable state if we attempt to use any other method at this
stage, an exception will be thrown.
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 155 of 215
Object Oriented Concepts using Java
Runnable State
The runnable state means that the thread is ready for execution and is waiting for the
availability of the processor.
In runnable state the thread is able to run
But till it doesn't start the execution
This state shows the status of the thread for execution
Running State
When the thread starts the execution by using the processor this state is called
running state
After runnable always running state will be there
A thread runs until it over its execution or any other thread has to ask for processor
When the thread is in its running state, we can ensure that the control is in run()
method of the thread.
Blocked State
A thread is said to be blocked when it is prevented from entering in to the runnable
state
This happens when the thread is suspended, sleeping or waiting for certain period
of time
A blocked thread is considered “not runnable” but not dead & therefore fully
qualified to run again
This state is achieved when we invoke suspend() or sleep() or wait() methods.
This state may appears more than one times in the life cycle of a thread
Dead State
A thread is said to be in dead state when it ends its execution
Every thread has a life cycle
A running thread ends its life when it has completed executing its run( ) method
Every born thread has to be a dead state at last
However, we can kill it by sending the stop message to it at any state thus causing a
premature death to it.
A thread can be killed as soon it is born, or while it is running, or even when it is in
"not runnable" (blocked) condition.
This state is achieved when we invoke stop() method or the thread completes it
execution.
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 156 of 215
Object Oriented Concepts using Java
Thread Methods:
Thread is a class found in java.lang package.
It provides several different methods to perform thread tasks and control thread behaviors.
The methods of Thread class with their meanings are listed below:
Thread Priority
In Java, each thread is assigned a priority
The priority affects the order in which it is scheduled for running
The java scheduler will going to assign the priority to the threads if all are at same
level
A user also assign the different priorities for threads
Java permits us to set the priority of a thread using setPriority() method as follows:
ThreadName.setPriority(intNumber);
The intNumber is an integer value to which the thread priority is set
The thread class defines several priority constants:
MIN_PRIORITY = 1
NORM_PRIORITY = 5
MAX_PRIORITY = 10
The intNumber may assume one of these constants
The default setting is NORM_PRIORITY
By assigning priority to threads, we can ensure that they are given the attention they
deserve
Priority can be set to a thread according to its post of the work
Thread Synchronization
Generally threads use their own data and methods provided inside their run()
methods.
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 157 of 215
Object Oriented Concepts using Java
But if we wish to use data and methods outside the thread’s run()
method, they may compete for the same resources and may lead to
serious problems.
For example, one thread may try to read a record from a file while
another is still writing to the same file.
Depending on the situation, we may get strange results.
Java enables us to overcome this problem using a technique known as
synchronization.
For example, the method that will read information from a file and the
method that will update the same file may be declared as synchronized as shown
below:
synchronized void update( )
{
………….. // code here is synchronized
}
When the method declared as synchronized, Java creates a "monitor" and
hands it over to the thread that calls the method first time.
As long as the thread holds the monitor, no other thread can enter the
synchronized section of code i.e. other threads cannot interrupt this thread with
that object until its complete execution. It is like locking a function.
synchronized (lock-object)
{
.......... // code here is synchronized
}
DEADLOCK:
Deadlock describes a situation where two or more threads are blocked
forever, waiting for each other.
This undesirable situation may occur when two or more threads are
waiting to gain control on a resource.
Due to some reasons, the condition on which the waiting threads rely on
to gain control does not happen. This results in a situation called as
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 158 of 215
Object Oriented Concepts using Java
deadlock.
But, java automatically recognizes this situation and terminates some
processes automatically to ensure safer execution.
For example, assume that the thread A must access Method1 before it can
release Method2, but the thread B cannot release Method1 until it gets holds of
Method2.
Exception Handling
Errors and Various Types of Errors:
Errors are the wrongs that can make a program go wrong.
In computer terminology, errors may be referred to as bugs.
It is common to make mistakes while developing as well as typing a program.
A mistake might lead to an error causing to program to produce unexpected
results.
An error may produce an incorrect output or may terminate the
execution of the program abruptly or even may cause the system to crash.
It is therefore important to detect and manage properly all the possible errors.
Types of Errors:
Errors may broadly be classified into two categories:
1. Compile-time errors
2. Run-time errors
Compile-time errors:
All syntax errors will be detected and displayed by the Java compiler and
therefore these errors are known as compile-time errors.
Whenever the compiler displays an error, it will not create the .class file.
It is necessary to fix these errors to get it compiled.
It becomes an easy job to a programmer to correct these errors because Java
compiler tells us where the errors are.
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 159 of 215
Object Oriented Concepts using Java
Most of the compile-time errors are due to typing mistakes.
Typographical errors are hard to find.
We may have to check the code word by word, or even
character by character.
The most common errors are:
Missing semicolons
Missing (or mismatch of) brackets in classes and methods
Misspelling of identifiers and keywords
Missing double quotes in strings
Use of undeclared variables Incompatible types in assignments / initialization
Bad references to objects
Use of = in place of = = operator
RUN-TIME ERRORS:
Sometimes, a program may compile successfully creating the .class file but
may not run properly these errors are known as Run time error.
Such programs may produce wrong results due to wrong logic or may
terminate due to errors such as stack overflow.
Most common run-time errors are:
Dividing an integer by zero
Accessing an element that is out of the bounds of an array
Trying to store a value into an array of an incompatible class or type
Trying to cast an instance of a class to one of its subclasses
Passing a parameter that is not in a valid range or value for a method
Trying to illegally change the state of a thread
Attempting to use a negative size for an array
Using a null object reference to access a method or a variable.
Converting invalid string to a number
Accessing a character that is out of bounds of a string
Example: The following code generates division-by-zero runtime error.
int x=5, y=0;
System.out.println(x/y);
It displays the following message and stops without executing further statements.
Java.lang.ArithmeticException: / by zero
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 160 of 215
Object Oriented Concepts using Java
For example:
If a user enters a string where an integer is expected, an error occurs
at runtime that causes the program to be stopped intermediately.
Java has a built-in mechanism for handling runtime errors, referred
to as exception handling.
This is to ensure that we can write robust (error-free) programs.
Exception Handling:
Handling runtime errors is exception handling.
In java, when an abnormal condition occurs within a method then the exceptions are thrown
in form of Exception Object
The normal program control flow is stopped and an exception object is
created to handle that exceptional condition.
If the exception object is not caught and handled properly, the interpreter
will display an error message and it will terminate the program.
If we want the program to continue with the execution of the remaining
code, then we should try to catch the exception.
The error handling code basically consists of two segments, one to detect
errors and to throw exceptions and the other to catch exceptions and to take
appropriate actions.
Exception handling mechanism includes the key words: try,
catch, throw, throws and finally.
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 161 of 215
Object Oriented Concepts using Java
The program becomes robust and more user-friendly.
With this mechanism, the working code and the error-handling code can be
disintegrated. It allows different handling code-blocks for different types of errors.
Types of exception
There are mainly two types of exceptions: checked and unchecked where error
is considered as unchecked exception. The sun microsystem says there are three
types of exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error
Checked Exception
The classes that extend Throwable class except RuntimeException and Error
are known as checked exceptions e.g.IOException, SQLException etc. Checked
exceptions are checked at compile- time.
Unchecked Exception
The classes that extend RuntimeException are known as unchecked
exceptions. e.g. ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at
compile-time rather they are checked at runtime.
Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError
etc.
Java uses a keyword try to preface a block of code that is likely to cause an error
condition
A catch block defined by the keyword catch “catches” the exception “thrown” by the
try block an handles it appropriately
The catch block is added immediately after the try block
Ex - ………..
..............
try
{
statement; // generates an exception
}
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 162 of 215
Object Oriented Concepts using Java
catch (Exception - type e)
{
statement; // process the exception
}
Try - Block:
“try” block contains the code in which runtime error may occur.
It throws Exception object.
A try block must be followed by at least one catch block or a finally block.
But, it can be followed by multiple catch blocks.
A try block allows another try block within.
Catch - Block:
“catch” block contains the handling code for runtime errors i.e. when run
time error occurs, instead of terminating the program, control comes to
“catch” block.
Program control enters into “catch” block only when the corresponding runtime
error occurs.
After executing the handling code the control continues with the remaining part of
the program.
Multiple “catch” blocks can be written to handle different errors. In a “catch” block the
exception type must be mentioned.
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 163 of 215
Object Oriented Concepts using Java
StackOverFlowExceptlon Caused when the system runs out of stack space
Caused when a program attempts to access a
StringlndexOutOfBoundsExcep
nonexistent character position in a string
tlon
********************OUTPUT********************
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 164 of 215
Object Oriented Concepts using Java
Example:
The Following program uses Multiple catch blocks and code in a catch block
will be executed only when the corresponding errors occurs. Sample output is also
shown.
class Test
{
public static void main(String as[])
{
try
{
int x=Integer.parseInt(as[0]);
int y=Integer.parseInt(as[1]);
System.out.print("Division="+ (x/y));
}
catch(ArithmeticException ae)
{
System.out.println("Denominator was zero");
}
catch(NumberFormatException ne)
{
System.out.println("Please supply numbers");
}
catch(ArrayIndexOutOfBoundsException ie)
{
System.out.println("Please supply two arguments");
}
}
}
c:\jdk1.5\bin>java Test xx yy
Please supply numbers
c:\jdk1.5\bin>java Test 5
Please supply two arguments
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 165 of 215
Object Oriented Concepts using Java
Using finally statement:
The finally block is always executed, regardless of whether or not an exception is
thrown.
It is recommended for actions like closing file streams and releasing system
resources.
Writing the finally block for try-block is optional unless there is no catch-block.
If no exception occurs during the running of the try-block, all the catch-
blocks are skipped, and finally-block will be executed after the try-block.
The finally block may be added after the catch block, or after the last catch
block.
try
{
Statements that may generate the exception
}
finally
{
Statements to be executed before exiting exception handler
}
try
{
Statements that may generate the exception
}
catch(Exception-Type1 a)
{
Statements to process the exception ‘a’
}
…. // other catch blocks
….
finally
{
Statements to be executed before exiting exception
handler
}
Handles the exception and moves to finally block
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 166 of 215
Object Oriented Concepts using Java
/*Program to handle NullPointerException and use the “finally” method to display a
message to the user.*/
import java.io.*;
class Exceptionfinally
{
public static void main (String args[])
{
String ptr = null;
try
{
if (ptr.equals("gfg"))
System.out.println("Same");
else
System.out.println("Not Same");
}
catch(NullPointerException e)
{
System.out.println("Null Pointer Exception Caught");
}
finally
{
System.out.println("finally block is always executed");
}
}
}
********************OUTPUT********************
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 167 of 215
Object Oriented Concepts using Java
Difference between final, finally and finalize:
There are many differences between final, finally and finalize. A list of
differences between final, finally and finalize are given below:
Collections in Java
1. Java Collection Framework
2. Hierarchy of Collection Framework
3. Collection interface
4. Iterator interface
The Collection in Java is a framework that provides an architecture to store and manipulate
the group of objects.
Java Collections can achieve all the operations that you perform on a data such as searching,
sorting, insertion, manipulation, and deletion.
Java Collection means a single unit of objects. Java Collection framework provides many
interfaces (Set, List, Queue, Deque) and classes (ArrayList,
Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 168 of 215
Object Oriented Concepts using Java
Hierarchy of Collection Framework
Let us see the hierarchy of Collection framework. The java.util package contains all
the classes and interfaces for the Collection framework.
Iterator interface
Iterator interface provides the facility of iterating the elements in a forward direction only.
1 public boolean It returns true if the iterator has more elements otherwise
hasNext() it returns false.
2 public Object next() It returns the element and moves the cursor pointer to the
next element.
3 public void remove() It removes the last elements returned by the iterator. It is
less used.
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 169 of 215
Object Oriented Concepts using Java
Introduction Java Beans
Reusability is the main concept in any programming language. A JavaBean is a software
component that has been designed to be reusable in a variety of environments.
What is JavaBeans?
JavaBeans is a portable, platform-independent model written in Java Programming Language. Its
components are referred to as beans.
In simple terms, JavaBeans are classes which encapsulate several objects into a single object.
It helps in accessing these object from multiple places. JavaBeans contains several elements
like Constructors, Getter/Setter Methods and much more.
JavaBean Properties
A JavaBean property can be accessed by the user of the object. The feature can be of any Java
data type, containing the classes that you define. It may be of the following mode: read, write,
read-only, or write-only. JavaBean features are accessed through two methods:
1. getEmployeeName ()
For example, if the employee name is firstName, the method name would be getFirstName()
to read that employee name. This method is known as an accessor. Properties of getter
methods are as follows:
1. Must be public in nature
2. Return-type should not be void
3. The getter method should be prefixed with the word get
4. It should not take any argument
2.setEmployeeName ()
For example, if the employee name is firstName, the method name would be setFirstName()
to write that employee name. This method is known as a mutator. Properties of setter
methods:
1. Must be public in nature
2. Return-type should be void
3. The setter method has to be prefixed with the word set
4. It should take some argument
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 170 of 215
Object Oriented Concepts using Java
Example Program: Implementation of JavaBeans
The example program shown below demonstrates how to implement JavaBeans.
public class Employee implements java.io.Serializable
{
private int id;
private String name;
public Employee()
{
}
public void setId(int id)
{
this.id = id;
}
public int getId()
{
return id;
}
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
}
Next program is written in order to access the JavaBean class that we created above:
public class Employee1
{
public static void main(String args[])
{
Employee s = new Employee();
s.setName("Chandler");
System.out.println(s.getName());
}
}
Output:
Chandler
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 171 of 215
Object Oriented Concepts using Java
Advantages of JavaBeans
The following list enumerates some of the benefits of JavaBeans:
Portable
JavaBeans components are built purely in Java, hence are fully portable to any platform that
supports the Java Run-Time Environment. All platform specifics, as well as support for
JavaBeans, are implemented by the Java Virtual Machine.
Disadvantages of JavaBeans
1. JavaBeans are mutable, hence lack the advantages offered by immutable objects.
2. JavaBeans will be in inconsistent state partway through its construction.
Java Networking
Java Networking is a concept of connecting two or more computing devices together
so that we can share resources. Java socket programming provides facility to share data
between different computing devices.
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 172 of 215
Object Oriented Concepts using Java
1) IP Address
IP address is a unique number assigned to a node of a network e.g. 192.168.0.1. It is
composed of octets that range from 0 to 255. It is a logical address that can be changed.
2) Protocol
A protocol is a set of rules basically that is followed for communication. For example:
o TCP
o FTP
o Telnet
o SMTP
o POP etc.
3) Port Number
The port number is used to uniquely identify different applications. It acts as a
communication endpoint between applications.
The port number is associated with the IP address for communication between two
applications.
4) MAC Address
MAC (Media Access Control) address is a unique identifier of NIC (Network Interface
Controller). A network node can have multiple NIC but each with unique MAC address.
For example, an ethernet card may have a MAC address of 00:0d:83::b1:c0:8e.
6) Socket
A socket is an endpoint between two-way communications.
java.net package
The java.net package can be divided into two sections:
1. A Low-Level API: It deals with the abstractions of addresses i.e. networking
identifiers, Sockets i.e. bidirectional data communication mechanism and Interfaces
i.e. network interfaces.
2. A High Level API: It deals with the abstraction of URIs i.e. Universal Resource
Identifier, URLs i.e. Universal Resource Locator, and Connections i.e. connections to
the resource pointed by URLs.
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 173 of 215
Object Oriented Concepts using Java
One mark questions
1. What is thread?
2. What is multitasking?
3. How to achieve multitasking in java?
4. What are the advantages of multithreading
5. Which method is used to block the thread in java?
6. Write two methods to create thread in java?
7. When did thread gets running to runnable state?
8. Which methods are used to unblock the thread?
9. What is thread synchronization?
10. What is an exception?
11. How many types of errors are their name them?
12. Write few compile time errors.
13. Mention few run time errors.
14. Mention types of exceptions in java.
15. Write any two checked and unchecked exceptions in java
16. What do you mean by NullPointer Exception?
17. Why do we use finally method?
18. What is java bean?
19. What is java networking?
20. Which is the super class for all exceptions?
Compiled by Mr. Manjunath Balluli, Dept. of Computer Science Page 174 of 215