Download as pdf or txt
Download as pdf or txt
You are on page 1of 50

Object Oriented Programming with Java 2023-24

UNIT-1

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 in 1991, Java was named as Oak. So James
Gosling and his team changed the name from Oak to Java in 1995.

Editions of Java
There are three editions of Java: Each edition of Java has different capabilities.
 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 can be created using Java programming:
 Standalone Applications: A Java standalone application uses GUI components such as
AWT (Abstract Window Toolkit), Swing, and Java FX. 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 application that runs on the server is called web applications. It
includes JSP, Servlet, Spring, and Hibernate technologies for creating web applications.

 Mobile Applications: Java ME (Java Micro Edition) is a cross-platform to develop mobile


applications which run across smart phones. Java is a platform for App Development in
Android.

Shruthi S, Asst. Professor, Dept. of BCA. Page 1


Object Oriented Programming with Java 2023-24

BASIC CONCEPT OF OBJECT-ORIENTED PROGRAMMING (OOP)


The General concepts of OOP’s are as follows
 Objects
 Classes
 Data abstraction and encapsulation
 Inheritance
 Polymorphism
 Dynamic binding

 Objects: It is an instance of a class. Objects are the 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 a 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. The representation of Object person is as shown
below.

 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, It 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 Encapsulation: The wrapping of data and methods 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.

Shruthi S, Asst. Professor, Dept. of BCA. Page 2


Object Oriented Programming with Java 2023-24

 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 means the ability to take more than one form.
The process of making an operator to exhibit different behavior 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 late binding 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 behavior.
2. Creating objects from class definitions.
3. Establishing communication among objects.

JAVA HISTORY
 Java is a general-purpose, object-oriented programming language developed by James
Gosling from Sun Microsystems of USA in 1991.
 Originally Java was called Oak.

Shruthi S, Asst. Professor, Dept. of BCA. Page 3


Object Oriented Programming with Java 2023-24

Year Development
1990 A team of Sun Microsystems programmers headed by James Gosling was formed.

1991 The team announced a new language named “Oak”.


The team developed a Web browser called “Hot Java” to locate and run applet
1994
programs on Internet.
Oak was renamed “Java”. Many popular companies including Netscape and
1995
Microsoft announced their support to Java.
Java established itself not only as a leader for Internet programming but also as a
1996 general-purpose, object oriented programming language. Sun releases Java
Development Kit 1.0.

1997 Sun releases Java Development Kit 1.1 (JDK 1.1)


Sun releases the Java 2 with version 1.2 of the Software Development Kit
1998
(SDK 1.2)
Sun releases the Java 2 Platform, Standard Edition (J2SE) and Enterprise Edition
1999
(J2EE)
2000 J2SE with SDK 1.3 was released.
2002 J2SE with SDK 1.4 was released.
2004 J2SE with SDK 5.0 (instead of JDK 1.5) was released. This is known as J2SE 5.0

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

Shruthi S, Asst. Professor, Dept. of BCA. Page 4


Object Oriented Programming with Java 2023-24

1. Compiled and Interpreted: Computer Language is either compiled or interpreted. Java


combines both these approaches thus making Java a two stage system. First stage Java
Compiler translates source code into bytecode instruction (Bytecodes are not machine
instructions). Second stage Java Interpreter generates machine code that can be directly
executed by the machine that is running the Java program.
Java compiler converts into source code (.java) into bytecode (.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, anywhere 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 sizes of the primitive data types are
machine independent.

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 garbage
collected language relieving the programmers virtually all memory management problems.
Java also incorporates the concept of exception handling which captures series of errors and
eliminates any risk of crashing the system.
Java systems not only verify all memory access but also ensure that no viruses are
communicated with an applet.

5. 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. This enables multiple programmers at multiple remote locations to
collaborate and work together on a single project.

Shruthi S, Asst. Professor, Dept. of BCA. Page 5


Object Oriented Programming with Java 2023-24

6. Simple, Small and Familiar: Java is a small and simple language. 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++.

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

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

9. 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++.

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) : Enables us to run Java applets (without
actually using a Java-compatible browser).
 javac ( Java Compiler) : The Java compiler, which translates Java source code to
bytecode files that the interpreter can understand.

Shruthi S, Asst. Professor, Dept. of BCA. Page 6


Object Oriented Programming with Java 2023-24

 java( Java Interpreter) : Java interpreter, which runs applets and applications by reading
and interpreting bytecode files.
 javadoc : Creates HTML format documentation from Java source code files.
 javah : Produces header files for use with native methods.
 javap: Java disassemble, which enables to convert bytecode files into a program
description.
 jdb : Java debugger is a tool for Java classes to debug a program in command line

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,
first define classes and then put them together.

Documentation Section: This section comprises a set of comment lines giving the name of the
program, the author and other details
Ex: /* Java Program for biggest of two number …….*/ known as documentation comment.

Package Statements: The first statement allowed in a java file a package statement. This
statement declares a package name and informs the compiler that classes defined here belong to
this package. The package statement is optional.
Ex: package student;

Shruthi S, Asst. Professor, Dept. of BCA. Page 7


Object Oriented Programming with Java 2023-24

Import Statements: The next statement after package statement may be number of import
statements. This is similar to #include statement in c.
Ex: import student.test;
This statement instructs the interpreter to load the class contained in the package Using import
statements, can 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 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.

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.

OVERVIEW OF JAVA LANGUAGE


Java is a general–purpose, object–oriented programming language. It can develop two types of
Java programs:
a) Stand alone applications
b) Web applets
a) 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
standalone Java program involves two steps:
1. Compiling source code into bytecode using javac compiler
2. Executing the bytecode program using java interpreter
b) 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.

Shruthi S, Asst. Professor, Dept. of BCA. Page 8


Object Oriented Programming with Java 2023-24

SIMPLE JAVA PROGRAM


