Java Object-Oriented Concepts Overview
Java Object-Oriented Concepts Overview
UNIT 1
INTRODUCTION TO JAVA
History of JAVA.
Java was initially developed in 1991 named as “oak” but was renamed “Java” in 1995.
Originally designed for small, embedded systems in electronic appliances like set-top
boxes.
The primary motivation was the need for a platform-independent language that could be
used to create software to be embedded in various consumer electronic devices.
Java programming language was originally developed by Sun Microsystems which was
initiated by James Gosling and released in 1995 as core component of Sun Microsystems'
Java platform (Java 1.0 [J2SE]).
Java 2, new versions had multiple configurations built for different types of platforms.
J2EE included technologies and APIs for enterprise applications typically run in server
environments, while J2ME featured APIs optimized for mobile applications.
The desktop version was renamed J2SE. In 2006, for marketing purposes, Sun renamed
new J2 versions as Java EE, Java ME, and Java SE, respectively.
On 13 November 2006, Sun released much of Java as free and open-source software
(FOSS), under the terms of the GNU General Public License (GPL).
On 8 May 2007, Sun finished the process, making all of Java's core code free and open-
source, aside from a small portion of code to which Sun did not hold the copyright
What is Java?
Java is a programming language that:
Is exclusively object oriented
Has full GUI support
Has full network support
Is platform independent
KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA
Robust
Robust simply means strong. Java is robust because:
It uses strong memory management.
There are lack of pointers that avoids security problem.
There is automatic garbage collection in java.
There is exception handling and type checking mechanism in java. All these points
makes java robust
Multithreaded
A thread is like a separate program, executing concurrently.
We can write Java programs that deal with many tasks at once by defining multiple
threads. o The main advantage of multi-threading is that it doesn't occupy memory for
each thread.
It shares a common memory area. Threads are important for multi-media, Web
applications etc…
Architecture-neutral
Java is architecture neutral because there is no implementation dependent features e.g.
size of primitive types is fixed.
Example : in c int occupy 2 byte for 32 bit OS and 4 bytes for 64 bit OS whereas in JAVA
it occupy 4 byte for int both in 32 bit and 64 bit OS.
Interpreted
Java enables the creation of cross-platform programs by compiling into an intermediate
representation called Java bytecode.
This code can be executed on any system that implements the Java Virtual Machine.
High-Performance
Most previous attempts at cross-platform solutions have done so at the expense of
performance.
As explained earlier, the Java bytecode was carefully designed so that it would be easy to
translate directly into native machine code for very high performance by using a just-in-
time compiler.
KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA
Dynamic
Java programs carry with them substantial amounts of run-time type information that is
used to verify and resolve accesses to objects at run time.
This makes it possible to dynamically link code in a safe and expedient manner
Distributed
Java is distributed because it facilitates us to create distributed applications in java.
RMI and EJB are used for creating distributed applications.
We may access files by calling the methods from any machine on the internet.
Platform Independent
Java is a platform independent programming language, because when you install JDK in
the system then JVM is also installed automatically on the system.
For every operating system separate JVM is available which is capable to read the .class
file or byte code.
When we compile Java code then .class file is generated by java compiler (javac) these
codes are readable by the JVM and every operating system have its own JVM so JVM is
platform dependent but due to JVM java is platform independent.
public: The public keyword is an access specifier, which means that the content of the following
block accessible from all other classes.
static: The keyword static allows main() to be called without having to instantiate a particular
instance of a class.
void: The keyword void tells the compiler that main() does not return a value. The methods can
return value.
main(): main is a method called when a java application begins,
String args [] Declares a parameter named args, which is an array of instance of the class string.
Args[] receives any command-line argument present when the program is executed.
[Link]()System is predefined class that provides access to the system. Out is the
output stream that is connected to the [Link] is accomplished by the built-in println()
method. Println() displays the string which is passed to it.
Compilation of Java Program
Keywords
6 Conditional Operator ?:
Arithmetic Operator
An arithmetic operator performs basic mathematical calculations such as addition, subtraction,
multiplication, division etc. on numerical values (constants and variables).
Increment / Decrement Operators
Increment and decrement operators are unary operators that add or subtract one, to or from
their operand.
the increment operator ++ increases the value of a variable by 1, e.g. a++ means a=a+1
the decrement operator -- decreases the value of a variable by 1. e.g. a–– means a=a–1
Relational Operators
A relational operators are used to compare two values.
They check the relationship between two operands, if the relation is true, it returns 1; if the
relation is false, it returns value 0.
Relational expressions are used in decision statements such as if, for, while, etc
Logical Operators
Logical operators are decision making operators.
They are used to combine two expressions and make decisions.
An expression containing logical operator returns either 0 or 1 depending upon whether
expression results false or true.
Assignment Operators
Assignment operators are used to assign a new value to the variable.
The left side operand of the assignment operator is a variable and right side operand of the
assignment operator is a value or a result of an expression.
Meaning of = in Maths and Programming is different.
Value of LHS & RHS is always same in Math.
In programming, value of RHS is assigned to the LHS
Bitwise Operators
bitwise operators can be applied to the integer types, long, int, short, byte and char.
These operators act upon the individual bits of their operands.
Boolean operators
The Boolean logical operators operate only on boolean operands.
All of the binary logical operators combine two boolean values to form a resultant
boolean value.
Switch Statement
Java switch statement executes one statement from multiple conditions. It is like if-else-if ladder
statement. Java 7, you can use strings in the switch statement.
Points to Remember
o There can be one or N number of case values for a switch expression.
o The case value must be of switch expression type only. The case value must be literal or
constant. It doesn't allow variables.
o The case values must be unique. In case of duplicate value, it renders compile-time error.
o The Java switch expression must be of byte, short, int, long (with its Wrapper
type), enums and string.
o Each case statement can have a break statement which is optional. When control reaches
to the break statement, it jumps the control after the switch expression. If a break statement
is not found, it executes the next case.
o The case value can have a default label which is optional.
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;
}
ACTIVITY : CREATE A PROGRAM BY USING DIFFERENT CONDITIONAL STATEMENT
Create a Method
A method must be declared within a class. It is defined with the name of the method, followed by
parentheses (). Java provides some pre-defined methods, such as [Link](), but you can
also create your own methods to perform certain actions:
Public class Main {
Static void myMetjod() {
//code to be executed
} }
Method Declaration
The method declaration provides information about method attributes, such as visibility, return-
type, name, and arguments. It has six components that are known as method header,
Call a Method
To call a method in Java, write the method's name followed by two parentheses () and a semicolon;
public class Main {
static void myMethod() {
[Link]("I just got executed!");
}
public static void main(String[] args) {
myMethod();
}}
EXAMPLE
static int plusMethodInt(int x, int y) { return x + y; }
static double plusMethodDouble(double x, double y) { return x + y; }
public static void main(String[] args) {
int myNum1 = plusMethodInt(8, 5);
DEFINITION:
An array is a fixed size sequential collection of elements of same data type grouped
DEFINITION ARRAY IN JAVA
An array is a fixed size sequential collection of elements of same data type grouped under
single variable name.
An array is a group of like-typed variables that are referred by a common name.
Example:
type varname[]; int month[];
varname = new type[size]; month = new int[12];
type varname[]=new type[size]; int varname[]=new int[size];
Multidimensional Arrays
int twoD[][]=new int[4][5];
If month is a reference to an array, [Link] will give you the length of the array.
Initialization:
⚫ int x[] = {1, 2, 3, 4};
⚫ char []c = {‘a’, ‘b’, ‘c’};
⚫ double d[][]= { {1.0,2.0,3.0}, {4.0,5.0,6.0}, {7.0,8.0,9.0} };
UNIT 2
OBJECTS AND CLASSES
Classes and Objects are basic concepts of Object Oriented Programming that revolve around real
life entities.
What is Object?
An object is an instance of a class, An object has a state and behavior.
Example: if class is car the object are audi ,Nissan,etc
State: represents the data (value) of an object.
Behavior: represents the behavior (functionality) of an object such as deposit.
Identity: An object identity is typically implemented via a unique ID. The value of the ID
is not visible to the external user. However, it is used internally by the JVM to identify
each object uniquely.
For Example, Pen is an object. Its name is Reynolds; colour is white, known as its state. It
is used to write, so writing is its behaviour.
Creating Object & Accessing members
new keyword creates new object
Syntax: ClassName objName = new ClassName();
Example :SmartPhone iPhone = new SmartPhone();
Object variables and methods can be accessed using the dot (.) operator
Example: [Link] = 8000;
Declaring an Object
Object of that data type will have all the attributes and abilities that are designed in the class.
The new operator dynamically allocates memory for an object and returns a reference to it.
This reference is, more or less, the address in memory of the object allocated by new.
This reference is then stored in the variable. Thus, in Java, all class objects must be dynamically
allocated.
new operator dynamically allocates memory for an object
WHAT IS CLASS?
Class is derived datatype, it combines members of different datatypes into one.
Defines new datatype (primitive ones are not enough).
For Example: Car, College, Bus etc.
This new datatype can be used to create objects.
A class is a template for an object.
DEFINE CONSTRUCTOR
A constructor in Java is a special type of method that is used to initialize objects.
The constructor is called when an object of a class is created.
A constructor initializes an object immediately upon creation.
It has the same name as the class in which it resides and is syntactically similar to a
method.
A constructor defines what happens when an object of a class is created.
Properties of Constructor
Constructor is invoked automatically whenever an object of class is created.
Constructor name must be the same as its class name
A Constructor must have no explicit return type
A Java constructor cannot be abstract, static, final, and synchronized
It calls a default constructor if there is no constructor available in the class. In such case, Java compiler
provides a default constructor by default.
Default Constructor
A constructor defines what occurs when an object of a class is created.
Most classes explicitly define their own constructors within their class definition but if no
explicit constructor is specified then java will automatically supply a default constructor.
Once you define your own constructor, the default constructor is no longer used.
The default constructor automatically initializes all instance variables to zero.
Code before compilation: Code after compilation:
class MyConst { class MyConst{
public static void main(String[] args) { MyConst(){
MyConst c=new MyConst(); //Default Constructor...
} }
} public static void main(String[] args) {
c=new MyConst();
}}
Copy Constructor
It is a special type of constructor that is used to create a new object using the existing object of a
class that had been created previously.
Finalize method in Java is an Object Class method that is used to perform clean-up activity
before destroying any object. It is called by Garbage collector before destroying the object from
memory.
Finalize () method is called by default for every object before its deletion
Finalize is an Object class method in Java.
The finalize() method is a non-static and protected method of [Link] class.
ACCESS MODIFIER
Private(-) The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
Default(~) The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default.
Protected(#) The access level of a protected modifier is within the package and outside
the package through child class. If you do not make the child class, it cannot be accessed
from outside the package.
Public(+) The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.
WHAT IS METHOD?
A method is a group of statements that performs a specific task.
A large program can be divided into the basic building blocks known as method/function.
The function contains the set of programming statements enclosed by { }.
Program execution in many programming language starts from the main [Link] is
also a method/function
void main()
{
// body part }
Method Definition
A method definition defines the method header and body.
A method body part defines method logic.
Then we can call it as [Link](). (using dot operater)
A function that is a property of an object is called its method.
Syntax: return-type method_name(datatyp1 arg1, datatype2 arg2,...) {
functions statements
}
Example: int addition(int a, int b);
{
return a+b; }
These classes are not really part of the language; they are provided in the package [Link].
You can get more information on-line via the Java Packages page.
STRING: String is a sequence of characters. In java, objects of String are immutable which means
a constant and cannot be changed once created.
String class provides a lot of methods to perform operations on strings such as compare(), concat(),
equals(), split(), length(), replace() to create a String:
BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 28 of 79
KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA
STRING BUFFER:
Java StringBuffer class is used to create mutable (modifiable) String objects. The
StringBuffer class in Java is the same as String class except it is mutable i.e. it can be changed.
class StringBufferExample{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
[Link]("Java");//now original string is changed
[Link](sb);//prints Hello Java
} }
Files
File handling is an important part of any application.
Java has several methods for creating, reading, updating, and deleting files.
Java File Handling
The File class from the [Link] package, allows us to work with files.
To use the File class, create an object of the class, and specify the filename or directory
name:
Example
import [Link]; // Import the File class
File myObj = new File("[Link]"); // Specify the filename
This referenc
The this is a keyword in Java which is used as a reference to the object of the current class, with
in an instance method or a constructor. Using this you can refer the members of a class such as
constructors, variables and methods.
Using “this” you can −
Differentiate the instance variables from local variables if they have same names, within a
constructor or a method.
class Student {
int age;
Student(int age) {
[Link] = age;
}
}
Call one type of constructor (parametrized constructor or default) from other in a class. It is known
as explicit constructor invocation.
class Student {
int age
Student() {
this(20);
}
Student(int age) {
[Link] = age;
}
}
Super Keyword in Java
The super keyword in Java is a reference variable which is used to refer immediate parent class
object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly
which is referred by super reference variable.
Usage of Java super Keyword
1. super can be used to refer immediate parent class instance variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.
UNIT - 3
INHERITANCE AND POLYMORPHISM
Inheritance:
The mechanism of a class to derive properties and characteristics from another class is
called Inheritance.
Inheritance is the process, by which a class can acquire(reuse) the properties and methods
of another class.
The mechanism of deriving a new class from an old class is called inheritance.
The new class is called derived class and old class is called base class.
It is the most important feature of Object Oriented Programming. Inheritance is
implemented using super class and sub class relationship in object-oriented languages.
The derived class may have all the features of the base class and the programmer can add
new features to the derived class.
Inheritance is also known as “IS-A relationship” between parent and child classes.
For Example :
Car IS A Vehicle
Bike IS A Vehicle
Inheritance: Advantages
• Promotes reusability
• When an existing code is reused, it leads to less development and maintenance costs.
• It is used to generate more dominant objects.
• Avoids duplicity and data redundancy.
• Inheritance makes the sub classes follow a standard interface.
Implementing Inheritance
To inherit a class, you simply incorporate the definition of one class into another by using
“extends” keyword.
Syntax:
FINAL KEYWORD
If you don't want other classes to inherit from a class, use the final keyword:
Single inheritance is the simplest type of inheritance in java. In this, a class inherits the
properties from a single class.
The multi-level inheritance includes the involvement of at least two or more than two
classes. One class inherits the features from a parent class and the newly created sub-
class becomes the base class for another new class.
Multiple inheritance in java is the capability of creating a single class with multiple
superclasses java doesn't provide support for multiple inheritance in classes.
Hierarchical inheritance" occurs when multiple child classes inherit the methods and
properties of the same parent class. This simply means we have only one superclass and
multiple sub-classes in hierarchical inheritance in Java
Hybrid inheritance is a method where one class inherits from the parent class and the
newly created sub-class becomes the base class for another new class.
WHAT IS OVERRIDING
If a class inherits a method from its superclass, then there is a chance to override the method
provided that it is not marked final.
The benefit of overriding is: ability to define a behavior that's specific to the subclass type, which
means a subclass can implement a parent class method based on its requirement.
OBJECT CLASS
Object class is present in [Link] package. The Object class is the parent class of all
the classes in java by default. In other words, it is the topmost class of java.
toString() Method:
It's provide string representation or convert
object to string form.
you can override toString() method to get your
own String representation of objects.
equals(Object obj) Method: It's used to compare the two objects dynamically.
getClass( ) Method: It's return runtime class object and used to get metadata information
as well.
finalize( ) method:This method call required to perform garbage collector.
clone( ) method: It used to create the copy or clone of object.
wait(), notify( ) notifyAll( ) Methods: These are used in multithreading.
WHAT IS POLYMORPHISM?
Polymorphism is the ability of an object to take on many forms.
The word “Polymorphism” derives from two words i.e. “Poly” which means many and
“morphs” meaning forms. Thus polymorphism means many forms.
Any Java object that can pass more than one IS-A test is considered to be polymorphic.
Advantages of Polymorphism
Code cleanliness
Ease of implementation
Aligned with Real World
Overloaded Constructors
Reusability of code
DYNAMIC BINDING
The method call is bonded to the method body at runtime. This is also known as late binding.
There are two type of dynamic binding
Static Binding( Early Binding)
Dynamic Biding (late Binding)
GENERIC
Java Generic methods and generic classes enable programmers to specify, with a single
method declaration, a set of related methods, or with a single class declaration, a set of
related types, respectively.
Generics also provide compile-time type safety that allows programmers to catch invalid
types at compile time.
Generic Classes
A generic class declaration looks like a non-generic class declaration, except that the class name
is followed by a type parameter section.
T used inside the angle bracket <> indicates the type parameter. Inside the Main class, we
have created two objects of GenericsClass
intObj - Here, the type parameter T is replaced by Integer. Now, the GenericsClass works
with integer data.
stringObj - Here, the type parameter T is replaced by String. Now, the GenericsClass works
with string data.
GENERIC METHOD
Single generic method declaration that can be called with arguments of different types.
Based on the types of the arguments passed to the generic method, the compiler handles each
method call appropriately
Rules:
All generic method declarations have a type parameter section delimited by angle brackets
(< and >) that precedes the method's return type ( < E > in the next example).
Each type parameter section contains one or more type parameters separated by commas.
A type parameter, also known as a type variable, is an identifier that specifies a generic
type name.
The type parameters can be used to declare the return type and act as placeholders for the
types of the arguments passed to the generic method, which are known as actual type
arguments.
A generic method's body is declared like that of any other method. Note that type
parameters can represent only reference types, not primitive types (like int, double and
char).
class GenericsClass<T> {
Syntax;
class GenericsClass<T> {...} // variable of T type
private T data;
Syntax; public GenericsClass(T data) {
public <T> void genericMethod(T data) [Link] = data;
{...} }
// method that return T type variable
public <T> void genericsMethod(T data) {
[Link]("Generics Method:"); }
}
ABSTRACT CLASS
A class which contains the abstract keyword in its declaration is known as abstract class.
Abstract classes may or may not contain abstract methods,
i.e., methods without body ( public void get(); )
But, if a class has at least one abstract method, then the class must be declared abstract.
If a class is declared abstract, it cannot be instantiated.
To use an abstract class, you have to inherit it from another class, provide implementations
to the abstract methods in it.
If you inherit an abstract class, you have to provide implementations to all the abstract
methods in it.
INTERFACE
An interface is a reference type in Java. It is similar to class. It is a collection of abstract
methods. A class implements an interface, thereby inheriting the abstract methods of the interface.
An interface is similar to a class in the following ways −
An interface can contain any number of methods.
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.
Interfaces appear in packages, and their corresponding bytecode file must be in a directory
structure that matches the package name.
PACKAGES
Packages are used in Java in order to prevent naming conflicts, to control access, to make
searching/locating and usage of classes, interfaces, enumerations and annotations easier,
etc.
A Package can be defined as a grouping of related types (classes, interfaces, enumerations
and annotations ) providing access protection and namespace management.
Some of the existing packages in Java are −
[Link] − bundles the fundamental classes
[Link] − classes for input , output functions are bundled in this package
Synatx:
package packagename;
UNIT 4
EVENT AND GUI PROGRAMMING
WHAT IS AN EVENT
Change in the state of an object is known as event
Events are generated as result of user interaction with the graphical user interface
components.
For example, clicking on a button, moving the mouse, entering a character through
keyboard,selecting an item from list, scrolling the page are the activities that causes an
event to happen.
TYPES OF EVENT
The events can be broadly classified into two categories:
Foreground Events - Those events which require the direct interaction of user.
They are generated as consequences of a person interacting with the graphical components
in Graphical User Interface.
For example, clicking on a button.
Background Events - Those events that require the interaction of end user are known as
background events. Operating system interrupts, hardware or software failure, timer
expires, an operation completion are the example of background events.
The Delegation Event Model has the following key participants namely:
Source –
The source is an object on which event occurs.
Source is responsible for providing information of the occurred event to it's handler.
Java provide as with classes for source object.
Listener –
Event [Link] is responsible for generating response to an event.
From java implementation point of view the listener is also an object.
Listener waits until it receives an event.
Once the event is received, the listener process the event an then returns.
Java BorderLayout
A BorderLayout places components in up to five areas: top, bottom, left, right, and center. It is
the default layout manager for every java JFrame
Java BorderLayout
Java FlowLayout
FlowLayout is the default layout manager for every JPanel. It simply lays out components in a
single row one after the other.
Java FlowLayout
Java GridBagLayout
It is the more sophisticated of all layouts. It aligns components by placing them within a grid of
cells, allowing components to span more than one cell.
Java GridBagLayout
For example,
Panel pnl = new Panel(); // Panel is a container
Button btn = new Button("Press"); // Button is a component
[Link](btn); // The Panel container adds a Button component
GUI components are also called controls
add(lb1);
add(txt1);
add(lb2);
BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 53 of 79
KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA
add(txt2);
add(lb3);
setSize(200,200);
setTitle("My Cal");
setLayout(new FlowLayout());
setLayout(new FlowLayout([Link]));
setLayout(new FlowLayout([Link]));
[Link](this);
[Link](this);
[Link](this);
}
public void actionPerformed(ActionEvent ae) {
double a=0,b=0,c=0;
try
{
a = [Link]([Link]());
}
catch (NumberFormatException e) {
[Link]("Invalid input");
}
try
{
b = [Link]([Link]());
}
catch (NumberFormatException e) {
[Link]("Invalid input");
}
if([Link]()==btn1)
{
BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 54 of 79
KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA
c = a + b;
[Link]([Link](c));
}
}
public static void main(String[] args)
{
Calculator calC = new Calculator();
[Link](true);
[Link](300,300);
}
}
ACTIVITY: WORK ON REMAINING COMPONENTS OF GUI AND CREATE A ALL
COMPONENTS AWT PROGRAM
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.
Advantage of Applet
o It works at client side so less response time.
o Secured
o It can be executed by browsers running under many plateforms, including Linux, Windows,
Mac Os etc.
Drawback of Applet
o Plugin is required at client browser to execute applet.
1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is maximized. It is used
to start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop or browser
is minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.
UNIT - 5
I/O PROGRAMMING
Java I/O (Input and Output) is used to process the input and produce the output.
Java uses the concept of a stream to make I/O operation fast. The [Link] package contains all the
classes required for input and output operations.
Stream
A stream is a sequence of data. In Java, a stream is composed of bytes. It's called a stream because
it is like a stream of water that continues to flow.
In Java, 3 streams are created for us automatically. All these streams are attached with the console.
1) [Link]: standard output stream
2) [Link]: standard input stream
3) [Link]: standard error stream
Let's see the code to print output and an error message to the console.
1. [Link]("simple message");
2. [Link]("error message");
Let's see the code to get input from console.
1. int i=[Link]();//returns ASCII code of 1st character
2. [Link]((char)i);//will print the character
OutputStream vs InputStream
The explanation of OutputStream and InputStream classes are given below:
OutputStream: Java application uses an output stream to write data to a destination; it may be a
file, an array, peripheral device or socket.
InputStream : Java application uses an input stream to read data from a source; it may be a file,
an array, peripheral device or socket.
OutputStream class: OutputStream class is an abstract class. It is the superclass of all classes
representing an output stream of bytes. An output stream accepts output bytes and sends them to
some sink.
Useful methods of OutputStream
Method Description
1) public void write(int)throws IOException is used to write a byte to the current output stream.
2) public void write(byte[])throws is used to write an array of byte to the current output
IOException stream.
4) public void close()throws IOException is used to close the current output stream.
OutputStream Hierarchy
InputStream class: InputStream class is an abstract class. It is the superclass of all classes
representing an input stream of bytes.
Useful methods of InputStream
Method Description
1) public abstract int read()throws reads the next byte of data from the input stream. It returns -1
IOException at the end of the file.
2) public int available()throws returns an estimate of the number of bytes that can be read from
IOException the current input stream.
InputStream Hierarchy
Java - RandomAccessFile
This class is used for reading and writing to random access file. A random access file behaves like
a large array of bytes. There is a cursor implied to the array called file pointer, by moving the
cursor we do the read write operations.
Constructor
Constructor Description
RandomAccessFile(File Creates a random access file stream to read from, and optionally
file, String mode) to write to, the file specified by the File argument.
RandomAccessFile(String name, Creates a random access file stream to read from, and optionally
String mode) to write to, a file with the specified name.
Method
void close() It closes this random access file stream and releases any
system resources associated with the stream.
FileChannel getChannel() It returns the unique FileChannel object associated with this
file.
void seek(long pos) It sets the file-pointer offset, measured from the beginning of
this file, at which the next read or write occurs.
void seek(long pos) It sets the file-pointer offset, measured from the beginning of
this file, at which the next read or write occurs.
UNIT - 6
MULTITHREADING IN JAVA
Program and Thread are two basic unit of java program execution
Multitasking is a process of executing multiple tasks simultaneously.
Multitasking can be achieved in two ways:
o Process-based Multitasking (Multiprocessing)
o Thread-based Multitasking (Multithreading)
THREAD
A thread is a lightweight sub process, smallest unit of processing
Thread are independent
It uses a shared memory area
Java provide Thread class to achieve thread programming
Advantage:
It doesn’t block the user
Can perform many operation together so it save time.
Thread are independent so it doesn’t affect other threads
CREATING THREAD
Threads are implemented in the form of objects.
The run() and start() are two inbuilt methods which helps to thread implementation
The run() method is the heart and soul of any thread
It makes up the entire body of a thread
Blocked State:
A thread is said to be blocked
It is prevented to entering into the runnable and the running state.
This happens when the thread is suspended, sleeping, or waiting in order to satisfy
certain requirements.
A blocked thread is considered "not runnable" but not dead and therefore fully
qualified to run again.
This state is achieved when we Invoke suspend() or sleep() or wait() methods.
Dead State:
Every thread has a life cycle.
A running thread ends its life when it has completed executing its run() method. It
is a natural death.
A thread can be killed in born, or in running, or even in "not runnable" (blocked)
condition.
It is called premature death.
This state is achieved when we invoke stop() method or the thread completes it
execution.
JAVA SYNCHRONIZATION
Generally threads use their own data and methods provided inside their run() methods.
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.
Java enables us to overcome this problem using a technique known as Synchronization.
For ex.: One thread may try to read a record from a file while another is still writing to
the same file.
When the method declared as synchronized java creates a “monitor” and hands it over to
the thread that calls the method first time.
Synchronized(Lock-object)
{
……..// code here is synchronized
}
Exception Handling in Java
An exception (or exceptional event) is a problem that arises during the execution of a
program.
When an Exception occurs the normal flow of the program is disrupted
and the program/Application terminates abnormally, which is not recommended,
therefore, these exceptions are to be handled.
1) Checked Exception
The classes that directly inherit the Throwable class except RuntimeException and Error are
known as checked exceptions. For example, IOException, SQLException, etc. Checked
exceptions are checked at compile-time.
BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 69 of 79
KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA
2) Unchecked Exception
The classes that inherit the RuntimeException are known as unchecked exceptions. For example,
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc.
Unchecked exceptions are not checked at compile-time, but they are checked at runtime.
3) Error
Error is irrecoverable some Example of error are OutOfMemoryError, VirtualMachineError,
AssertionError etc
try block
• The try block contains a set of statements that might throw an exception
• It must be used within the method.
• A try block must be followed by catch blocks or finally block or both.
Synatax of java try-catch Synatax of java try-finally
try{ try{
// code that may throw an exception // code that may throw an exception
}catch(Exception_class_name ref){} }finally{}
throw throws
The throw keyword in Java is used to throws is a keyword in Java which is
explicitly throw an exception from a used in the signature of method to
method or any block of code. indicate that this method might throw
We can throw either checked or one of the listed type exceptions.
unchecked exception. The caller to these methods has to
The throw keyword is mainly used to handle the exception using a try-catch
throw custom exceptions. block.
COLLECTIONS IN JAVA
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.
What is a framework in Java
o It provides readymade architecture.
o It represents a set of classes and interfaces.
o It is optional.
What is Collection framework
The Collection framework represents a unified architecture for storing and manipulating a group
of objects. It has:
1. Interfaces and its implementations, i.e., classes
2. Algorithm
INTRODUCTION TO JAVABEANS
JavaBeans is a portable, platform-independent model written in Java Programming
Language.
Its components are referred to as beans
JavaBeans are classes which encapsulate several objects into a single object
It is a reusable software components
JavaBeans has several conventions that should be followed:
Beans should have a default constructor (no arguments)
Beans should provide getter and setter methods
o A getter method is used to read the value of a readable property
o To update the value, a setter method should be called
Beans should implement [Link], as it allows to save, store and restore the
state of a JavaBean you are working on
Implementation of JavaBeans Access the JavaBean class
public class Employee implements public class Employee1 {
[Link] public static void main(String args[])
{ private int id; {
private String name; Employee s = new Employee();
public Employee() [Link]("Chandler");
{ } [Link]([Link]());
public void setId(int id) }
{ [Link] = id; } }
public int getId()
{ return id; }
public void setName(String name)
{ [Link] = name; }
public String getName()
{ return name; }}
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.
Advantage of Java Networking
1. Sharing resources
2. Centralize software management
The [Link] package supports two protocols,
1. TCP: Transmission Control Protocol provides reliable communication between the sender
and receiver. TCP is used along with the Internet Protocol referred as TCP/IP.
2. UDP: User Datagram Protocol provides a connection-less protocol service by allowing
packet of data to be transferred along two or more nodes
JAVA NETWORKING TERMINOLOGY
1. IP Address
2. Port Number
3. Protocol
4. MAC Address
5. Connection-oriented and connection-less protocol
6. Socket
1) IP Address:
IP address is a unique number assigned to a node of a network e.g. [Link] .
It is composed of octets that range from 0 to 255.
It is a logical address that can be changed.
2) 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.
3) 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.
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.
[Link] package
The [Link] 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.
PART B
14. What is package? Mention the steps to create and use java package with example.
15. Explain each word in the statement Public Static Void Main.
16. Explain command line argument with a program. Illustrate the use of break and continue
statement with an example.
17. Write a program to implement constructor.
18. What is constructor? Explain its types.
19. Write the syntax of creating of object in java.
20. Difference between JDK, JRE, JVM.
21. Explain try and catch with example.
22. Explain the steps of executing an applet program.
23. What is Mouse event? Explain different mouse events with example.
24. What is key event? Explain different key events with example.
25. Explain constructor, Inheritance with its features.