0% found this document useful (0 votes)
327 views

Unit-1 Java (Nep)

The document discusses the syllabus for an Object Oriented Programming course using Java. The syllabus covers 3 units: introduction to Java basics, inheritance and polymorphism, and event and GUI programming. It also includes an introduction to Java that defines Java, its platform, editions, and types of applications. The introduction explains object oriented programming concepts like objects, classes, encapsulation, inheritance, polymorphism, and dynamic binding.

Uploaded by

Sharath Kumar MS
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)
327 views

Unit-1 Java (Nep)

The document discusses the syllabus for an Object Oriented Programming course using Java. The syllabus covers 3 units: introduction to Java basics, inheritance and polymorphism, and event and GUI programming. It also includes an introduction to Java that defines Java, its platform, editions, and types of applications. The introduction explains object oriented programming concepts like objects, classes, encapsulation, inheritance, polymorphism, and dynamic binding.

Uploaded by

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

OBJECT ORIENTED PROGRAMMMING WITH JAVA

OBJECT ORIENTED PROGRAMMING


USING JAVA

nd
BCA 2 semester(NEP)

Dr VIKRAM B Page 1
OBJECT ORIENTED PROGRAMMMING WITH JAVA

SYLLABUS

Unit - 1
Introduction to Java: Basics of Java programming. Data types, Variables, Operators, Control
structures including selection, Looping, Java methods, Overloading, Math class, Arrays in java.

Objects and Classes: Basics of objects and classes in java, Constructors, Finalizer, Visibility
modifiers, Methods and objects, Inbuilt classes like String, Character, String Buffer, File, this
reference.
Unit-2
Inheritance and Polymorphism: Inheritance in java, Super and sub class, Overriding, Object
class, Polymorphism, Dynamic binding, Generic programming, Casting objects, Instance of operator,
Abstract class, Interface in java, Package in java, UTIL package.

Multithreading in java: Thread life cycle and methods, Runnable interface, Thread
synchronization, Exception handling with try catch-finally, Collections in java, Introduction to
JavaBeans and Network Programming.
Unit - 3
Event and GUI programming: Event handling in java, Event types, Mouse and key events,
GUI Basics, Panels, Frames, Layout Managers: Flow Layout, Border Layout, Grid Layout, GUI
components like Buttons, Check Boxes, Radio Buttons,
Labels, Text Fields, Text Areas, Combo Boxes, Lists, Scroll Bars, Sliders, Windows, Menus, Dialog
Box, Applet and its life cycle, Introduction to swing. Exceptional handling mechanism.

I/O programming: Text and Binary I/O, Binary I/O classes, Object I/O, Random Access Files.

Dr VIKRAM B 1ST BCA Page 2


OBJECT ORIENTED PROGRAMMMING WITH JAVA

INTRODUCTION TO JAVA

BASICS OF JAVA PROGRAMMING

What is Java?
Java is a high-level, general-purpose, object-oriented, and secure
programming language developed by James Gosling at Sun Microsystems, James Gosling is
known as the father of Java. Before Java, its name was Oak. Since Oak was already a
registered company, so James Gosling and his team changed the name from Oak to Java.

Platform: Any hardware or software environment in which a program runs, is known as a


platform. Since Java has a runtime environment (JRE) and API, it is called a platform.

Editions of Java

Each edition of Java has different capabilities. There are three editions of Java:
Java Standard Editions (JSE): It is used to create programs for a desktop
computer.
Java Enterprise Edition (JEE): It is used to create large programs that run on the
server and manages heavy traffic and complex transactions.
Java Micro Edition (JME): It is used to develop applications for small devices
such as set-top boxes, phone, and appliances.

Types of Java Applications


There are four types of Java applications that can be created using Java programming:

Standalone Applications: Java standalone applications uses GUI components such as


AWT, Swing, and JavaFX. These components contain buttons, list, menu, scroll panel, etc.
It is also known as desktop alienations.

Enterprise Applications: An application which is distributed in nature is called enterprise


applications.

Web Applications: An applications that run on the server is called web applications. We
use JSP, Servlet, Spring, and Hibernate technologies for creating web applications.

Mobile Applications: Java ME is a cross-platform to develop mobile applications which


run across smartphones. Java is a platform for App Development in Android.

BASIC CONCEPT OF OBJECT-ORIENTED PROGRAMMING


 Objects
 Classes
 Data abstraction and encapsulation
 Inheritance
 Polymorphism
 Dynamic binding

Dr VIKRAM B 1ST BCA Page 3


OBJECT ORIENTED PROGRAMMMING WITH JAVA

 Message communication
Objects: It is an instance of a class. It can also be defined as basic run-
time entities in an object-oriented system. They may represent a person, a
place, a bank account, a table of data or any item that the program has to
handle.

When an program is executed, the objects interact by sending


messages to one another. Each object contains data, and code to manipulate
the data. Objects can interact without having to know details of each
other’s data or code.

Classes: It is a user-defined data –type which consists of both data


members and member functions. The entire set of data and code of an
object can be made a user-defined data-type with the help of a class.
Objects are variables of the type class. Once a class has been defined,
we can create any number of objects belonging to that class. Each object is
associated with the data of type class with which they are created. A class
is thus a collection of objects of similar type.

Data Abstraction and Encapsulation: The wrapping of data and


functions into a single unit (called class) is known as encapsulation. Data
encapsulation is the most striking feature of a class. The data is not
accessible to the outside world, and only those functions which are
wrapped in the class can access it. These functions provide the interface
between the objects data and the program. This insulation of the data from
direct access by the program is called data hiding or information hiding.

Abstraction refers to the act of representing essential features


without including the background details or explanations .Classes use the
concept of abstraction and are defined as a list of abstract attributes and
functions to operate on these attributes. They encapsulate all the essential
properties of the objects that are to be created. The attributes are sometimes
called data members because they hold information. The functions that
operate on these data are sometimes called methods or member functions.
Since the classes use the concept of data abstraction, they are known as
Abstract Data Types(ADT).

Inheritance: It can be defined as “creating / deriving a new class from an


existing class”. Inheritance is the process by which objects of one class
acquire the properties of objects of another class.

In OOP, the concept of inheritance provides the idea of reusability.


This means that we can add additional features to an existing class without
modifying it. This is possible by deriving a new class from the existing
one. The new class will have the combined feature of both the classes

Polymorphism: (Greek word. poly means many, morphism means different forms of
representation)
It is another important OOP concept. Polymorphism, a Greek term, means the ability

Dr VIKRAM B 1ST BCA Page 4


OBJECT ORIENTED PROGRAMMMING WITH JAVA

to take more than one form. The process of making an operator to exhibit different behaviour in
different instances is known as operator overloading. Using a single function name to perform
different types of tasks is known as function overloading.

Dynamic binding: Binding refers to the linking of a procedure call to the code to be executed in
response to the call. Dynamic binding also known as latebinding means that the code associated
with a given procedure call is not known until the time of the call at run-time.

Message communication: An object – oriented program consists of a set


of objects that communicate with each other. The process of programming
in an object-oriented language therefore involves the following basic steps:
1. Creating classes that define objects and their behaviour.
2. Creating objects from class definitions and
3. Establishing communication among object

JAVA FEATURES:

1. Compiled and Interpreted


2. Platform–independent and Portable
3. Object–oriented
4. Robust and Secure
5. Distributed
6. Familiar, Simple and Small
7. Multithreaded and Interactive
8. High Performance
9. Dynamic and Extensible