class sample
{
public static void main (String args[])
{
System.out.println (“Java is an object oriented programming language”);
}
}

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. Every Java application program must include the main () method. This is the starting point
for the interpreter to begin the execution of the program. 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.
This line contains a number of keywords, public, static and void.
public: The keyword public is an access specifier that declares the main method as
unprotected and therefore making it accessible to all other classes..
static: static declares main method as one that belongs to the entire class and not a part of any
objects of the class. The main must always be declare as a static since the interpreter uses this
method before any objects are created.
void: The type modifier void states that the main method does not return any value.

The output Line: The only executable statement in the program is


System.out.println(“Java is an object oriented programming language”);
The println always appends a newline character to the end of the string.

Shruthi S, Asst. Professor, Dept. of BCA. Page 9


Object Oriented Programming with Java 2023-24

IMPLEMENTING A JAVA PROGRAM


Implementation of a Java application program involves a series of steps.
They include
1. Creating the program: A program can create using any text editor. Save the program using
filename.java extension ensuring that the filename contains the class name properly. This file
is called source file.
2. 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.
3. Running the program: The Java Interpreter is used to run a standalone program. To run a
command the following commands are used. java filename

JAVA VIRTUAL MACHINE (JVM)

All language compilers translate source code into machine code for a specific computer. Java
compiler produces an inter media code known as bytecode for a machine. The machine is called

Java Java Virtual


Program Compiler Machine

the Java Virtual Machine (JVM) and it exists only inside the computer memory. Below figure
illustrate the process of compiling a java program into bytecode which is also referred to as
virtual machine code.
The virtual machine code is not machine specific. The machine specific code is generated by the
java interpreter by acting as an intermediary between the virtual machine and the real machine as
shown in below figure. Remember that the interpreter is different for different machine.

Byte code Java Interpreter Machine Code

Real Machine

Shruthi S, Asst. Professor, Dept. of BCA. Page 10


Object Oriented Programming with Java 2023-24

JAVA TOKENS
Smallest individual units in a program are known as tokens. The compiler recognizes them for
building up expressions and statements.
A Java program is a collection of tokens, comments and white spaces. Java language includes
five types of tokens. They are:
 Reserved Keyword
 Identifiers
 Literals
 Operators
 Separators

JAVA CHARACTER SET


The smallest units of Java language are the characters used to write Java tokens. These characters
are defined by the unicode character set, an emerging standard that tries to create characters for a
large number of scripts worldwide. The Unicode is an l6-bit character coding system.

KEYWORDS
Keywords are an essential part of a language definition. Keywords have specific meaning in
Java. Java language has reserved 50 words as keywords.
Keywords cannot use them as names for variables, classes, methods and so on.
All keywords are to be written in lower-case letters.

Shruthi S, Asst. Professor, Dept. of BCA. Page 11


Object Oriented Programming with Java 2023-24

IDENTIFIER
Identifiers are programmer designed tokens. They are used for naming classes, methods,
variables, objects, labels, packages and interfaces in a program. Java identifier follows the
following rules:
 They can have alphabets, digits, and the underscore and dollar sign characters.
 They must not begin with digit.
 Uppercase and lowercase letters are distinct.
 They can be of any length.
 It should not be a keyword.

Java developers have followed some naming conventions.


 Names of all public methods and instance variables start with a leading lowercase letter.
Ex: average, sum
 when more than one words are used in a name, the second and subsequent words are marked
with a leading uppercase letters, Ex: dayTemperature, firstDayOfMonth, totalMarks
 All private and local variables use only lowercase letters combined with underscores.
Ex: length, batch_strength
 All classes and interfaces start with a leading uppercase letter
Ex: Student, HelloJava
 Variables that represent constant values use all uppercase letters and underscores between
words
Ex: TOTAL, F_MAX, PRINCIPAL_AMOUNT

LITERALS
Literals in Java are a sequence of characters (digits, letters, and other characters) that represent
constant values to be stored in variables; Java language specifies five major types of literals.
They are:
 Integer literals
 Floatingjoint literals
 Character literals
 String literals
 Boolean literals
Shruthi S, Asst. Professor, Dept. of BCA. Page 12
Object Oriented Programming with Java 2023-24

OPERATORS
An operator is a symbol that takes one or more arguments and operates on them to produce a
result.

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. Below lists separator and their functions.

Parentheses ( ) – Used to enclose parameters in method definition and invocation, also used for
definition precedence in expressions, containing expressions for flow control, and surrounding
cast types.
Braces {} - Used to contain the values of automatically initialized arrays and to define a block of
code for classes, methods and local scopes.
Brackets [] - Used to declare array types and for dereferencing array values.
Semicolon ; - Used to separate statements
Comma , - Used to separate consecutive identifiers in variable declaration, also used to chain
statements together inside a ‘for’ statement.

Period . - Used to separate package names from sub packages and classes; also used to separate
a variable or method from a reference variable.

VARIABLES
A variable is an identifier that denotes a storage location used to store a data value. The value of
variable remains unchanged during the execution of the program.
Ex: average, height, total_height classStrength
Variable names may consist of alphabets, digits, the underscore ( _ ) and dollar characters,
subject to the following conditions:
 They must not begin with a digit.
 Uppercase and lowercase are distinct. This means that the variable Total is not the same as
total or TOTAL.
 It should not be a keyword.
 White space is not allowed.
 Variable names can be of any length.

Shruthi S, Asst. Professor, Dept. of BCA. Page 13


Object Oriented Programming with Java 2023-24

CONSTANTS
Constants in java refer to fixed value that does not change during the execution of a program.
Java supports several types of constants as illustrated in figure.
Java constants

Numeric constant Character constant

Integer constant Real constant Character String Backslash character


