0% found this document useful (0 votes)
15 views81 pages

Java Object-Oriented Concepts Overview

The document provides a comprehensive overview of Java, covering its history, features, and fundamental concepts such as the Java Development Kit (JDK), Java Runtime Environment (JRE), bytecode, and the Java Virtual Machine (JVM). It explains Java's object-oriented nature, its portability, security features, and various data types, along with examples of variable declarations, operators, and control structures. Additionally, it includes activities for practical application of the concepts discussed, aimed at BCA students in their third semester at Krupanidhi Degree College.

Uploaded by

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

Java Object-Oriented Concepts Overview

The document provides a comprehensive overview of Java, covering its history, features, and fundamental concepts such as the Java Development Kit (JDK), Java Runtime Environment (JRE), bytecode, and the Java Virtual Machine (JVM). It explains Java's object-oriented nature, its portability, security features, and various data types, along with examples of variable declarations, operators, and control structures. Additionally, it includes activities for practical application of the concepts discussed, aimed at BCA students in their third semester at Krupanidhi Degree College.

Uploaded by

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

JAVA

III SEMESTER BCA

KRUPANIDHI DEGREE COLLEGE


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

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

 Executes stand-alone or “on-demand” in web browser as applets


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

Java Development Kit (JDK)


 JDK contains tools needed ,
o To develop the Java programs and
o JRE to run the programs.
 The tools include compiler ([Link]), Java application launcher ([Link]), Appletviewer,
etc…
 Java application launcher ([Link]),
o Opens a JRE, loads the class, and invokes its main method.
KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

Java Runtime Environment (JRE)


 The Java Runtime Environment (JRE) is required to run java applications.
 It combines the Java Virtual Machine (JVM), platform core classes and supporting
libraries.
 JRE is part of the Java Development Kit (JDK), but can be downloaded separately.
 It does not contain any development tools such as compiler, debugger, etc.
Byte code
 Byte code is intermediate representation of java source code.
 It produce by java compiler by compiling java source code.
 Extension for java class file or byte code is ‘.class’.
 It is platform independent.
JVM (Java Virtual Machine)
 JVM is virtual because It provides a machine interface that does not depend on the
operating system and machine hardware architecture.
 JVM interprets the byte code into the machine code.
 JVM itself is platform dependent, but Java is Not.
KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

Explain features of JAVA.


The Features of Java programming are as below
1. Simple
2. Secure
3. Portable
4. Object-oriented
5. Robust
6. Multithreaded
7. Architecture-natural
8. Interpreted
9. High performance
10. Distributed
11. Dynamic
Simple
 It’s simple because it contains many features of other languages like C and C++
 It also removed complexities like pointers, Storage classes, goto statement and
multiple Inheritance.
Secure
 Java is best known for its security. With Java, we can develop virus-free systems.
Java is secured because:
No explicit pointer
Java Programs run inside virtual machine sandbox
Bytecode Verifier
Portable
 Java is portable because it facilitates you to carry the java bytecode to any platform.
Object oriented
 Java is Object-oriented programming language. Everything in Java is an object.
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.

Program Structure, Compilation and Run Process


Simple Java Program Structure
public class Example
{
public static void main(String args[])
{
[Link](“First Example”);
} }
class Example
Here name of the class is Example.
public static void main(String args[])
KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

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

ACTIVITY: CREATE A PROGRAM TO DISPLAY HELLO WORLD


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

Keywords

Explain Data types of JAVA.


Data Type Size Range Example
byte Byte -128 to 127 byte a = 10;
short Bytes -32,768 to 32,767 short a = 200;
Int Bytes -2,147,483,648 to 2,147,483,647 int a = 50000;
-9,223,372,036,854,775,80---to
long Bytes 9,223,372,036,854,775,807 long a = 20;
float Bytes 1.4e-045 to 3.4e+038 float a = 10.2f;
double Bytes 4.9e-324 to 1.8e+308 double a = 10.2;
char Bytes 0 to 65536 (Stores ASCII of character) char a = ‘a’;
boolean Not true or false boolean a = true;
defined

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 8 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