1. Compiled and Interpreted: Java combines both these approaches thus


making Java a two–stage system.
FirststageJava Compiler translates sourcecode into what is known as bytecode
instructions
(Bytecodes are not machine instructions)
Secondstage Java Interpreter generates machine code that can bedirectly executed by the machine that is running the
Java program

Java compiler converts Source code( into Byte

.java) code(.class)

Java Interpreter Generates machine code


2. Platform –Independent and Portable: The most significant contribution
of Java over other languages is its portability. Java programs can be easily
moved from one computer system to another, any where and anytime.
Changes and upgrades in operating systems, processors and system
resources will not force any changes in Java programs.
Java ensures portability in two ways. First, Java compiler
generates bytecode instructions that can be implemented on any
machine. Secondly, the size of the primitive data types are
machine–independent.

Dr VIKRAM B 1ST BCA Page 5


OBJECT ORIENTED PROGRAMMMING WITH JAVA

3. Object – oriented: Java is a true object-oriented language. Almost


everything in Java is an object. All program code and data reside within
objects and classes. Java comes with an extensive set of classes, arranged
in packages, that we can use in our programs by inheritance.

4. Robust and Secure: Java is a robust language. It provides many


safeguards to ensure reliable code. It has strict compile time and run time
checking for data types. It is designed as a garbage – collected language
relieving the programmers virtually all memory management problems.
Java also in corporate the concept of exception handling which captures
series of errors and eliminates any risk of crashing the system.
Security becomes an important issue for a language that is used for programming on
Internet. Threat of viruses and abuse of resources is everywhere. Java systems not only
verify all memory access but also ensure that no viruses are communicated with an applet.
The absence of pointers in java ensures that programs cannot gain access to memory
locations without proper authorization.
1. Distributed: Java is designed as a distributed language for creating
applications on networks. It has the ability to share both data and
programs. Java applications can open and access remote objects on Internet
(RMI – Remote Method Invocation) as easily as they can do in a local
system. This enables multiple programmers at multiple remote locations to
collaborate and work together on a single project.
2. Simple, Small and Familiar: Java is a small and simple language. Many
features of C &C++that are either redundant or sources of unreliable code
are not part of Java.
Familiarity is another striking feature of Java. To make the
language look familiar to the existing programmers, it was
modelled on C & C++ languages. Java uses many constructs of C
& C++ and therefore, Java code “looks like a C++”code. In fact,
Java is a simplified version of C++.
3. Multithreaded and Interactive :Multithreaded means handling multiple
tasks simultaneously. Java supports multithreaded programs. This means
that we need not wait for the application to finish one task before beginning
another. This feature greatly improves the interactive performance of
graphical applications.

4. High-performance: Java performance is impressive for an interpreted


language, mainly due to the use of intermediate bytecode. Java speed is
comparable to the native C / C++. The incorporation of multithreading
enhances the overall execution speed of Java programs.

Dr VIKRAM B 1ST BCA Page 6


OBJECT ORIENTED PROGRAMMMING WITH JAVA
5. Dynamic and Extensible: Java is a dynamic language. Java is capable of
dynamically linking in new class libraries, methods and objects. Java can also
Determine the type of class through a query, making it possible to either
dynamically link or abort the program, depending on the response.
Java programs support functions written in other languages such as
C and C++. These functions are known as native methods. This
facility enables the programmers to use the efficient functions
available in these languages. Native methods are linked
dynamically at runtime.
Functions written in other languages are called native methods.

Hardware and software requirements

Java is currently supported on Windows95, NT, SunSolaris,


Macintosh& UNIX machines. The minimum hardware and software
requirements are
 Pentium system
 Minimum16 MB memory
 Windows 98 and above OS
 A hard drive
 ACD– ROM / Writer
 A mouse

Java environment

Java environment includes a large number of development tools


and hundreds of classes and methods. The development tools are part of
the system known as Java Development Kit (JDK) and the classes and
methods are part of the Java Standard Library(JSL)also called as
Application Programming Interface(API).

Java Development Kit(JDK):

The JDK comes with a collection of tools that are used for developing
and running Java programs. They include:
 Appletviewer (for viewing Java applets)
 javac(Java compiler)

 java(Java interpreter)
 javap(Java disassemble)
 javah(for C headerfiles)
 javadoc(for creating HTML documents)
 jdb(Java debugger)

Dr VIKRAM B 1ST BCA Page 7


OBJECT ORIENTED PROGRAMMMING WITH JAVA

Java Development Tools

Sl.no Tool Description


01 Appletviewer Enables us to run Java applets
02 Java Java interpreter ,which runs applets and applications by
reading and interpreting bytecode files

03 Javac The java compiler, which translates Java sourcecode to


bytecode files that the interpreter can understand
04 Javadoc Creates HTML format documentation from Java sourcecode
files
05 Javah Produces header files for use with native methods

06 Javap Javadisassemble,whichenablesustoconvertbytecodefilesintoap
rogram description
07 Jdb Java debugger, which helps us to find errors in our programs

OVERVIEW OF JAVA LANGUAGE


INTRODUCTION
Java is a general–purpose, object–oriented programming
language. We can develop two types of Java programs:
a) Stand–alone applications
b) Web applets

Stand – alone applications are programs written in Java to carry out certain tasks
on a stand –alone local computer. HotJava itself is a Java application program.
Executing a stand-alone Java program involves two steps:
1. Compiling source code into bytecode using javac compiler

2. Executing the bytecode program using java interpreter

Applets are small Java programs developed for Internet applications. An applet
located on a distant computer (Server) can be downloaded via Internet and
executed on a local computer(Client)using a Java– capable browser.
SIMPLE JAVA PROGRAM

Class sample

public static void main(String args[])

System.out.println(“Java is an object oriented programming language”);


}
}

Dr VIKRAM B 1ST BCA Page 8


OBJECT ORIENTED PROGRAMMMING WITH JAVA
Class Declaration:

The first line class sample declares a class, which is an object-oriented construct.
sample is a Java identifier that specifies the name of the class to be defined.
Opening Brace:

Every class definition in Java begins with an opening brace { and end with a
matching closing brace }
The main Line:

The third line public static void main(String args[]) defines a method named
main. Conceptually, this is similar to the main() function in C / C++. Every Java
application program must include the main() method. This is the starting point for
the interpreter to begin the execution of the program. A Java application can have
any number of classes but only one of them must include a main method to initiate
the execution.
All parameters to a method are declared inside a pair of
parentheses. Here, String args[] declares a parameter named args, which contains
an array of objects of the class type String.
The output Line: The only executable statement in the program is

System.out.println(“Java is an object oriented programming language”);

This is similar to the printf() statement of C or cout<< construct of C++. The


println always appends a newline character to the end of the string.
IMPLEMENTINGAJAVAPROGRAM

Implementation of a Java application program involves a series of steps. They include

 Creating the program: We can create a program using any text editor.
We must save the program using filename.java extension ensuring that the
filename contains the class name properly. This file is called source file.
Note that, all Java source files will have the extension java. Further, If a
program contains multiple classes, then filename must be the class name
of the class containing the main method.
 Compiling the program: To compile the program, we must run the Java Compiler
javac, with the name of the source file on the command line

javac filename.java

After successful compilation the javac compiler creates a file called


filename.class containing the bytecode of the program. The compiler
automatically names the bytecode file as filename.class.
 Running the program: We need to use the Java Interpreter to run a stand-
alone program.At the command prompt type: java filename

Dr VIKRAM B 1ST BCA Page 9