constant constant
Integer Constants
An integer constant refers to a sequence of digits. There are three types of integers, namely,
decimal integer, octal integer and hexadecimal integer.
Decimal integer consist of a set of digits, 0 through 9, preceded by an optional minus sign
Ex: 123, -321, 0, 654321
Embedded space, commas, and non-digit character are not permitted between digits:
Ex: $1000 // Are illegal Numbers.
An octal integer constant consists of any combination of digit from set 0 through 7, with a
leading 0.
Ex: 037 0 0435 0551
A sequence of digit preceded by 0x or 0X is considered as hexadecimal integer. They may also
include alphabets A through F or a through f. A letter A through F represents the number 10
through 15.
Ex: 0X2 0X9F 0xbcd 0x

Real Constants
Integer numbers are inadequate to represent quantities that vary continuously, such as distances,
heights, temperatures, prices, and so on. These quantities are represented by numbers containing
fractional parts like 17.548 such number are called real (or floating point) constants.
Ex: 0.0083, -0.75, 435.36

Shruthi S, Asst. Professor, Dept. of BCA. Page 14


Object Oriented Programming with Java 2023-24

These numbers are shown in decimal notation, having a whole number followed by a decimal
point and the fractional part, which is an integer. It is possible that the number may not have
digits before the decimal point or digits after the decimal point.
Ex: 215, .95, - .71
A real number may also be expressed in exponential (or scientific) notation.
Ex: The value 215.65 may be written as 2.1565e2 in exponential notation.e2 means multiply by
102. .
The mantissa is either a real number expressed in decimal notation or integer. The exponent is an
integer with an optional plus or minus sign.
Ex: 0.65e4, 12e-2, 1.5e+5 , 3.18E3, -1.2E-1

Exponential notation is useful for representing number that are either very large or very smallin
magnitude
Ex: 7500000000 may be written as 7.5E9 or 75E8.
-0.000000368 is Equivalent to -3.68E-7.
A floating point constant may thus comprise four parts:
 A whole number
 A decimal point
 A fractional part
 An exponent

Single Character Constants


Single character constants a single character enclosed within a pair of quote marks.
Ex: ‘5’ ‘X’ ‘:’ ‘‘

String Constants
A string constant is a sequence of characters enclosed between double quotes. The character may
be alphabets, digits, special character and blank spaces.
Ex: “Hello Java”, “1997”, “WELL DONE”, “?...!”, “5+3” , “X”

Shruthi S, Asst. Professor, Dept. of BCA. Page 15


Object Oriented Programming with Java 2023-24

Backslash Character constants


Java supports some special backslash character constants that are used in output methods.

Constant Meaning
‘\b’ back space
‘\f’ Form feed
‘\n’ New line
‘\r’ Carriage return
‘\t’ Horizontal tab
‘\’ ‘ Single quote
‘\” ’ Double quote
‘\\’ Backslash

DATA TYPES
Data types specify the size and type of values that can be stored. Java language is rich in its data
types .Data types in Java are:
a. Primitive types (Intrinsic or built-in types or primary)
b. Derived types (Reference types)

DATA TYPES

Primitive Non-Primitive
(Derived)

Numeric Non-numeric
Classes Arrays

Interface
Integer Floating-point Character Boolean

Shruthi S, Asst. Professor, Dept. of BCA. Page 16


Object Oriented Programming with Java 2023-24

1. Primitive types (Intrinsic or built-in types)


Primitive types are Numeric and Non Numeric
Integer types
Integer types are a whole number such as 123,-96 and 5639. Java supports four types of
integers. They are byte, short, integer 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. Below
table shows the memory size and range of all four integer data types.

We can make integer long by appending the letter L or 1 at the end of the number.
Ex: 123L or 1231

Floating point types: floating point type to hold numbers containing fractional parts such as
27.59, -1.375. There are two kinds of floating point storage in Java. The float type values are
single-precision numbers and double types represent double precision numbers. Floating point
numbers are treated as double-precision quantities. To force them to be in single-precision mode,
we must append f or F to the number Size and Range of Floating Point Types
Ex: 1. 23f , 7.56923e5F

Double precision types are used when greater precision in storage of floating point number. All
the mathematical functions such as sin, cos and sqrt return double type values.
Floating point data types supports special value known as Not a-Number (NaN). NaN is used to
represent the result of operation such as dividing zero, where an actual number is not produced.

Shruthi S, Asst. Professor, Dept. of BCA. Page 17


Object Oriented Programming with Java 2023-24

Character Type
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.

Boolean Type
Boolean type is used 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. Boolean type is denoted by the
keyword boolean and uses only one bit of storage.

OPERATORS
Operators can be classified into different categories. They are
1. Assignment operator: = , + =, - =, * =, / =
2. Arithmetic operator: +, -, *, /, %
3. Relational operator : <, >, < =, > =, = =, ! =
4. Logical operator: &&, ||, !
5. Increment or decrement operator: ++, --
6. Bitwise operator: &, |, ^, <<, >>
7. Conditional operator: - (ternary) ? :
8. Special operator: , ( . ) dot operator, instanceof

1. Arithmetic operators
The arithmetic operators are used to perform arithmetic operations like, addition, subtraction,
multiplication, division and modulo. An arithmetic expression is one which comprises
arithmetic operators and variables or constants. Here variables and constants are called as
operands. The arithmetic operators are as follows.
+ : addition
- : subtraction
* : multiplication
/ : division
% : modulo

Shruthi S, Asst. Professor, Dept. of BCA. Page 18


Object Oriented Programming with Java 2023-24

The unary + and unary – are defined over a single operand.

Syntax: operand1 operator operand2


Ex : a+b, a-b etc.

2. Relational Operators
Relational operators are used to construct relational expressions, which are used to compare
two quantities. A relational expression is of the form operand1 operator operand2. The
relation operator are as follows.
< : is less than
> : is greater than
>= : is greater than or equal to
<= : is lesser than or equal to
== : is equal to
!= : is not equal to

Ex: a < b, a = =10.

The value of relational expression is either one or zero. It is one if the specified relation is
true and zero if the relation is false.
Ex: 10 < 20 is TRUE
30 = = 30 is TRUE
20 ! = 20 is FALSE