Character Data Type


 char in Java is not the same as char in C or C++.
 Java uses Unicode to represent characters.
 Unicode defines a fully international character set that can represent all of the
 characters found in all human languages.
 Hence it requires 16 bits.
 The range of a char in java is 0 to 65,536.
 There are no negative chars

ACTIVITY: CREATE A PROGRAM USING ALL DATA TYPE

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 9 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

Explain Variable in Java


 The variable is the basic unit of storage in a java program.
 A variable is defined by the combination of identifiers, a type and an optional initialize.
 All variables have a scope, which defines their visibility and a life time.
Naming Rules for a variable: -
 It should start with a lowercase letter such as id, name.
 It should not start with the special characters like & (ampersand), $ (dollar), _
(underscore).
 If the name contains multiple words, start it with the lowercase letter followed by
an uppercase letter such as firstName, lastName.
 Avoid using one-character variables such as x, y, z.
Declaring a Variable: -
All variables must be declared before they can be used. The basic form of a variable
declaration is shown here.
Type identifier [= value] [, identifier [=value]...];
Int a,b,c; // declare 3 integers
Byte z = 22; // initialize z
Char x = ‘X’; // the variable x has the value ‘X’

ACTIVITY: CREATE A PROGRAM BY USING DIFFERENT VARIABLES TYPES

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 10 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

The Scope and Lifetime of Variables


 Scope
The scope of a declared element is the portion of the program where the element is
visible.
 Lifetime
The lifetime of a declared element is the period of time during which it is alive.
The lifetime of the variable can be determined by looking at the context in which
they're defined.
 Java allows variables to be declared within any block.
 A block begins with an opening curly brace and ends by a closing curly brace.
⚫ Variables declared inside a scope are not accessible to code outside.
⚫ Scopes can be nested. The outer scope encloses the inner scope.
⚫ Variables declared in the outer scope are visible to the inner scope.
⚫ Variables declared in the inner scope are not visible to the outside scope.

public class Scope


{
public static void main(String args[]){
int x; //know to all code within main
x=10;
if(x==10){ // starts new scope
int y=20; //Known only to this block
//x and y both known here
[Link]("x and y: "+x+" "+y);
x=y+2;
}
[Link]("x is "+x);
}
}

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 11 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

Explain Operators in JAVA


Sr
. Operator Examples

1 Arithmetic Operators +,-,*,/,%

<, <=, >, >=, ==,


2 Relational Operators !=

3 Logical Operators &&, ||, !

4 Assignment Operators =, +=, -=, *=, /=

5 Increment and Decrement Operators ++, --

6 Conditional Operator ?:

7 Bitwise Operators &, |, ^, <<, >>

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

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 12 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

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.

ACTIVITY : CREATE A PROGRAM BY USING DIFFERENT OPERATORS

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 13 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

Explain Control structures including selection, looping


A control structure is a syntactic form in a programming language that expresses the flow of
control over a specific list of instructions to make decisions among the alternate path or given
paths and executes the instructions in the sequence in which they appear, one by one.

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 14 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

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

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 15 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

Explain Loop Statements


In programming, sometimes we need to execute the block of code repeatedly while some condition
evaluates to true. The execution of the set of instructions depends upon a particular condition

ACTIVITY : CREATE A PROGRAM BY USING DIFFERENT LOOPING STATEMENT

What is a method how to declare and call?


A method is a block of code which only runs when it is called. You can pass data, known as
parameters, into a method. Methods are used to perform certain actions, and they are also known
as functions.
Types of Method
There are two types of methods in Java:
o Predefined Method: 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.
Example length(), equals(), compareTo(), sqrt()
o 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.

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 16 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

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();
}}

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 17 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

Parameters and Arguments


Information can be passed to methods as parameter. Parameters act as variables inside the method.
Parameters are specified after the method name, inside the parentheses. You can add as many
parameters as you want, just separate them with a comma.

public class Main {


static void myMethod(String fname) {
[Link](fname + " Refsnes");
}
public static void main(String[] args) {
myMethod("Liam");
myMethod("Jenny");
myMethod("Anja");
}}

Method Overloading in Java