OBJECT ORIENTED PROGRAMMMING WITH JAVA
Important:

Sourcecode filename.java(program written by the programmer)

Bytecodefilename.class(itwillbeautomaticallycreatedwhenwecompiletheJavapr
ogram)
JavaCompilerit converts source code into bytecode.

JavaInterpreterit translates bytecode into machine code.

JAVA VIRTUAL MACHINE (JVM)

All language compiler translates source code into machinecode for a


specific computer .Java compiler also does the samething .Java compiler produces
an inter media code known as bytecode for a machine that does not exist. This
machine is called the Java Virtual Machine (JVM)and it exists only inside the
computer memory.It is simulated computer within the computer and does all major
functions of a real computer.

Java program Java compiler Virtual Machine

Sourcecode Bytecode
The virtual machine code is not machine specific. The machine specific
code (known as machine code) is generated by the Java interpreter by acting as an
intermediatry between the virtual machine and the real machine. Interpreter is
different for different machines.

Bytecode Java Interpreter Machine code

VirtualMachine RealMachine

JAVA PROGRAM STRUCTURE

A Java program may contain many classes of which only one class
defines a main method. Classes contain data members and methods that
operate on the data members of the class. Methods may contain data type
declarations and executable statements. To write a Java program, we first
define classes and then put them together.

Dr VIKRAM B 1ST BCA Page 10


OBJECT ORIENTED PROGRAMMMING WITH JAVA

Documentation Section: The documentation section comprises a set of comment


lines giving the name of the program, the author and other details, which the programmer
would like to refer to at a later stage. In addition to the two styles of comments Java also
uses a third style of comment
/** .... */ known as documentation comment. This form of comment is used for
generating documentation automatically.

Package Statement: The first statement allowed in a Java file is a package


statement. This statement declares a package name and informs the compiler that
the classes defined here belong to this package.
Import Statements: The next thing after a package statement may be a number
of import statements. This is similar to the # include statement in C.
Eg: import student. test;

This statement instructs the interpreter to load the text class contained in the
package student. Using import statements ,we can have access to classes that are
part of other named packages.
Interface Statements: An interface is like a class but includes a group of method
declarations. This is also an optional section and is used only when we wish to
implement the multiple inheritance feature in the program.
Class Definitions: A Java program may contain multiple class definitions. Classes
are the primary and essential elements of a Java program. These classes are used
to map the objects of real-world problems. The number of classes used depends
on the complexity of the problem.

Dr VIKRAM B 1ST BCA Page 11


OBJECT ORIENTED PROGRAMMMING WITH JAVA
Main Method Class: Since every Java stand-alone program requires a main method as
its starting point, this class is the essential part of a Java program. A simple Java program
may contain only this part. The main method creates objects of various classes and
establishes communications between them.

JAVA TOKENS:

Smallest individual units / element in a program are known as tokens.Thereare fivetypes


of tokens in Java.
Java tokens

Keywords Identifiers Literals Operators Separators

1. Keywords:Keywordsareanessentialpartofalanguagedefinition.Javalangua
gehasreserved60wordsaskeywords.Someofthemare:case,private,public,pr
otected,static,super, throw, break, switch, do, final, class, finally etc.,
Keywords have specific meaning in Java, we cannot use them as
names for variables, classes, methods and so on. All keywords are
to be written in lower-case letters. Java is case-sensitive.
2. Identifiers: Identifiers are programmer-designed tokens. They are used for
naming classes, methods, variables, objects, labels, packages and
interfaces in a program. Java identifiers follow the following rules:
a) They can have alphabets, digits and the underscore.
b) They must not begin with a digit.
c) Uppercase and lowercase are distinct.
d) They can be of any length.

3. Literals:LiteralsinJavaareasequenceofcharacters(digits,letterandotherchar
acters) that represent constant values to be stored in variables. Java
language specifies five types of literals namely:
a) Integer literals
b) Floating-point literals
c) Character literals
d) String literals
e) Boolean literals
4. Operators: An operator is a symbol that takes one or more arguments and
operates on them to produce a result.
5. Separators: Separators are symbols used to indicate where groups of code
are divided and arranged. They basically define the shape and function of
our code. Some of these operators are : ( ) { } [] , ; .

Dr VIKRAM B 1ST BCA Page 12


OBJECT ORIENTED PROGRAMMMING WITH JAVA

VARIABLES AND DATATYPES

VARIABLES:
A variable is an identifier that denotes a storage location used to store a
data value. A variable may take different values at different times during the
execution of the program. A variable name can be chosen by the programmer in a
meaningful way so as to reflect what it represents in the program.
Eg: average, height, total_ height, class Strength

Variable names may consist of alphabets ,digits ,the under score and dollar characters.

Rules for naming a variable:


They must not begin with a digit.

Uppercaseandlowercasearedistinct.ThismeansthatthevariableTotalisnotth
esameas total or TOTAL.
 It should not be a keyword.
 White space is not allowed.
 Variable names can be of any length.
DATATYPES:

Data types specify the size and type of values that can be stored. Java
language is rich in its data types. The variety of data types available allow the
programmer to select the type appropriate to the needs of the application. Data
types in Java are:
a. Primitive types(also called intrinsic or built-in types)
b. Derived types(also known as reference types)

1. Integer Types :Integer type can hold whole numbers such as 123, -96 and
5639. The size of the values that can be stored depends on the integer data
type we choose. Java supports 4 types of integers namely byte, short, int
and long. Java does not support the concept of unsigned types and
therefore all Java values are signed meaning they can be positive or
negative.

Dr VIKRAM B 1ST BCA Page 13


OBJECT ORIENTED PROGRAMMMING WITH JAVA

Size and range of Integer types

Type Size
Byte 1byte
short 2bytes
int 4bytes
long 8bytes

Integer

Byte Short Int Long

2. Floating point types: Integer types can hold only whole numbers and
therefore we use another type known as floating point type to hold numbers
containing fractional parts such as 27.59, -1.375 (known as floating point
constants). There are two kinds of floating point storage in Java.The float
type values are single-precision numbers while the double types represent
double precision

Floating point

float double

Size and range of Floating point types

Type Size

float 4bytes

double 8bytes

1. Character type: In order to store character constants in memory, Java


provides a character data type called char. The char type assumes a size of
2 bytes but, basically it can hold only a single character.
2. Boolean type: Boolean type is used when we want to test a particular
condition during the execution of the program. There are only two values
that a Boolean type can take: true or false. Both these words have been
declared as keywords. Boolean type is denoted by the keyword Boolean
and uses only one bit of storage.

Dr VIKRAM B 1ST BCA Page 14


OBJECT ORIENTED PROGRAMMMING WITH JAVA
OPERATORS
OPERATORS IN JAVA
Operators in java

Arithmetic Relational Logical Assignment Inc.&Dec Conditional Bitwise Special

Integer Real Mixed– mode

1. ARITHMATIC OPERATORS: An operator which allows the user to


perform basic arithmetic operation.
a. + (addition)
b. – (subtraction)
c. * (multiplication)

d. / (division)
e. % (modulus)
A. Integer Arithmetic: When both the operands in a single arithmetic
expression such as a + b are integers, the expression is called an integer
expression and the operation is called integer arithmetic. Integer
arithmetic always yields an integer value.
a-b=10
a+b=18
a*b=51
a / b=3(decimal part truncated)
a%b=2(remainder of integer division)
B. Real Arithmetic: An arithmetic operation involving only real
operands is called real arithmetic. A real operand may assume values
either in decimal or exponential notation.
C. Mixed – mode Arithmetic: When one of the operands is real and the
other is integer, the expression is called a mixed – mode arithmetic
expression. If either operand is of the real type, then the other operand
is converted to real and the real arithmetic is performed.The result will
be a real.
Eg:15/ 10.0 produces the result 1.5