3. Logical Operators
These are used to construct compound conditional expressions. The logical operators &&
and || are used to combine two expressions and make decision and ! is used to negate a
conditional expression.
The Logical operators are
&& : Logical AND
|| : Logical OR
! : Logical NOT

Shruthi S, Asst. Professor, Dept. of BCA. Page 19


Object Oriented Programming with Java 2023-24

Logical AND: &&


The general form of compound expression constructed using && is C1 && C2.
The resultant condition (C1 && C2) is true only when both the conditions C1 and C2 are
true. Otherwise, it will be false.
The value of expression are as follows
C1 C2 C1 && C2
0 0 0
0 1 0
1 0 0
1 1 1

Ex: a=10, b=20


if (a>b && b>a) is FALSE
a>b = 10>20 is FALSE
b>a = 20>10 is TRUE

Logical OR: ||
The resultant condition C1 || C2 is false only when both the conditions C1 and C2 are false,
otherwise, it is true.
The value of expression are as follows

C1 C2 C1 || C2
0 0 0
0 1 1
1 0 1
1 1 1

Ex: a=10, b=20


if (a>b || b>a) is TRUE
a>b = 10>20 is FALSE
b>a = 20>10 is TRUE

Shruthi S, Asst. Professor, Dept. of BCA. Page 20


Object Oriented Programming with Java 2023-24

Logical NOT: !
Here the values are negated. True becomes false and false becomes true.
C1 ! C1
0 1
1 0

4. Increment and decrement operator


These operators are used to increment a variable by value 1 or decrement a variable by a
value 1. The operators are
++ : increment by 1
--- : decrement by 1

Ex: a=10
a++ = 11
a-- = 9
There are two types of increment:
1. Pre-increment: ++Operand
Here first increment takes place and then assign the value to the operand.
Ex: a = 90
x = ++a
The value of x = 91 and a = 91
2. Post-increment: Operand ++
Here first assignment takes place then increment the value.
Ex: a = 90
x = a++
The value of x = 90 and a = 91

There are two types of decrement:


1. Pre-decrement: - - operand
Here first decrement takes place and then assign the value to the operand.
Ex: a = 90
x=--a
The value of x = 89 and a=89
Shruthi S, Asst. Professor, Dept. of BCA. Page 21
Object Oriented Programming with Java 2023-24

2. Post-decrement: Operand - -
Example: a - -
Here first assignment takes place then decrement the value.
Ex: a = 90
x=a--
The value of x = 90 and a=89

5. Assignment operator
Assignment operators are used to assign the result of an expression to a variable.

Syntax: variable = expression;

Ex: int A;
A=10;
The variable A is assigned the value 10.
The assignment operator are as follows.
= : Assignment
+=, -=, *=, /=, %= are the symbols used perform arithmetic operation with assignment. These
are called shorthand assignment operators.

Ex: a+=10;  a = a+10;


A - =10  A= A - 10
B* = 20  B = B*20
C /= 4  C=C/4
D %= 5  D = D %5

6. Conditional Operator
Conditional operators are used for two way decision making. It is also called as ternary
operator.

Syntax: exp1? exp2: exp3;

First exp1 will be evaluated. If it is true then it will evaluate exp2 or else it will evaluate
exp3.

Shruthi S, Asst. Professor, Dept. of BCA. Page 22


Object Oriented Programming with Java 2023-24

Ex: a = 50, d =5
a > d ? a: d
50 > 5 ? 50: 5
The result is 50

7. Bitwise operator
It is used to manipulate numbers in bit level and also it is also used for faster calculations.
There are different types of bitwise operator they are:
& : Bitwise AND operator
| : Bitwise OR operator
~ : Bitwise COMPLEMENT operator
^ : Bitwise XOR operator
<< : Bitwise left shift.
>> : Bitwise right shift.

The bitwise AND, bitwise OR, bitwise XOR bitwise NOT are binary operators require two
integer-type operands. These operators work on their operands bit by bit.
The result of logical operations are as follows.

Op1 Op2 Op1 & Op2 Op1 | Op2 Op1 ^ Op2


0 0 0 0 0
0 1 0 1 1
1 0 0 1 1
1 1 1 1 0

Bitwise AND ( & ):


Let us consider two variables X and Y whose values are 13 and 25.The binary representation of
these two variables are
Z = X & Y  13 & 25
X  0000 1101
Y  0001 1001
Z = X & Y  0000 1001
So Z = 0000 1001, the decimal representation is 9.
Shruthi S, Asst. Professor, Dept. of BCA. Page 23
Object Oriented Programming with Java 2023-24

Bitwise OR ( | ):
Let us consider two variables X and Y whose values are 13 and 25.The binary representation of
these two variables are
Z = X | Y  13 & 25
X  0000 1101
Y  0001 1001
Z = X | Y  0001 1101
So Z = 0001 1101, the decimal representation is 29.

Bitwise XOR ( ^ ):
Let us consider two variables X and Y whose values are 13 and 25.The binary representation of
these two variables are as follows

Z = X ^ Y  13 & 25
X  0000 1101
Y  0001 1001
Z = X ^ Y  0001 0100
So Z = 0001 0100, the decimal representation is 20.

Bitwise LEFT SHIFT Operator ( << ):


The << operator is used to move bit pattern to the left. The general form of left shift is

Syntax: Operand << n

Operand is the integer expression that is to be shifted and n is the number of bit positions to be
shifted. The leftmost n bits in the original bit pattern will be lost and right most n bit positions
that are vacated will be filled with 0s.
Ex: a=10
a << 1
10<<1 => 0000 1010
=> 0001 0100 => 20

Shruthi S, Asst. Professor, Dept. of BCA. Page 24


Object Oriented Programming with Java 2023-24

Bitwise RIGHT SHIFT Operator ( >> ):


The >> operator is used to move bit pattern to the right. The general form of right shift is

Syntax: Operand >> n

Operand is the integer expression that is to be shifted and n is the number of bit positions to be
shifted. The right most n bits in the original bit pattern will be lost and left most n bit positions
that are vacated will be filled with 0s.
Ex: a=10
a >> 1
10 >> 1 => 0000 1010
=> 0000 0101 => 5