If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading.
If we have to perform only one operation, having same name of the methods increases the
readability of the program.
There are two ways to overload the method in java
1. By changing number of arguments
2. By changing the data type

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);

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 18 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

double myNum2 = plusMethodDouble(4.3, 6.26);


[Link]("int: " + myNum1);
[Link]("double: " + myNum2); }

Java Math class


Java Math class provides several methods to work on math calculations like min(), max(), avg(),
sin(), cos(), tan(), round(), ceil(), floor(), abs() etc.
public class JavaMathExample1
{
public static void main(String[] args)
{
double x = 28, y = 4;
// return the maximum of two numbers
[Link]("Maximum number of x and y is: " +[Link](x, y));

// return the square root of y


[Link]("Square root of y is: " + [Link](y));
[Link]("expm1 of a is: " +Math.expm1(x));
}
}

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.

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 19 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

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} };

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 20 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

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

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 21 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

 Here, s1 is a variable of the class type.


 The class name followed by parentheses specifies the constructor for the class.
 It is important to understand that new allocates memory for an object during run time.

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.

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 22 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

class <class_name>{ class Car{


field; String company;
method; String model;
} double price;
double mileage;
..........}
A class in Java can contain:
Fields
Methods
Constructors
Blocks
Nested class and interface

ACTIVITY : CREATE A PROGRAM TO UNDERSTAND CLASS AND OBJECT OF YOUR


CHOICE

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 23 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

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.

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 24 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

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();
}}

Parameterized Constructor: A constructor which has a specific number of parameters is


called a parameterized constructor.
Parameterized Constructor: [Link]
class Cube {
double width, height;
Cube(double w, double h)
{ [Link]("Constructing cube");
width = w;
height = h;
}}
class MyMain{
public static void main(String[] args){
Cube c=new Cube(10,10);
}}

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 25 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

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.

ACTIVITY: CREATE A PROGRAM TO UNDERSTAND FINAZLIE METHOD

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 26 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

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.

ACTIVITY: CREATE A PROGRAM TO UNDERSTAND ACCESS MODIFIER

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 }

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 27 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

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 S1 = "hello", // initialize from a string literal


S2 = new String("bye"), // use new and the String constructor
S3 = new String(S1); // use new and a different constructor

CHARACTER: Java provides a wrapper class Character in [Link] package. An object of


type Character contains a single field, whose type is char.
Methods ;
1, isLetter(). Determines whether the specified char value is a letter. ;
2, isDigit(). Determines whether the specified char value is a digit

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:

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 29 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

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;

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 30 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

}
}

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.

ACTIVITY: CREATE A PROGRAM TO UNDERSTAND FILE IN JAVA

ACTIVITY: CREATE A PROGRAM TO UNDERSTAND SUPER KEYWORD AND


METHOD IN JAVA

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 31 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

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

Subclass and Superclass


 Base Class: The class whose properties are inherited by sub class is called Base
Class/Super class/Parent class.
 Derived Class: The class that inherits properties from another class is called Sub
class/Derived Class/Child class.

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 32 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

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:

class subclass -name extends superclass -name {


// body of class …
}

Implementing Inheritance in java

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 33 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

FINAL KEYWORD
If you don't want other classes to inherit from a class, use the final keyword:

Types of Inheritance in Java


 Single level inheritance
 Multilevel inheritance
 Multiple inheritance
 Hierarchical inheritance
 Hybrid inheritance

Note: Multiple and Hybrid Inheritance is not


supported in Java with the Class Inheritance,
we can still use those Inheritance with
Interface.

 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.

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 34 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

ACTIVITY: CREATE A PROGRAM TO UNDERSTAND INHERITANCE PROGRAM


WITH REAL TIME EXAMPLE

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.

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 35 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

Rules for Method Overriding


 The argument list should be exactly the same as that of the overridden method.
 The return type should be the same or a subtype of the return type declared in the original
overridden method in the superclass.
 The access level cannot be more restrictive than the overridden method's access level. For
example: If the superclass method is declared public then the overridding method in the sub
class cannot be either private or protected.
 Instance methods can be overridden only if they are inherited by the subclass.
 A method declared final cannot be overridden.
 A method declared static cannot be overridden but can be re-declared.
 If a method cannot be inherited, then it cannot be overridden.
 A subclass within the same package as the instance's superclass can override any superclass