15/ 10 produces the result 1

Dr VIKRAM B 1ST BCA Page 15


OBJECT ORIENTED PROGRAMMMING WITH JAVA

2. RELATIONALOPERATORS:
Relational operators are used to compare two quantities.

Operator Meaning
< Is less than
<= Is less than or equal to
> Isgreaterthan
>= Is greater than or equal to
== Is equal to
!= Is not equal to

3. LOGICALOPERATORS:

Operator Meaning
&& logical AND

|| logical OR

! logical NOT

1. ASSIGNMENT OPERATORS:

Assignment operators are used to assign the value of an expression


to a variable. Normally we use = symbol for assignment, in addition
to that java supports shorthand assignment operator.
v op =exp;
where v is a variable,exp is an expression and op is a Java binary
operator.The operator op =is known as the shorthand assignment
operator.
V op = exp; is equivalent to v =v op (exp);
E.g.: x+=y+1 is same as x=x+(y+1);
Advantages:

 What appears on the left hand side need not be repeated and therefore it
becomes easier to write.
 The statement is more concise and easier to read.
 Use of shorthand operator results in a more efficient code.
2. INCREMENTANDDECREMENTOPERATORS:
Java supports increment and decrement operators namely++ and- -

The operator ++ adds 1 to the operand while --subtracts1. Both are unary
operators and are used in the following form:
++m; or m++;

-- m or m --;

Dr VIKRAM B 1ST BCA Page 16


OBJECT ORIENTED PROGRAMMMING WITH JAVA
3. CONDITIONALOPERATORS:

The character pair?: is a ternary operator available in Java.This


operator issued to construct conditional expressions of the form:
exp1?exp2 :exp3
where exp1,exp2 and exp3 are expressions.
Working of ?:
exp1 is evaluated first.If it is nonzero (true),then the expression exp2 is
evaluated and becomes the value of the conditional expression.If exp1 is false,
exp3 is evaluated and its value becomes the value of the conditional expression.
Note that only one of the expressions (either exp2 orexp3) is evaluated.
x=( a>b )?a: b;
In the above example ,x will be assigned the value of b.This can be achieved
using the if..else statement as follows:
4. BITWISE OPERATORS:
Java has a distinction of supporting special operators known as
bitwise operators for manipulation of data at values of bit level. These operators are used
for testing the bits or shifting them to the right or left. Bitwise operators may not be
applied to float or double.
Operato Meaning
r
& Bitwise AND
! Bitwise OR
^ Bitwise exclusive
OR
~ One’s complement
<< Shift left
>> Shift right
>>> Shift right with
zero fill

5. SPECIALOPERATORS:
Java supports some special operators:
a. Instanceof
b. Member selection operator(.)
InstanceofOperator:
The instanceof is an object reference operator and returns true if the object
on the left-hand side is an instance of the class given on the right-hand side. This operator
allows us to determine whether the object belongs to a particular class or not.
E.g.: person instance of student
Is true if the object person belongs to the class student; otherwise it is false.
Dot operator:
The dot operator(.) is used to access the instance variables and methods of class
objects.
E.g.: person1.age // reference to the variable age person1.salary() //reference to the
method salary()
It is also used to access classes and sub-packages from a package.

Dr VIKRAM B 1ST BCA Page 23


OBJECT ORIENTED PROGRAMMMING WITH JAVA
CONTROL STRUCTURES INCLUDING SELECTION

There are three kinds of control structures:


Conditional Branches, which we use for choosing between two or more paths. There are
three types in Java: if/else/else if, ternary operator and switch

Selection statements are a program control structure in Java. As the name suggests, they are
used to select an execution path if a certain condition is met. There are three selection statements in
Java: if, if..else, and switch.

When a program breaks the sequential flow and jumps to another part of
the code, it is called branching. When the branching is based on a particular
condition, it is known as conditional branching.If branching takes place without
any decision,it is known as unconditional branching.
Java language possesses such decision making capabilities and supports
the following statements known as control or decision making statements.
1. If statement

2. Switch statement

3. Conditional operator statement

DECISION MAKINGWITHIFSTATMENT
if statement is a powerful decision making statement and is used to
control the flow of execution of statements .It is basically a two–way decision statement
and is used in conjunction with an expression.
If(test expression)

It allows the computer to evaluate the expression first and then, depending on whether
the value of the expression (relation or condition) is „true‟ or „false‟ it transfers the
control to a particular statement. This point of program has two paths to follow, one for
the true condition and the other for the false condition.

Entry

Test
expression

False

True

Two –way branching

Dr VIKRAM B 1ST BCA Page 24


OBJECT ORIENTED PROGRAMMMING WITH JAVA
Types of if statement:

1. Simple if statement

2. If...else statement

3. Nested if ... else statement

4. Elseifladder
SIMPLE IF STATMENT

The general form of a simple if statement is:

if(test expression)

Statement-block;

Statement x;

The statement block may be a single statement or a group of statements. if


the test expression is true, the statement-block will be executed; otherwise
the statement-block will be skipped and the execution will jump to the
statement-x.

Java program to illustrate If statement


class IfDemo
{
public static void main(String args[])
{
int i = 10;

if (i > 15)
System.out.println("10 is less than 15");
// This statement will be executed
// as if considers one statement by default
System.out.println("I am Not in if");
}
}

Output:
I am Not in if

Dr VIKRAM B 1ST BCA Page 25


OBJECT ORIENTED PROGRAMMMING WITH JAVA
Entry

Test
expressio True

Statement block

Fals

Statement x

Next statement

THE IF...ELSE STATEMENT


The if....else statement is an extension of the simple if statement.
if(test expression)
{

True block statement(s)

Else

False block statement(s)

}
Statement x;

If the test expression is true, then the true-block statement (s) immediately
following the if statement, are executed; otherwise, the false -block statement (s)
are executed. In either case, either true– block or false – block will be executed,
not both.

Dr VIKRAM B 1ST BCA Page 26


OBJECT ORIENTED PROGRAMMMING WITH JAVA
Entry

Test
True expression False
?

True block statements False block statements

Statement x

Java program to illustrate if-else statement


class IfElseDemo
{
public static void main(String args[])
{
int i = 10;
if (i < 15)
System.out.println("i is smaller than 15");
else
System.out.println("i is greater than 15");
}
}
Output:
i is smaller than 15

NESTING O IF ELSE STATEMENTS

When a series of decisions are involved,we may have to use more than one if…else
statement in nested form

Dr VIKRAM B 1ST BCA Page 27


OBJECT ORIENTED PROGRAMMMING WITH JAVA

if the condition1 is false, the statement3 will be executed;otherwise it


continues to perform the second test. If the condition 2 is true, the statement 1 will be
evaluated; otherwise the statement 2 will be evaluated and then the control is
transferred to the statement x.
Java program to illustrate nested-if statement
class NestedIfDemo
{
public static void main(String args[])
{
int i = 10;

if (i == 10)

Dr VIKRAM B 1ST BCA Page 28


OBJECT ORIENTED PROGRAMMMING WITH JAVA
{
// First if statement
if (i < 15)
System.out.println("i is smaller than 15");
// Nested - if statement
// Will only be executed if statement above
// it is true
if (i < 12)
System.out.println("i is smaller than 12 too");
else
System.out.println("i is greater than 15");
}
}
}
Output:
i is smaller than 15
i is smaller than 12 too