Bitwise COMPLEMENT Operator (~)


The complement operator inversts all the bits represted by its operand. That is 0’s become 1’s
and 1’s become zero.
Ex: X = 7 => 0000 0111
~X = 1111 1000 => 248

CONTROL STRUCTURES INCLUDING SELECTION


Control statement defined how the control is transferred from one part to the other part of the
program.
There are several control statement are also called decision making statements or conditional
statements. They are
1. Simple if statement.
2. If…else statement.
3. Nested if…else statement.
4. else if ladder
5. switch statement

1. SIMPLE IF STATEMENT
Simple if statement is used to make a decision based on the available choice. It has the
following form:

Shruthi S, Asst. Professor, Dept. of BCA. Page 25


Object Oriented Programming with Java 2023-24

Syntax:
if ( condition )
{
Block of Statements;
}
Statements X;
if is the keyword. <condition> is a relational expression or logical expression or any expression
that returns either true or false. It is important to note that the condition should be enclosed
within parentheses ‘(‘ and ’ )’. The block of Statements; can be a simple statement or a
compound statement or a null statement. Statements X is any valid statement.
The flow of control using simple if statement is determined as follows:
Whenever simple if statement is encountered, first the condition is tested. It returns either true or
false. If the condition is false, the control transfers directly to Statements X without considering
the block of Statements. If the condition is true, the control enters into the block of Statements.
Once, the end of Statements block is reached, the control transfers to Statements X.
Ex: if (age>=55)
{
System.out.println ("person is retired\n");
}

2. IF ELSE STATEMENT
if else statement is used to make a decision based on two choices. It has the following form:
Syntax:
if(condition)
{
True Statement block;
}
else
{
False Statement block;
}
Statement X;
Shruthi S, Asst. Professor, Dept. of BCA. Page 26
Object Oriented Programming with Java 2023-24

 In this syntax, if and else are the keywords.


 <condition> is a relational expression or logical expression or any expression that returns
either true or false. It is important to note that the condition should be enclosed within
parentheses ( and ).
 The true Statement block and false Statement block are simple statements or
compound statements or null statements.
 Statement X is any valid C statement.

The flow of control using if. else statement is determined as follows:

Whenever if...else statement is encountered, first the condition is tested. It returns either true or
false. If the condition is true, the control enters into the true Statement block. Once, the end of
true Statement block is reached, the control transfers to Statement X without considering else-
body. If the condition is false, the control enters into the false Statement block by skipping true
Statement block. Once, the end of false Statement block is reached, the control transfers to
Statement X.

Ex: if(age>=55)
System.out.println ("person is retired\n");
else
System.out.println ("person is not retired\n");

3. NESTED IF ELSE STATEMENT


Nested if else statement is one of the conditional control flow statements. If the body of if
statement contains at least one if statement, then that if statement is called as “Nested if else
statement”. The nested if else statement can be used in such a situation where at least two
conditions should be satisfied in order to execute particular set of instructions. It can also be
used to make a decision among multiple choices. The nested if else statement has the
following form:

Shruthi S, Asst. Professor, Dept. of BCA. Page 27


Object Oriented Programming with Java 2023-24

Syntax:
if(condition1)
{
if(condition 2)
{
Statement 1;
}
else
{
Statement 2;
}
}
else
{
Statement 3;
}
Statement X;

In this syntax,
 if and else are keywords.
 <condition1>,<condition2> … <condition> are relational expressions or logical
expressions or any other expressions that return true or false. It is important to note that
the condition should be enclosed within parentheses ( and ).
 if-body and else-body are simple statements or compound statements or empty
statements.
 Statement X is a valid C statement.

The flow of control using Nested if else statement is determined as follows.


Whenever nested if else statement is encountered, first <condition1> is tested. It returns either
true or false. If condition1 (or outer condition) is false, then the control transfers to else-body (if
exists) by skipping if-body.
If condition1 (or outer condition) is true, then condition 2 (or inner condition) is tested. If the
condition 2 is true, if-body gets executed. Otherwise, the else-body that is inside of if statement
gets executed.
Ex: if(a>b)
{
if(a>c)

Shruthi S, Asst. Professor, Dept. of BCA. Page 28


Object Oriented Programming with Java 2023-24

{
System.out.println ("The result= " +a);
else
System.out.println ("The result= " +b);
}
else
{
if(c>b)
System.out.println ("The result= " +c);
else
System.out.println ("The result= " +b);
}
}

4. ELSE IF LADDER
else if ladder is one of the conditional control flow statements. It is used to make a decision
among multiple choices. It has the following form:
Syntax:
if (condition 1)
{
Statement 1;
}
else if(condition 2)
{
Statement 2;
}
else if(condition 3)
{
Statement 3;
}
else if(condition N)
{
Statement N;
Shruthi S, Asst. Professor, Dept. of BCA. Page 29
Object Oriented Programming with Java 2023-24

}
else
{
Default Statement;
}
Statement X;
In this syntax,
 if and else are keywords. There should be a space between else and if, if they come
together.
 <condition 1>,<condition 2>….<condtion N> are relational expressions or logical
expressions or any other expressions that return either true or false. It is important to note
that the condition should be enclosed within parentheses ( and ).
 Statement 1, statement 2, statement 3……, statement N and default statement are either
simple statements or compound statements or null statements.
 Statement X is a valid C statement.

The flow of control using else if Ladder statement is determined as follows:


Whenever else if ladder is encountered, condition1 is tested first. If it is true, the statement 1 gets
executed. After then the control transfers to Statement X.
If condition1 is false, then condition2 is tested. If condition2 is false, the other conditions are
tested. If all are false, the default Statement at the end gets executed. After then the control
transfers to Statement X
If any one of all conditions is true, then the body associated with it gets executed. After then the
control transfers to Statement X.
Ex: if(avg>=75)
{
System.out.println ("distinction");
}
else if(avg>=60 && avg<75)
{
System.out.println ("first class");
}