method that is not declared private or final.
 A subclass in a different package can only override the non-final methods declared public
or protected.
 An overriding method can throw any uncheck exceptions, regardless of whether the
overridden method throws exceptions or not.
 Constructors cannot be overridden.

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 36 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

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.

public String toString()


{
// Can override and give own definition
}
hashCode() Method:
 It's generate unique hashcode for each object.
 The main advantage of saving objects.
 It's used to override for user defined objects for better performance like searching.

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 37 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

 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.

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 38 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

Runtime Polymorphism in java


Run-Time Polymorphism: Whenever an object is bound with the functionality at run time,
this is known as runtime polymorphism. The runtime polymorphism can be achieved by method
overriding.

Advantages of Polymorphism
 Code cleanliness
 Ease of implementation
 Aligned with Real World
 Overloaded Constructors
 Reusability of code

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 39 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

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)

ACTIVITY: PROGRAM TO UNDERSTAND THE DIFFERENT TYPE OF DYNAMIC


BINDING WITH LOGICAL CODE

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 40 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

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.

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 41 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

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:"); }
}

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 42 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

ABSTRACTION is the quality of dealing with ideas rather than events


In Java, abstraction is achieved using Abstract classes and interfaces.

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.

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 43 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

 Interfaces appear in packages, and their corresponding bytecode file must be in a directory
structure that matches the package name.

ACTIVITY: CREATE A PROGRAM TO LEARN ABSTRACT CLASS AND INTERFACE


TO BUILD APPLICATION

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 44 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

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;

TO RUN PACAKGE PROGRAM:


javac -d Destination_folder file_name.java

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 45 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

ACTIVITY: CREATE A PACKAGE AND USE IN THE PROGRAME AS IMPORT


STATEMENT TO CHECK THE WORKING OF INBUILD PACKAGE

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 46 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

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.

Event handling in java:


 Event Handling is the mechanism that controls the event and decides what should
happen if an event occurs.
 This mechanism have the code which is known as event handler that is executed
when an event occurs.
 Java Uses the Delegation Event Model to handle the events.

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 47 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

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.

MouseEvent and MouseMotionListener Interface


 A MouseEvent is also fired when you move and drag the mouse pointer at the source
object.
 But you need to use MouseMotionListener to handle the mouse-move and mouse-drag.
 The MouseMotionListener interface declares the following two abstract methods:

public void mouseDragged(MouseEvent e)


// Called-back when a mouse-button is pressed on the source component and then dragged.
public void mouseMoved(MouseEvent e)
// Called-back when the mouse-pointer has been moved onto the source component but no
buttons have been pushed.

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 48 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

KeyEvent and KeyListener Interface


 A KeyEvent is fired when you pressed, released, and typed (pressed followed by
released) a key on the source object.
 A KeyEvent listener must implement KeyListener interface, which declares three abstract
methods:

public void keyTyped(KeyEvent e)


// Called-back when a key has been typed (pressed and released).
public void keyPressed(KeyEvent e)
public void keyReleased(KeyEvent e)
// Called-back when a key has been pressed or released.

What is Swing in Java?


Swing in Java is a Graphical User Interface (GUI) toolkit that includes the GUI
components. Swing provides a rich set of widgets and packages to make sophisticated GUI
components for Java applications. Swing is a part of Java Foundation Classes(JFC), which is an
API for Java GUI programing that provide GUI.

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 49 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

Java Swing class Hierarchy Diagram

Java Swing Class Hierarchy Diagram


All components in Java Swing are JComponent which can be added to container classes.

What is a Container Class?


Container classes are classes that can have other components on it. So for creating a Java Swing
GUI, we need at least one container object. There are 3 types of Java Swing containers.
1. Panel: It is a pure container and is not a window in itself. The sole purpose of a Panel is
to organize the components on to a window.
2. Frame: It is a fully functioning window with its title and icons.
3. Dialog: It can be thought of like a pop-up window that pops out when a message has to
be displayed. It is not a fully functioning window like the Frame.

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 50 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