THE ELSE IF LADDER

There is another way of putting ifs together when multipath decisions are
involved. A multipath decision is a chain of ifs in which the statement associated
with each else is an if.

This construct is known as the elseif ladder. The conditions are evaluated from the top
downwards. As soon as the true condition is found, the statement associated with it is
executed and the control is transferred to the statement x(skipping the rest of the
ladder).When all the n conditions becomes false, then the final else containing the default
– statement will be executed.

Dr VIKRAM B 1ST BCA Page 29


OBJECT ORIENTED PROGRAMMMING WITH JAVA

Java program to illustrate if-else-if ladder


class IfElseDemo
{
public static void main(String args[])
{
int i = 20;
if (i == 10)
System.out.println("i is 10");
else if (i == 15)
System.out.println("i is 15");
else if (i == 20)
System.out.println("i is 20");
else
System.out.println("i is not present");
}
}
Output:
i is 20
THE SWITCHSTATEMENT
Java has a built-in multiway decision statement known as a switch. The
switch statement tests the value of a given variable (or expression) against a list of case
values and when a match is found,a block of statements associated with that case is
executed.
Syntax:
switch (expression)
{
case value1:
statement1;
break;
case value2:
statement2;
break;

Dr VIKRAM B 1ST BCA Page 30


OBJECT ORIENTED PROGRAMMMING WITH JAVA
case valueN:
statementN;
break;
default:
statementDefault;
}
When the switch is executed, the value of the expression is successfully compared against the values
value 1,value 2, If a case is found whose value matches with the value
Of the expression, then the block of statements that follows the case are executed.

The break statement at the end of each block signals the end of a particular
case and causes an exit from the switch statement, transferring the control to the
statement-x following the switch.
The default is an optional case. When present, it will be executed if the value of
the expression does not match with any of the case values. If not present, no action

takes place when all matches fail and the control goes to the statement– x.

Java program to illustrate switch-case


class SwitchCaseDemo
{
public static void main(String args[])
{
int i = 9;
switch (i)

Dr VIKRAM B 1ST BCA Page 31


OBJECT ORIENTED PROGRAMMMING WITH JAVA
{
case 0:
System.out.println("i is zero.");
break;
case 1:
System.out.println("i is one.");
break;
case 2:
System.out.println("i is two.");
break;
default:
System.out.println("i is greater than 2.");
}
}}
Output:
i is greater than 2.
THE ?: OPERATOR:

The Java language has an unusual operator, useful for making two-way
decisions. This operator is a combination of ? and : and takes three operands. This
operator is popularly known as the conditional operator.

conditional expression ? expression1 : expression2

The conditional expression is evaluated first, if the result is true,expression1 is evaluated


and is returned as the value of the conditional expression.Otherwise,expression2 is
evaluated and its value is returned.
Ex:if(x<0)
flag=0;
else
flag=1;
can be written as
flag= (x<0) ? 0 : 1;

Dr VIKRAM B 1ST BCA Page 32


OBJECT ORIENTED PROGRAMMMING WITH JAVA
DECISION MAKING LOOPING:

LOOPING
The process of repeatedly executing a block of statements is known as
looping. The statements in the block may be executed any number of times, from zero to
infinite number.If a loop continues forever, it is called an infinite loop.
A looping process, in general would include the following four steps:

1. Setting and initialization of a counter

2. Execution of the statements in the loop

3. Test for a specified condition for execution of the loop

4. Incrementing the counter.


The Java language provides for three constructs for performing loop operations. They are:

1. The while statement

2. The do statement

3. The for statement

THE WHILE STATEMENT:(Entry–controlled loop)

The simplest of all the looping structures in Java is the while statement.
Initialization;
while(test condition)
{
Body of the loop
}

Working:
Thewhileisanentrycontrolledloopstatement.Thetestconditionisevaluated
andif the condition is true, then the body of the loop is executed. After execution
of the body, the test condition is once again evaluated and if it is true, the body is
executed once again. This process of repeated execution of the body continues
until the test condition finally becomes false and the control is transferred out of
the loop. On exit, the program continues with the statement immediately after the
body of the loop.
while Example program:
public class While Example {
public static void main(String[] args) {
int i=1;
while(i<=3){
System.out.println(i);
i++;
}
}
}

S Dr VIKRAM B 1ST BCA Page 33


OBJECT ORIENTED PROGRAMMMING WITH JAVA
Output
1
2
3
THE DO STATEMENT: (Exit– controlled loop)

do {
//code to be executed / loop body
//update statement
}while (condition);

do statement is a exit controlled loop.

Working:

On reaching the do statement, the program proceeds to evaluate the body


of the loop first. At the end of the loop, the test condition in the while statement is
evaluated. If the condition is true, the program continues to evaluate the body of
the loop once again. This process continues as long as the condition is true. When
the condition becomes false, the loop will terminated and the control goes to the
statement that appears immediately after the while statement.
Since the test condition is evaluated at the bottom of the loop, the do...
while construct provides an exit-controlled loop and therefore the body of the
loop is always executed atleast once.

Do While Example program


public class DoWhileExample {
public static void main(String[] args) {
int i=1;
do{
System.out.println(i);
i++;
}
while(i<=3);
}
Output: }
1
2
3

Dr VIKRAM B 1ST BCA Page 34

S
OBJECT ORIENTED PROGRAMMMING WITH JAVA

THEFORSTATEMENT:(Entry –controlled loop)

for loop is an other entry–controlled loop that provides a more concise


loop control structure.

for(initialization;testcondition; increment)

Body of the loop


The execution of the for statement is as follows:

1. Initialization of the control variables is done first, using assignment


statements such as i =1 and count =0.The variables i and count are known
as loop-control variables.
2. The value of the control variable is tested using the test condition. The test
condition is a relational expression, such as i<10 that determines when the
loop will exit. If the condition is true,the body of the loop is
executed;otherwise the loop is terminated and the execution continues with
the statement that immediately follows the loop.
3. When the body of the loop is executed, the control is transferred back to
the for statement after evaluating the last statement in the loop. Now, the
control variable is incremented using an assignment statement such as i =
i + 1 and the new value of the control variable is again tested to see whether
it satisfies the loop condition. If the condition is satisfied, the body of the
loop is again executed. This process continues till the value of the control
variable fails to satisfy the test condition.

for loop Example

public class ForExample {


public static void main(String[] args) {
//Code of Java for loop
for(int i=1;i<=3;i++)
{
System.out.println(i);
}
}}

Output
1
2
3

S Dr VIKRAM B 1ST BCA Page 35


OBJECT ORIENTED PROGRAMMMING WITH JAVA
For-each Loop
. The Java for-each loop prints the array elements one by one. It holds an array element in a variable, then
executes the body of the loop.

The syntax of the for-each loop is given below:

for(data_type variable: array)


{
//body of the loop
}
Let us see the example of print the elements of Java array using the for-each loop.

//Java Program to print the array elements using for-each loop


class Testarray1
{
public static void main(String args[])
{
int arr[]={33,3,4,5};
//printing array using for-each loop
for(int i:arr)
System.out.println(i);
}}
Output:
33
3
4
5

JAVA METHODS
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.
Why use methods? To reuse code: define the code once, and use it many times.

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 System.out.println(), but you can
also create your own methods to perform certain actions:
Example
Create a method inside Main:
public class Main {
static void myMethod () {
// code to be executed

}
}

