Unit 1 - Oops With Java (Part 1)
Unit 1 - Oops With Java (Part 1)
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.
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.
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.
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.
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.
Year Development
1990 A team of Sun Microsystems programmers headed by James Gosling was formed.
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
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.
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.
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++.
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( 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
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;
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.
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.
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
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.
Real Machine
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
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.
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.
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.
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
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
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
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”
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
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.
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
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
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
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
Logical NOT: !
Here the values are negated. True becomes false and false becomes true.
C1 ! C1
0 1
1 0
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
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.
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.
6. Conditional Operator
Conditional operators are used for two way decision making. It is also called as ternary
operator.
First exp1 will be evaluated. If it is true then it will evaluate exp2 or else it will evaluate
exp3.
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.
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.
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
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
1. SIMPLE IF STATEMENT
Simple if statement is used to make a decision based on the available choice. It has the
following form:
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
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");
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.
{
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.
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.
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.
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;
}
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;
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);
while do while
While is also called as entry controlled loop Do while is also called as exit controlled loop
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.
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.
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,
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.
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
In the above example two method names are sum but parameters are defined as int and float.
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);
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
//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]);
}
}
//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++)
{
for(int j=0;j<3; j++)
{
System.out.println(arr[i][j]+ " ");
}
System.out.println();
}
}
}
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;
}
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;
}
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 ();
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()
{
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);
}
}
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()
{
//
}
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.