What is GUI in Java?


 GUI (Graphical User Interface) in Java is an easy-to-use visual experience builder for
Java applications.
 It is mainly made of graphical components like buttons, labels, windows, etc. through
which the user can interact with an application.
 GUI plays an important role to build easy interfaces for Java applications.

Java Layout Manager


The Layout manager is used to layout (or arrange) the GUI Java components inside a container.
There are many layout managers, but the most frequently used are-

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

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 51 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

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

AWT Containers and Components

There are two groups of GUI elements:


1. Component (Widget, Control): Components are elementary GUI entities, such
as Button, Label, and TextField. They are also called widgets, controls in other graphics
systems.
2. Container: Containers, such as Frame and Panel, are used to hold components in a specific
layout (such as FlowLayout or GridLayout). A container can also hold sub-containers.
In a GUI program, a component must be kept (or added) in a container. You need to identify a
container to hold the components. Every container has a method called add(Component c). A
container (say aContainer) can invoke [Link](aComponent) to add aComponent into
itself.

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 52 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

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

PROGRAM TO EXPLAIN THE COMPONENTS OF GUI


import [Link].*;
import [Link];
import [Link];

class Calculator extends Frame implements ActionListener


{
Label lb1,lb2,;
/Label Lb1=new Label("welco,");
Label Lb2=new Label("welco,");
TextField txt1,txt2;
Button btn1,btn2;
public Calculator()
{
lb1 = new Label("INPUT");
lb2 = new Label("Input");
txt1 = new TextField(10);
txt2 = new TextField(10);
btn1 = new Button("Add");
btn2 = new Button("Sub");

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.

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 55 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

APPLET AND ITS LIFE CYCLE


1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. Applet is destroyed.

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.

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 56 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

Applet Life Cycle Working


o The Java plug-in software is responsible for managing the life cycle of an applet.
o An applet is a Java application executed in any web browser and works on the client-side. It doesn't
have the main() method because it runs in the browser. It is thus created to be placed on an HTML
page.
o The init(), start(), stop() and destroy() methods belongs to the [Link] class.
o The paint() method belongs to the [Link] class.
o In Java, if we want to make a class an Applet class, we need to extend the Applet
o Whenever we create an applet, we are creating the instance of the existing Applet class. And thus,
we can use all the methods of that class.
ACTIVITY: DEMONSTRATE APPLET PROGRAM PART B OF LAB

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 57 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

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.

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 58 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

The working of Java OutputStream and InputStream

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.

3) public void flush()throws IOException flushes the current output stream.

4) public void close()throws IOException is used to close the current output stream.

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 59 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

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.

3) public void close()throws is used to close the current input stream.


IOException

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 60 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

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.

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 61 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

Method

Modifier and Method Method


Type

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.

int readInt() It reads a signed 32-bit integer from this file.

String readUTF() It reads in a string from 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 writeFloat(float It converts the float argument to an int using the


v) floatToIntBits method in class Float, and then writes that int
value to the file as a four-byte quantity, high byte first.

void write(int b) It writes the specified byte to this file.

int read() It reads a byte of data from this file.

long length() It returns the length of 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.

ACTIVITY: CREATE A PROGRAM TO PERFORM RANDOM ACCESS FILE

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 62 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

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

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 63 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

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

Thread can be created by two methods


1. By extending Thread Class
2. By implementing Runnable Interface

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 64 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 65 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

LIFE CYCLE OF THREAD

New born State:


 The thread is born and is said to be in newborn state.
 The thread is not yet scheduled for running.
 At this state, we can do only one of the following:
• Schedule it for running using start() method.
• Kill it using stop() method.
Runnable State:
 The thread is ready for execution
 Waiting for the availability of the processor.
 The thread has joined the queue
Running State:
 Thread is executing
 The processor has given its time to the thread for its execution.
 The thread runs until it gives up control on its own or taken over by other threads.

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 66 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

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.

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 67 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

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.

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 68 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

An exception can occur for many reasons. Some of them are:


• Invalid user input
• Device failure
• Loss of network connection
• Physical limitations (out of disk memory)
• Code errors
• Opening an unavailable file
Types of Java Exceptions
There are three types of exceptions namely:
1. Checked Exception
2. Unchecked Exception
3. Error

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

Java Exception Keywords


Java provides five keywords that are used to handle the exception. The following table describes each.

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{}

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 70 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

Java catch block


 Java catch block is used to handle the Exception by declaring the type of
exception within the parameter.
 The declared exception must be the parent class exception ( i.e., Exception) or the
generated exception type.

PROGRAM TRY-CATCH STATEMENT TO HANDLE THE EXCEPTION


public class JavaExceptionExample{
public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){[Link](e);}
//rest code of the program
[Link]("rest of the code...");
}
}

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 71 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

Multi-catch block Java finally block


 A try block can be followed by one or  Java finally block is always
more catch blocks. executed whether an exception is
 Each catch block must contain a handled or not.
different exception handler.  Java finally block is a block used to
execute important code such as
closing the connection, etc.
class MultipleCatchBlock5{ class Main{
public static void main(String args[]){ public static void main(String args[]){
try{ try{
int a[]=new int[5]; [Link](40/0);
a[5]=30/0; }
} catch(Exception e){
catch(Exception e){ [Link](e);
[Link]("commontaskcompleted"); }
} Finally
catch(ArithmeticException e){ {
[Link]("task1 is completed"); [Link](“finally executed);
} }
catch(ArrayIndexOutOfBoundsException e) [Link]("end...");
{ } }
[Link]("task 2 completed");}
[Link]("rest of the code...");
} }

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 72 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

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.

public class JavaTester{ public class JavaTester{


public void checkAge(int age){ public int division(int a, int b) throws
if(age<18) ArithmeticException
throw new ArithmeticException("Not Eligible {
for voting"); int t = a/b;
else return t;
[Link]("Eligible for voting"); }
}
public static void main(String args[]) public static void main(String args[]){
{ try{
checkAge(13); [Link](division(15,0));
[Link]("End Of Program"); }
}} catch(ArithmeticException e){
[Link]("You shouldn't divide
number by zero");
} } }

ACTIVITY: WRITE A PROGRAM TO DEMONSTRATE CUSTOM EXCEPTION

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 73 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

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

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 74 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

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; }}

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 75 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

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.

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 76 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

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.

5) Connection-oriented and connection-less protocol


In connection-oriented protocol, acknowledgement is sent by the receiver. So it is reliable but
slow. The example of connection-oriented protocol is TCP

[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.

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 77 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

JAVA QUESTION BANK


PART A

1. Java is platform independent. Justify.


2. Write any two characteristics of java.
3. What do you mean by command line argument?
4. What is instance variable? Give example.
5. What are the different types of access modifiers in java?
6. What is java API?
7. What is meant by check and uncheck exception in java?
8. How java applets are different from java application?
9. What are static variable. Illustrate the use of this and super keyboard.
10. Mention any two mathematical functions of math class.
11. What are default and parameterize constructor?
12. How to create an instance of class in java?
13. What is an applet?
14. What is [Link] and [Link]?
15. Give the general form of switch statement.
16. Mention any four thread method.
17. Write the default value of float and character primitive data type?
18. What is the use of [Link] classes?
19. What is byte code?
20. Define a package and mention its uses.

PART B

1. Explain the features of java.


2. Explain visibility control in java.
3. Define Inheritance. Explain its types supported by java.
4. Explain the cycle of thread with a neat diagram.
5. Explain any 7 methods of graph, class with an example.
6. Explain the use of 5 input string class and 5 output string class.
7. Explain different data types in java with example.
8. Explain different access specifiers used in java.
9. Explain final variable and final method and classes with example.
10. Illustrate and explain difference method overloading and method overriding.
11. Explain the methods of string classes with example.
12. Write a note on exception handling.
13. What is thread? Explain various ways of creating thread in java with example.

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 78 of 79


KRUPANIDHI DEGREE COLLEGE OBJECT ORIENTED CONCEPTS USING JAVA

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.

BCA DEPARTMENT 2nd SEM ~Mr. SAYED FAIZAL Page 79 of 79

You might also like