S Dr VIKRAM B 1ST BCA Page 36


OBJECT ORIENTED PROGRAMMMING WITH JAVA
Example Explained
myMethod() is the name of the method
static means that the method belongs to the Main class and not an object of the Main class.
void means that this method does not have a return value

Call a Method
To call a method in Java, write the method's name followed by two parentheses () and a semicolon;
In the following example, myMethod() is used to print a text (the action), when it is called:
Example
Inside main, call the myMethod() method:
public class Main
{
static void myMethod()
{
System.out.println("I just got executed!");
}
public static void main(String args[])
{
myMethod();
}
}
Output: I just got executed!

OVERLOADING

METHOD OVERLOADING

If a class has having same name but different in parameters, it is known as Method Overloading.
Advantage of method overloading
Method overloading increases the readability of the program.
Method overloading is used when objects are required to perform similar
tasks but using different input parameters. When we call a method in an object,
Java matches up the method name first and then the number and type of
parameters to decide which one of the definitions to execute. This process is
known as polymorphism.
To create an overloaded method, all we have to do is to provide several
different method definitions in the class, all with the same name, but with different
parameter lists. The difference may either be in the number or type of arguments.
That is, each parameter list should be unique. Note that the methods return type
does not play a role in this.
Different ways to overload the method
There are two ways to overload the method in java
 By changing number of arguments
 By changing the data type
1) Method Overloading: changing no. of arguments

In this example, we have created two methods, first add() method performs addition of two numbers
and second add method performs addition of three numbers. In this example, we are creating static
methods so that we don't need to create instance for calling methods.
S Dr VIKRAM B 1ST BCA Page 37
OBJECT ORIENTED PROGRAMMMING WITH JAVA
class Adder
{
static int add(int a,int b)
{
return a+b;
}
static int add(int a,int b,int c)
{
return a+b+c;
}
}
class TestOverloading1
{
public static void main(String[] args)
{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}
}
Output:
22
33

2) Method Overloading: changing data type of arguments


In this example, we have created two methods that differs in data type. The first add method receives
two integer arguments and second add method receives two double arguments.
class Adder
{
static int add(int a, int b)
{
return a+b;
}
static double add(double a, double b)
{
return a+b;
}
}
class TestOverloading2
{

public static void main(String[] args)


{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
} }
Output:
22
24.9

S Dr VIKRAM B 1ST BCA Page 38


OBJECT ORIENTED PROGRAMMMING WITH JAVA
MATH CLASS
The java.lang.Math class contains methods for performing basic numeric operations such as the
elementary exponential, logarithm, square root, and trigonometric functions
Mathematical functions such as cos, sqrt, log etc are frequently used in analysis of
real – life problems. Java supports these basic math functions through Math class defined
in the java.lang package.
These functions should be used as follows:

Math.function_name()Exampl

e:

double y=Math.sqrt(x);

ARRAYS IN JAVA
An array is a collection of similar type of elements which has contiguous memory location.
Java array is an object which contains elements of a similar data type. Additionally, The
elements of an array are stored in a contiguous memory location. It is a data structure where we store
similar elements. We can store only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd
element is stored on 1st index and so on.
Types of Array in java
There are two types of array.
 Single Dimensional Array
 Multidimensional Array
Single Dimensional Array in Java
Syntax to Declare an Array in Java
1. dataType[ ] arr; (or)
2. dataType arr[ ];
Instantiation of an Array in Java
arrayRefVar=new datatype[size];
Example of Java Array
Let's see the simple example of java array, where we are going to declare, instantiate, initialize and
traverse an array.

//Java Program to illustrate how to declare, instantiate, initialize and traverse the Java array.
class Testarray
{
public static void main(String args[])
{
int a[]=new int[5];//declaration and instantiation
a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0;i<a.length;i++) //length is the property of array
System.out.println(a[i]);
}
}

S Dr VIKRAM B 1ST BCA Page 39


OBJECT ORIENTED PROGRAMMMING WITH JAVA