Shruthi S, Asst. Professor, Dept. of BCA. Page 30


Object Oriented Programming with Java 2023-24

else if(avg>=50 && avg<60)


{
System.out.println ("second class");
}
else if (avg<50 && avg>35)
{
System.out.println ("Pass");
}
else
{
System.out.println ("Fail");
}

5. SWITCH CASE STATEMENT


switch statement is one of decision making control flow statements. Just like else if ladder, it
is also used to make a decision among multiple choices. Switch statement has the following
form:
Syntax:
switch(<exp>)
{
case val-1: statements block-1
break;
case val-2: statements block-2
break;
case val-3: statements block-3
break;
:
case val-N: statements block-N
break;
default: default statements block
}
Next-statement;

Shruthi S, Asst. Professor, Dept. of BCA. Page 31


Object Oriented Programming with Java 2023-24

In this syntax,
 switch, case, default and break are keywords.
 <exp> is any expression that should give an integer value or character value. In other
words, it should never return any floating point value. It should always be enclosed with
in parentheses ( and ). It should also be placed after the keyword switch.
 val-1, val-2, val-3…. val-N should always be integer constants or character constants or
constant expressions. In other words, variables can never be used as val. There should be
a space between the keyword case and val. The keyword case along with its val is called
as a case label. val should always be unique; no duplications are allowed.
 Statements block-1, statements-block-2, statements block-3… statements block-N and
default statements block are simple statements, compound statements or null statements.
It is important to note that the statements blocks along with their own case labels should
be separated with a colon ( : ).
 The break statement at the end of each statements block is an optional one. It is
recommended that break statement always be placed at the end of each statements block.
 The statement block and break statement can be enclosed with in a pair of curly braces {
and }.
 The default along with its statements block is an optional one. The break statement can
be placed at the end of default statements block.

Whenever, switch statement is encountered, first the value of <exp> gets matched with case
values. If suitable match is found, the statements block related to that matched case gets
executed. The break statement at the end transfers the control to the Next-statement.
If suitable match is not found, the default statements block gets executed. After then the control
gets transferred to Next-statement.
Ex:
switch(ch)
{
case 1: c=a+b;
break;
case 2: c=a-b;
break;
Shruthi S, Asst. Professor, Dept. of BCA. Page 32
Object Oriented Programming with Java 2023-24

case 3: c=a*b;
break;
case 4: c=a/b;
break;
case 5:return;
}

LOOPING STATEMENTS
C supports four types of looping statement.
1. for loop
2. while loop
3. do while loop
4. nested loop

1. FOR LOOP
It is one of the looping control statements. It tests the condition before entering into the loop
body. The syntax for “for” statement is as follows:

Syntax:
for(Initialize; Condition; increment/decrement)
{
for-block of statement;
}
next_statement;
In this syntax,
 for is a keyword.
 Initialization statement: If there is more than one statement, then those should be
separated with commas.
 Condition: It is a relational expression or a compound relational expression or any
expression that returns either true or false.
 increment/decrement statement: If there is more than one statement, then those should be
separated with commas. for-bock of statement is a simple statement or compound
statement or a null statement.

Shruthi S, Asst. Professor, Dept. of BCA. Page 33


Object Oriented Programming with Java 2023-24

Whenever “for” statement is encountered, first initialization gets executed. After then, condition
is tested. If it is true then the body of the loop will be executed otherwise loop will be
terminated. When the body of the loop is executed the control is transferred back to the for
statement after evaluating last statement in the loop. Now increment/decrement will be evaluated
and the new value is again tested .if it satisfies, body of the loop is executed. This process
continues till condition is false.

Ex: for(i=1; i<=n ;i++)


{
System.out.println ("The value is=",+i);
}

2. WHILE LOOP
The simplest of all the looping structures in c is the while statement. The basic format of the
while statement is:

Syntax:
while (condition)
{
block of Statements;
}
next statement;

The while is an entry controlled loop statement. The condition is evaluated and if the condition is
true then the statements will be executed. After execution of the statements the condition will be
evaluated and if it is true the statements will be executed once again. This process is repeated
until the condition becomes false and the control is transferred out of the loop.

Ex: i=1;
while(i<=n)
{
System.out.println ("Number=",+i);
i=i+1;
}

Shruthi S, Asst. Professor, Dept. of BCA. Page 34


Object Oriented Programming with Java 2023-24

3. DO WHILE STATEMENT
It is one of the looping control statements. It is also called as exit controlled looping control
statement. i.e., it tests the condition after executing the do while loop body.
In “do-while” statement, the loop body gets executed at least once, though the condition is not
tested. for the first time.
Syntax:
Initialization statement;
do
{
block of statement;
} while(<condition>) ;
next statement;

 While and do are the keywords.


 <condition> is a relational expression or a compound relational expression or any
expression that returns either true or false.
 The statements within the curly braces are called as do-while loop body. There should be
a semi-colon (;) at the end of while(<condition>).

Whenever “do-while” statement is encountered, the initialization statement gets executed first.
After then, the control enters into do while loop body and all the statements in that body will be
executed. When the end of the body is reached, the condition is tested with the updated loop
counter value. If the condition returns the value false, the control transfers to next statement
without executing do-while loop body. Hence, it states that, the do-while loop body gets
executed for the first time, though the condition returns the value false.
Ex: i=1;
do
{
System.out.println("Value= " +i);
i=i+1;
} while(i<=n);

Shruthi S, Asst. Professor, Dept. of BCA. Page 35


Object Oriented Programming with Java 2023-24

DIFFERENCE BETWEEN WHILE AND DO WHILE

while do while
While is also called as entry controlled loop Do while is also called as exit controlled loop

It follows a top down approach. It follows a bottom up approach.