Output: 70
10 40
20 50
//Java Program to illustrate the use of declaration, instantiation
//and initialization of Java array in a single line
class Testarray1
{
public static void main(String args[])
{
int a[]={33,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}

Multidimensional Array in Java


Data is stored in row and column based index (also known as matrix form).

Syntax to Declare Multidimensional Array in Java

dataType[ ][ ] arrayRefVar; (or)


dataType arrayRefVar[ ][ ]; (or)
dataType [ ]arrayRefVar[ ];

Example to instantiate Multidimensional Array in Java

int[ ][ ] arr=new int[3][3]; //3 row and 3 column

Example to initialize Multidimensional Array in Java

arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;
Example of Multidimensional Java Array
Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array.
//Java Program to illustrate the use of multidimensional array
class Testarray3

{
public static void main(String args[])
{
//declaring and initializing 2D array
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
//printing 2D array
Dr VIKRAM B 1ST BCA Page 40

S
OBJECT ORIENTED PROGRAMMMING WITH JAVA

for(int i=0;i<3;i++)

{
for(int j=0;j<3;j++)
{
System.out.println(arr[i][j]+" ");
}
System.out.println();
}
}}
Output:
123
245
445

Unit-1
Objects and Classes: Basics of objects and classes in java, Constructors, Finalizer, Visibility
modifiers, Methods and objects, Inbuilt classes like String, Character, String Buffer, File, this
reference.

OBJECTS AND CLASSES


Basics of objects and classes in java
DEFININGA CLASS

A class is a user-defined data type with a template that serves to define its
properties.Once the class type has been defined, we can create“variable”of that
type using declarations that are similar to the basic type declarations. In Java, these
variables are termed as instance of classes, which are the actual objects.
The basic form of class declaration is:
Class classname
{
Variable declaration;
Method declaration;
}
ADDING VARIABLES:

Class Rectangle

{
int length;
int width;
}
class Rectangle contains two integer type instance variables. It is allowed to declare them in one line
as
int length,width;

Dr VIKRAM B 1ST BCA Page 41


OBJECT ORIENTED PROGRAMMMING WITH JAVA
ADDING METHODS:
A class with only data fields (and without methods that operate on that
data) has no life. The objects created by such a class cannot respond to any
messages. We must therefore add methods that are necessary for manipulating the
data contained in the class. Methods are declared inside the body of the class but
immediately after the declaration of instance variables.
type methodname(parameterlist)
{
method body;
}
Method declarations have four basic parts:
 The name of the method(method name)
 The type of the value the method returns(type)
 A list of parameters(parameter list)
 The body of the method
The type specifies the type of value the method would return. This could
be a simple data type such as int as well as any class type. It could even be
void type, if the method does not return any value. The method name is a valid
identifier. The parameter list is always enclosed in parentheses. This list
contains variable names and types of all the values we want to give to the
method as input. The variables in the list are separated by commas.
The body actually describes the operations to be performed on the data.
Class Rectangle
{
int length,width;
void getdata(int x, int y)
{
length=x;
width=y;
}
}
Note that the method has a return type of void because it does not return
any value. We pass two integer values to the method which are then assigned
to the instance variables length and width. The getdata method is basically
added to provide values to the instance variables. Notice that we are able to
use directly length and width inside the method
CREATING OBJECTS:
An object in Java is essentially a block of memory that contains space to
store all the instance variables. Creating an object is also referred to as
instantiating an object.
Objects in Java are created using the new operator. The new operator
creates an object of the specified class and returns a reference to that object.
Eg: Rectangle rect1; // declare
rect1=new Rectangle (); //instantiate
the first statement declares a variable to hold the object reference and the second
one actually assigns the object reference to the variable. The variable rect1 is now
an object of the rectangle class.
Both statements can be combined into one as follows:
Rectangle rect1=new Rectangle ();
Dr VIKRAM B 1ST BCA Page 42
OBJECT ORIENTED PROGRAMMMING WITH JAVA
The method rectangle() is
The default constructor of the class. We can create any number of objects of
rectangle.
Eg:
Rectangle rect1=new Rectangle();
Rectangle rect2=new Rectangle();

In the above example both rect1 and rect2 are objects.

It is important to understand that each object has its own copy of the
instance variables of its class. This means that any changes to the variables of one
object have no effect on the variables of another. It is also possible to create two
or more references to the same object.
Eg : Rectangle r1=new Rectangle() ;

Rectangle r2 =r1

Both r1and r2 refer to the same object.

r1

rectangleobject

r2

ACCESSING CLASS MEMBERS:


All variables must be assigned values before they are used. Since we are outside the
class, we cannot access the instance variables and the methods directly. To do this, we must use the
concerned object and the dot operator as shown below:

object name.variable name ;

object name. methodname (parameterlist ) ;

here object name is the name of the object, variable name is the name of the
instance variable inside the object that we wish to access, method name is the
method that we wish to call, and type and number with the parameter list of the
method name declared in the class .The instance variables of the rectangle class
may be accessed and assigned values as follows:
rect1.lenght=15;
rect1.width=25;
rect2.lenght=18;
rect2.width=30;
Dr VIKRAM B 1ST BCA Page 43
OBJECT ORIENTED PROGRAMMMING WITH JAVA
note that the two objects rect1 and rect2 store different values as shown
below:rect1 rect1 rect2
rect1.length rect2.length 18
15

rect1.width rect2.width 30
25

This is one way of assigning values to the variables in the objects. Another way
and more convenient way of assigning values to the instance variables is to use a
method that is declared inside the class.
Rectangle rect1=new Rectangle (); // creating an object

rect1.getdata( 15, 10); //calling the method using the object

this code create rect1 object and then passes in the values 15 and 25 for the x and y
parameters of the method getdata. This method then assigns these values to length and width
variables respectively.

CONSTRUCTORS:
All objects that are created must be given initial values using two
approaches. The first approach uses the dot operator to access the instance
variables and then assigns values to them individually. It can be a tedious
approach to initialize all the variables of all the objects.
The second approach takes the help of a method like get data to initialize

each object individually using statement like:

rect1 .getdata(15,25 ) ;

it would be simpler and more concise to initialize an object when it is first


created. Java supports a special type of method, called a constructor that
enables an object to initialize itself when it is created.
Constructors have the same name as the class itself. Secondly,
they do not specify a return type, not even void. This is because they
return the instance of the class itself.
Types of Java constructors
There are two types of constructors in Java:
 Default constructor (no-arg constructor)
 Parameterized constructor

Parameterized Constructor
A constructor which has a specific number of parameters is called a parameterized
constructor.
The parameterized constructor is used to provide different values to distinct objects.
However, you can provide the same values also
class Rectangle
{
int length, width;
Rectangle (int x, int y) //defining constructor
Dr VIKRAM B 1ST BCA Page 44
OBJECT ORIENTED PROGRAMMMING WITH JAVA
{
length = x;
width = y;
}
int rectArea ( )
{
return (length *width);
}
}
class RectangleArea
{
public static void main (string args[])
{
Rectangle rect1= new Rectangle (15, 10); //calling constructor
int areal = rectl.rectArea( );
System.out.println ("Areal = "+ areal);
}
}
Output
Areal = 150
In parameterized constructor at the time of object instantiation, the constructor is explicitly
invoked by passing arguments.
Default Constructor
A constructor is called "Default Constructor" when it doesn't have any parameter.

The default constructor is used to provide the default values to the object like 0, null, etc.,
depending on the type.
Example of default constructor
class perimeter
{
int length;
int breadth;
perimeter () //default constructor
{
length = 0;
breadth = 0;
}
perimeter (int x, int y) //parameterized constructor
{
length = x;
breadth=y;
}
void cal_perimeter ()
{
int peri;
peri= 2* (length + breadth);
System.out.println("\nThe perimeter of the rectangle is :"+peri);
}
}
class Ex_default_c
{
public static void main(String args[])
Dr VIKRAM B 1ST BCA Page 45
OBJECT ORIENTED PROGRAMMMING WITH JAVA
{
perimeter p1 = new perimeter (); // calling default constructor
perimeter p2= new perimeter (5, 10); // calling parameterized constructor
p1.cal_perimeter();
p2.cal_perimeter ();

Output of Program :
The perimeter of the rectangle is :0
The perimeter of the rectangle is : 30
FINALIZER METHODS:

We have seen that a constructor method is used to initialize an object when it is declared.
This process is known as initialization. Similarly, Java supports a concept called finalization,
which is just opposite to initialization.
We know that Java run-time is an automatic garbage collecting system. It automatically
frees up the memory resources used by the objects. But objects may hold other non-object
resources such as file descriptors or window system fonts. The garbage collector cannot free
these resources. In order to free these resources we must use a finalizer method. This is similar
to destructors in C++.
The finalizer method is simply finalize() and can be added to any class. Java calls that method
whenever it is about to reclaim the space for that object. The finalize method should explicitly
define the tasks to be performed.
The finalize( ) method has this general form:
protected void finalize( )
{
//finalization code here
}
Here, the keyword protected is a specifier that prevents access to finalize( ) by code defined
outside its class. Note that finalize( ) is only called just prior to garbage collection. It is not
called when an object goes out-of-scope.

Finalize() is the method of Object class. This method is called just before an object is
garbage collected. finalize() method overrides to dispose system resources, perform clean-up
activities and minimize memory leaks
VISIBILITY MODIFIERS
The access modifiers in Java specifies the accessibility or scope of a field, method,
constructor, or class. We can change the access level of fields, constructors, methods, and class
by applying the access modifier on it.

There are four types of Java access modifiers:

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
Dr VIKRAM B 1ST BCA Page 46
OBJECT ORIENTED PROGRAMMMING WITH JAVA
the class, outside the class, within the package and outside the package.
Private
The private access modifier is accessible only within the class.
Simple example of private access modifier
In this example, we have created two classes A and Simple. A class contains private data
member and private method. We are accessing these private members from outside the class,
so there is a compile-time error.
class A
{
private int data=40;
private void msg()
{
System.out.println("Hello java");
}
}
public class Simple{
public static void main(String args[])
{
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}}
2) Default
If you don't use any modifier, it is treated as default by default. The default modifier is
accessible only within package. It cannot be accessed from outside the package. It provides
more accessibility than private. But, it is more restrictive than protected, and public.
Example of default access modifier
In this example, we have created two packages pack and mypack. We are accessing the A
class from outside its package, since A class is not public, so it cannot be accessed from
outside the package.
//save by A.java
package pack;
class A
{
void msg()
{
System.out.println("Hello");
} }
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[])
{
A obj = new A(); //Compile Time Error
obj.msg(); //Compile Time Error
}}
3) Protected
The protected access modifier is accessible within package and outside the package but
through inheritance only.
The protected access modifier can be applied on the data member, method and
constructor. It can't be applied on the class. It provides more accessibility than the default

Dr VIKRAM B 1ST BCA Page 47