It tests condition before the body gets It tests condition after the body gets executed.
executed.
The body of statement gets executed only The body of statement gets executed at least
when the condition is true. once though the condition is false for the first
time.
while(condition) while(condition);
No semicolon is present at the end of the while A semicolon is present at the end of the do-
loop. while loop.

4. NESTING OF LOOP or NESTED LOOP


When one or more loop written inside the body of another loop then, it is known as nesting
of loop. Any type of loop can be nested in any type such as while, do while, for.
For example nesting of for loop can be represented as:

for(Initialize; Condition; increment/decrement)


{
for(Initialize; Condition; increment/decrement)
{
for-block of statement; Inner Loop Outer
Loop
}
}

When Outer loop is condition is true, control will enter the inner loop to test, if it true, body of
inner loop gets execute. When inner loop become false it will execute the body of outer loop.
Inner loop will get execute repeatedly till the outer loop gets false.

Shruthi S, Asst. Professor, Dept. of BCA. Page 36


Object Oriented Programming with Java 2023-24

for(i=0;i<2;i++)
{
for(j=0;j<5; j++)
{
System.out.println(+ j);
}
}

For example nesting of for and while loop can be represented as:
for(Initialize; Condition; increment/decrement)
{
while (condition)
{
block of Statements; Inner Loop Outer Loop
}
}

JAVA METHODS
A method is a block of code which only runs when it is called. we can pass data, known as
parameters, into a method. Methods are used to perform certain actions, and they are also known
as functions.
Methods are used 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() etc,

Syntax: return type method name (parameter list)


{
Method definition // code to be executed
}

Shruthi S, Asst. Professor, Dept. of BCA. Page 37


Object Oriented Programming with Java 2023-24

Ex: Create a method inside Main:


public class Main
{
static void myMethod ()
{
// code to be executed
}
}
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 is 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 when it is called: Since void main()
is present inside the same class no need to create a object.
Ex: public class Main
{
static void myMethod()
{
System.out.println("I just got executed!");
}
public static void main(String args[])
{
myMethod();
}
}

OVERLOADING
It is possible to create methods that have same name, but different parameter lists and different
definition. This is called overloading. Method overloading is used when objects are required to
perform similar tasks but using different input parameters.

Shruthi S, Asst. Professor, Dept. of BCA. Page 38


Object Oriented Programming with Java 2023-24

Definition: Multiple methods can have the same name with different parameters is called
method overload or function overloading.
There are two ways to overload the method in java
 Same method name but different in datatype
 Same method name but different in number of arguments

 Same method name but different in datatype


Ex: class overloading
{
int c;
void sum(int a,int b)
{
c=a+b;
System.out.println("The sum of integers ="+c);
}
void sum(float a,float b)
{
float c;
c=a+b
System.out.println("The sum of floating numbers:"+c);
}
public static void main(String args[])
{
overloading o=new overloading();
o.sum(10,20);
o.sum(10.1f,11.2f);
}
}

In the above example two method names are sum but parameters are defined as int and float.

Shruthi S, Asst. Professor, Dept. of BCA. Page 39


Object Oriented Programming with Java 2023-24

 Same method name but different in number of arguments


Ex: 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 TestOverloading
{
public static void main(String[] args)
{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(10,12,13));
}
}
In the above example two method names are add but number of parameters are different. In one
method is passed with 2 parameter, and another is passed with 3 parameters

M ATH CLASS

The java.lang.Math class contains methods for performing basic numeric operations such as
exponential, logarithm, square root, and trigonometric functions. Mathematical functions such as
cos, sqrt, log etc. Java supports these basic math functions through Math class defined in the
java.lang package.
These functions should be used as follows:
Syntax: Math.function_name ();
Ex: Math.sqrt(x);

Shruthi S, Asst. Professor, Dept. of BCA. Page 40


Object Oriented Programming with Java 2023-24

import java.lang.Math;
class squareroot
{
public static void main(String args[])
{
double x = 5;
double y;
y = Math.sqrt(x);
System.out.println(”Y=”, +y);
}
}

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. Array in Java is index-based,
the first element of the array is stored at the 0th index, and 2nd element is stored on 1st index and
so on.
There are two types of array.
1. Single Dimensional Array
2. Multidimensional Array

1. Single Dimensional Array in Java


The declaration of array can be done as follows.
Syntax: datatype arrayname[size];
Ex: int arr[3];
Creation of array in java are as follows.
Syntax: arrayname = new datatype [size];
Ex: arr = new int [3];

Initialization of an Array in Java


Syntax: datatype arrayname[size] = { list of values};
Ex: int arr[3] = {34, 12, 5};

Shruthi S, Asst. Professor, Dept. of BCA. Page 41


Object Oriented Programming with Java 2023-24

//Java Program to illustrate how to declare, initialize and display the Java array.
class Testarray
{
public static void main(String args[])
{
int a[]=new int[3]; //declaration and creation
int a[3] = {34, 12, 5};
for(int i=0;i<3; i++)
System.out.println(a[i]);
}
}

Multidimensional Array in Java


Multidimensional Array is data is stored in row and column based index.
Syntax: datatype arrayname[rowsize ][colsize];
Ex: int arr[2][3];

Creation of Multidimensional array in java are as follows.


Syntax: arrayname = new datatype [rowsize ][colsize];
Ex: arr = new int [2][3];

Initialization of an Array in Java


Syntax: datatype arrayname[rowsize ][colsize] = { list of values};
Ex: int arr[2][3] = {{34, 12, 5},{1,2,3}};

//Java Program to illustrate how to declare, initialize and display the Multidimensional Array
class Testarray1
{
public static void main(String args[])
{
arr = new int [2][3];
int arr[2][3];={{1,2,3},{2,4,5}}; //declaring and initializing 2D array
for(int i=0;i<2; i++)

Shruthi S, Asst. Professor, Dept. of BCA. Page 42


Object Oriented Programming with Java 2023-24

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

CLASS AND OBJECTS


CLASS: A class is a collection both data member and member functions” And “It is a collection
of similar type of object.
A class is a set of objects with similar properties (attributes), common behavior (operations), and
common link to other objects

Creation of Class
Syntax: class class_name
{
[Data member declaration;]
[Methods declaration;]
}
Here class is a keyword. Class name is java identifiers. Data members are the variables of class.
Methods are the functions used to perform on data fields.

Data member declaration:-Data is encapsulated in a class by placing data fields inside the body
of the class definition. These variables are called instance variables as they are created whenever
an object of the class is initiated.
Ex: class rectangle
{
int length;
int width;
}

Shruthi S, Asst. Professor, Dept. of BCA. Page 43


Object Oriented Programming with Java 2023-24

Methods declaration: It is necessary to add methods that are used for manipulating the data
contained in the class. A method is declared inside the body of the class but immediately after
the declaration of instance variables. The general for of method declaration is as follows:
Syntax: returntype method_name(parameter list)
{
Method body;
}

Ex: class Rectangle


{
int length; // Data member declaration
int width;
void getdata(int x,inty) // method declaration
{
length=x;
width=y;
}
}

OBJECTS
Object is an instance of a class used to access the both Data member & member functions
outside the class

Creating objects
Creating an object is referred as instantiating an object. Objects, in java are created using the new
operator. The new operator crates an object of the specified class and returns a reference to that
object.
Syntax: class_name object name = new class_name();
Ex: Rectangle r1=new Rectangle ();

Shruthi S, Asst. Professor, Dept. of BCA. Page 44


Object Oriented Programming with Java 2023-24

Accessing class members


To access the class data members, we use the concerned object and the dot operator.
Syntax: objectname. variable_name = value;
Ex: r1.length = 10;
To access the class method,
Syntax: Object name. metod_name (parameter list);
Ex: r1.getdata (10, 30);
Here,
1. Object name is the name of the object.
2. Variables are the instance variables inside the class
3. Method name is the member methods of the class
4. Parameter list is the actual values that must match in type and number with the parameter
list of the method name declared in the class.

A java Program to illustrate class, object, fields, method declaration and accessing the class
members.
class Rectangle
{
int length, width;
void getdata(int x,int y)
{
length = x;
width = y;
}
void putdata()
{
System.out.println("length = " + length);
System.out.println("width = " + width);
}
void display()
{

Shruthi S, Asst. Professor, Dept. of BCA. Page 45


Object Oriented Programming with Java 2023-24

int area = length*width;


System.out.println("Area = " +area);
}
public static void main(String args[])
{
Rectangle r1=new Rectangle();
r1.length = 10;
r1.width = 30;
r1.getdata(10,30);
r1.putdata();
r1.display();
}
}

CONSTRUCTOR
A constructor is a special type of method that enables an object to initialize itself when it is
created. All the objects that are created must be given initial values. This can be done using dot
operator or using member methods of a class.
Constructor has the same name of that of the class. Constructor do not return any type because
that return the instance of the class itself.
Rules for creating java constructor
1. Constructor name must be same as its class name
2. Constructor must have no explicit return type
//program to illustrate constructor:

class Rectangle
{
int length, width;
Rectangle (int x, int y) //declaring constructor
{
length = x;
width = y;
}
Shruthi S, Asst. Professor, Dept. of BCA. Page 46
Object Oriented Programming with Java 2023-24

int rectarea()
{
return (length*width);
}
class RectArea
{
public static void main(String args[])
{
Rectangle.rect1 = new Rectangle(5,10); //calling constructor
int area = rect1.rectarea();
System.out.println(“Area = “+,area);
}
}

Types of java constructors


1. Default constructor (no-argument constructor): A constructor that have no parameter is
known as default constructor. Default constructor provides the default values to the object
like 0, null etc. depending on the type.

Ex: class Student


{
int id;
String name;
Student() // Default constructor
{
id = 1;
name = “Shru”;
}
void display()
{
System.out.println (id+" "+name);
}
Shruthi S, Asst. Professor, Dept. of BCA. Page 47
Object Oriented Programming with Java 2023-24

public static void main(String args[])


{
Student s1 = new Student(); // calling default constructor
s1.display();
}
}

2. Parameterized constructor: Constructors that have parameters is known as parameterized


constructor. Parameterized constructor is used to provide different values to the distinct
objects.
class Student
{
int id;
String name;
Student(int i,String n) // parameter constructor
{
id = i;
name = n;
}
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
Student4 s1 = new Student4(111,"Karan"); // calling parameter constructor
s1.display();
}
}

Shruthi S, Asst. Professor, Dept. of BCA. Page 48


Object Oriented Programming with Java 2023-24

FINALIZER METHOD
Java supports a concept called finalization, which is just opposite to initialization. Java run time
is an automatic garbage collecting system. It automatically frees up the memory resources used
by the objects.
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.

VISIBILITY MODIFIER
The visibility modifier is also called as access modifiers. Visibility modifier in java specifies the
accessibility or scope of a field, method, constructor, or class. There are four types of Java access
modifiers.
1. public: Public Access modifiers Specifies that data Members and Member Functions those
are declared as public will be visible in entire class in which they are defined. 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.
Ex: public int number;
public void sum()
{
//
}

2. Private: The Methods or variables those are declared as private Access modifiers are not
accessed outside the class or in inherited Class or the Subclass. By default all the Data
Members and Member Functions is private. The access level of a private modifier is only
within the class.
Ex: private int number;
private void sum()
{
//
}

Shruthi S, Asst. Professor, Dept. of BCA. Page 49


Object Oriented Programming with Java 2023-24

3. Protected: The Methods those are declared as protected access modifiers are accessible to only in
the Sub Classes but not in the Main Program.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.
Ex: protected int number;
protected void sum()
{
//
}

4. private protected: A field can be declared with two keywords private and protected
together like
Ex: private protected int number;
This gives the visibility level in between the protected access and private acess.This
modifier makes the fields visible in all subclasses regardless of what package they are in.

Shruthi S, Asst. Professor, Dept. of BCA. Page 50

You might also like