OBJECT ORIENTED PROGRAMMMING WITH JAVA
modifer.
Example of protected access modifier
In this example, we have created the two packages pack and mypack. The A class of pack
package is public, so can be accessed from outside the package. But msg method of this
package is declared as protected, so it can be accessed from outside the class only through
inheritance.
//save by A.java
package pack;
public class A
{
protected void msg()
{
System.out.println("Hello");
} }
//save by B.java
package mypack;
import pack.*;
class B extends A
{
public static void main(String args[])
{
B obj = new B();
obj.msg();
}}
Output:Hello
4) Public
The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.
Example of public access modifier
//save by A.java
package pack;
public class A{
public void msg()
{
System.out.println("Hello");
} }
//save by B.java
package mypack;
import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}

Dr VIKRAM B 1ST BCA Page 48


OBJECT ORIENTED PROGRAMMMING WITH JAVA
INBUILT CLASSES
STRING CLASS
The java.lang.String class provides a lot of built-in methods that are used to
manipulate string in Java. By the help of these methods, we can perform operations on
String objects such as trimming, concatenating, converting, comparing, replacing strings etc.
some important methods of String class.
Java String toUpperCase() and toLowerCase() method
The Java String toUpperCase() method converts this String into uppercase letter and
String toLowerCase() method into lowercase letter.
public class Stringoperation1
{
public static void main(String args[])
{
String s="Sachin";
System.out.println(s.toUpperCase()); //SACHIN
System.out.println(s.toLowerCase()); //sachin
System.out.println(s); //Sachin(no change in original)
}
}
Output:
SACHIN
sachin
Sachin
Java String trim() method
The String class trim() method eliminates white spaces before and after the String.
Stringoperation2.java
public class Stringoperation2
{
public static void main(String args[])
{
String s=" Sachin ";
System.out.println(s); // Sachin
System.out.println(s.trim()); //Sachin
}
}
output
Sachin
Sachin
Java String charAt() Method
The String class charAt() method returns a character at specified index.
Stringoperation4.java
public class Stringoperation4
{
public static void main(String ar[])
{
String s="Sachin";
System.out.println(s.charAt(0)); //S
System.out.println(s.charAt(3)); //h
}
}
Output
Dr VIKRAM B 1ST BCA Page 49
OBJECT ORIENTED PROGRAMMMING WITH JAVA
S
h
Java String length() Method
The String class length() method returns length of the specified String
public class Stringoperation5
{
public static void main(String args[])
{
String s="Sachin";
System.out.println(s.length());//6
} }
Output
6
Java String valueOf() Method
The String class valueOf() method coverts given type such as int, long, float, double,
boolean, char and char array into String.
Stringoperation7.java
public class Stringoperation7
{
public static void main(String args[])
{
int a=10;
String s=String.valueOf(a);
System.out.println(s+10);
} }
Output
1010

Character class
The Character class generally wraps the value of all the primitive type char into an object. Any
object of the type Character may contain a single field whose type is char.
All the fields, methods, and constructors of the class Character are specified by the Unicode
Data file which is particularly a part of Unicode Character Database and is maintained by the
Unicode Consortium.
Methods
Method Description

charCount(int codePoint) Determines the number of char values which are


required to represent the given character.

charValue() Returns the value of the given Character object.

codePointAt(char[]a, int index) Returns the codePoint for the specified index of
the given array.

codePointAt(char[]a, int index, Returns the codePoint of the char array at the
int limit ) specified index where only the elements of the
array with the index less than the specified limit
being used.

Dr VIKRAM B 1ST BCA Page 50


OBJECT ORIENTED PROGRAMMMING WITH JAVA
codePointAt(CharSequence Returns the codePoint at the specified index for
seq, int index) the given CharSequence.

codePointBefore(char[]a, int Returns the codePoint for the given array in the
index) preceding index.

compare(char x, char y) Compares two character type values numerically.

StringBuffer class
The java.lang.StringBuffer class is a thread-safe, mutable sequence of characters. Following
are the important points about StringBuffer −
 A string buffer is like a String, but can be modified.
 It contains some particular sequence of characters, but the length and content of the
sequence can be changed through certain method calls.
 They are safe for use by multiple threads.
 Every string buffer has a capacity.

Class Declaration
Following is the declaration for java.lang.StringBuffer class −
public final class StringBuffer
extends Object
implements Serializable, CharSequence
Class constructors
Sr.No. Constructor & Description

1 StringBuffer()
This constructs a string buffer with no characters in it and an initial capacity of 16
characters.

2 StringBuffer(CharSequence seq)
This constructs a string buffer that contains the same characters as the specified
CharSequence.

3 StringBuffer(int capacity)
This constructs a string buffer with no characters in it and the specified initial capacity.

4 StringBuffer(String str)
This constructs a string buffer initialized to the contents of the specified string.

Important methods of StringBuffer class


Modifier and Method Description
Type

public append(String s) It is used to append the specified string with


synchronized this string. The append() method is
StringBuffer overloaded like append(char),
append(boolean), append(int),
append(float), append(double) etc.

Dr VIKRAM B 1ST BCA Page 51


OBJECT ORIENTED PROGRAMMMING WITH JAVA
public insert(int offset, It is used to insert the specified string with
synchronized String s) this string at the specified position. The
StringBuffer insert() method is overloaded like insert(int,
char), insert(int, boolean), insert(int, int),
insert(int, float), insert(int, double) etc.

public replace(int It is used to replace the string from specified


synchronized startIndex, int startIndex and endIndex.

StringBuffer endIndex, String


str)

public delete(int It is used to delete the string from specified


synchronized startIndex, int startIndex and endIndex.
StringBuffer endIndex)

public reverse() is used to reverse the string.


synchronized
StringBuffer

public int capacity() It is used to return the current capacity.

Java File Class


The File class is an abstract representation of file and directory pathname. A pathname
can be either absolute or relative.
The File class have several methods for working with directories and files such as creating
new directories or files, deleting and renaming directories or files, listing the contents of a
directory etc.
Fields
Modifier Type Field Description

Static String pathSeparator It is system-dependent path-separator


character, represented as a string for
convenience.

Static char pathSeparatorChar It is system-dependent path-separator


character.

Static String separator It is system-dependent default name-


separator character, represented as a
string for convenience.

Static char separatorChar It is system-dependent default name-


separator character.

Useful Methods
Modifier Method Description
and Type

Dr VIKRAM B 1ST BCA Page 52


OBJECT ORIENTED PROGRAMMMING WITH JAVA
Boolean createNewFile() It atomically creates a new, empty file named by
this abstract pathname if and only if a file with this
name does not yet exist.

Boolean canWrite() It tests whether the application can modify the file
denoted by this abstract pathname.String[]

Boolean canExecute() It tests whether the application can execute the file
denoted by this abstract pathname.

Boolean canRead() It tests whether the application can read the file
denoted by this abstract pathname.

Boolean isAbsolute() It tests whether this abstract pathname is absolute.

Boolean isFile() It tests whether the file denoted by this abstract


pathname is a normal file.

this reference
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)
{
this.age = age;
}
}
There can be a lot of usage of Java this keyword. In Java, this is a reference variable that
refers to the current object.

Usage of Java this keyword


Here is given the 6 usage of java this keyword.
 this can be used to refer current class instance variable.
 this can be used to invoke current class method (implicitly)
 this() can be used to invoke current class constructor.
 this can be passed as an argument in the method call.
 this can be passed as argument in the constructor call.

Dr VIKRAM B 1ST BCA Page 53

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy