Object Oriented Programming in Java
Object Oriented Programming in Java
UNIT 1
COURSE [Link]
SEMESTER 21
PREPARED BY
(Faculty Name/s) [Link], Assistant professor
Version V-1
BTECH_IT-SEM 21
SVEC TIRUPATI
15 CONTENTS BEYOND THE SYLLABUS
16 PRESCRIBED TEXT BOOKS & REFERENCE BOOKS
17 MINI PROJECT SUGGESTION
BTECH_IT-SEM 21
1. Course Objectives
The objectives of this course are to
1. To understand object oriented concepts and problem solving techniques
2. To obtain knowledge about the principles of inheritance and polymorphism
3. To implement the concept of packages, interfaces, exception handling and
concurrency mechanism.
4. To design the GUIs using applets and swing controls.
5. To understand the Java Database Connectivity Architecture
2. Prerequisites
Students should have knowledge on
1. C Programming Syntax and Semantics
2. Object Oriented Programming Concepts
3. Syllabus
UNIT I
Object Oriented Programming: Basic concepts, Principles, Program Structure in Java: Introduction,
Writing Simple Java Programs, Elements or Tokens in Java Programs, Java Statements, Command Line
Arguments, User Input to Programs, Escape Sequences Comments, Programming Style.
Data Types, Variables, and Operators :Introduction, Data Types in Java, Declaration of Variables, Data
Types, Type Casting, Scope of Variable Identifier, Literal Constants, Symbolic Constants, Formatted
Output with printf() Method, Static Variables and Methods, Attribute Final,
Introduction to Operators, Precedence and Associativity of Operators, Assignment Operator ( = ),
Basic Arithmetic Operators, Increment (++) and Decrement (- -)Operators, Ternary Operator,
Relational Operators, Boolean Logical Operators, Bitwise Logical Operators.
Control Statements: Introduction, if Expression, Nested if Expressions, if–else Expressions, Ternary
Operator?:, Switch Statement, Iteration Statements, while Expression, do–while Loop, for Loop,
Nested for Loop, For–Each for Loop, Break Statement, Continue Statement.
4. Course outcomes
Student should be able to
Understand the syntax, semantics and features of Java Programming
Language.
Learn object oriented features and understanding type conversion and
casting.
Understand different types of string handling functions and its usage.
CO1 2 2 2 1 3 1 1 3 1 3 2 3 3
CO2 1 2 3 3 1 2 3 1 1 3 3
CO3
2 2 2 3 3 1 1 3 3
6. Lesson Plan
LECTURE WEEK TOPICS TO BE COVERED REFERENCES
8. Lecture Notes
1.1 INTRODUCTION
1. Java Is A “Programming Language”.
2. A Programming Language Is Set Of Instructions , Used To Establish
Communication Between Human And A System
3. Java technology is both a programming language and a platform.
4. Java is a high level, robust, secured and object-oriented programming
language.
[Link] IT 21
SVEC TIRUPATI
[Link] IT SEM21
SVEC TIRUPATI
4) Continue Statement.
5) Program Structure in Java:
Introduction
After import statement, every java program starts with the declaration of the
class. A program may have one or more classes.
A class declaration starts with the keyword class, followed by the identifier or name
of the class. Giving the name of a package at the top is optional.
Class declarion contains name of the class and body of the class. The body of
the class may consist of several statements and is enclsed between the
braces {}.
Here:
public is access specifier. This class is accessible to any ouside code. Otherwise
the class is accessibe to only same package classes.
4|O O P S - U N I T - I
[Link] IT SEM21
SVEC TIRUPATI
class is a keyword of java language which is used to declare the class.
The class body starts with the left brace { and ends with the right colsing brace }.
// are comments which are neglected by the compiler.A class body may comprise
statements for declaration of variables. constants, expressions, and methods.
Here:
class is a keyword
Start is a name the class. Here class is declared as public, so it is
available to all the classes.
main() is the method which initiate and terminate the program ( in java
functions are called as Methods)
println() is method of object “out”. “out” is the object of class
“System”. println() prints the string “Hello World” on the
screen/monitor.
Java compiler first converts the source code into an intermediate code,
known as bytecode or virtual machine code. To run the bytecode, we need
the Java Virtual Machie (JVM). JVM exists only inside the computer memory
and runs on top of the Operating System. The bytecode is not machine
specific. The Java interpreter converts the bytecode into Machine code. The
following diagram illustrates the process of compiling and running Java
programs.
For compiling the program, the Java compiler javac is run, specifying the
name of the source file on the command line as depicted here:
javac [Link]
The Java compiler creates a file called [Link] containing the bytecode
version of the program. The java interpreter in JVM executes the instructions
contained in
5|O O P S - U N I T - I
[Link] IT SEM21
this intermediate Java bytecode version of the program. The
Java interpreter is called with “java” at the command prompt.
Output:
Hello World
Here java command calls the Java interpreter which executes the
[Link] (bytecode of [Link]).
2. Boolean literal
• These are Boolean values. There are only two values—true or false.
3. Character literal
• These are the values in characters.
• Characters are represented in single quotes such as ‘A’, ‘H’, ‘k’, and so
on.
4. String literal
• These are strings of characters in double quotes.
Examples are “Delhi”, “John”, “AA”, etc.
5. Null literal
• There is only one value of Null Literal, that is, null.
Types of Operators:
Arithmetic Operators:
Operator Description
+ Addition or Unary plus
- Subtraction or Unary minus
* Multiplication
/ Division
% Modulus
Relational Operators:
Operator Description
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
== Equal to
!= Not equal to
Logical Operators:
Operator Description
&& Greater than
|| Greater than or equal to
! Less than
Assignment Operators:
Operator Description
+= Add and assign to
-= Subtract and assign to
*= Multiply and assign to
/= Divide and assign to
%= Modulus and assign to
Conditional Operators:
Operator Description
?: Used to construct Conditional expression
Java Statements
A Statement is a instruction to the computer. A program is a set
of statements or instructions. The statements specify the
sequence of actions to be performed when some method or
constructor is invoked. The statements are executed in the
sequence in the specified order. The important Java statements
are as follows.
Statement Description
Empty statement These are used during program development.
Variable It defines a variable that can be used to store the
declaration values.
statement
Labeled statement A block of statements is given a label. The
labels should not be keywords, previously used
labels, or already declared
local variables.
Expression Most of the statements come under this
statement category. There are seven types of expression
statements that include
assignment, method call and allocation, pre-
increment, post increment, pre-decrement, and
post decrement statements.
Control statement This comprises selection, iteration, and jump
statements.
Selection In these statements, one of the various control
statement flows is selected when a certain condition
expression is true. There are three types of
selection statements including if, if-else,
and switch.
Iteration statement These involve the use of loops until some
condition for the
termination of loop is satisfied. There are three
types of iteration statements that make use of
while, do, and for
Jump statement In these statements, the control is transferred
to the beginning or end of the current block or
to a labeled statement. There are four types of
Jump statements including
break, continue, return, and throw.
Synchronization These are used with multi-threading
statement
Guarding These are used to carry out the code safely that
statement may cause exceptions (such as division by zero,
and so on). These
statements make use of try and catch block, and
finally
Command Line Arguments
• A Java application can accept any number of arguments from the command
line.
• These arguments can be passed at the time of running the
program. This enables a programmer to check the behavior of a
program for different values of inputs.
• When a Java application is invoked, the runtime system passes
the command line arguments to the application's main method
through an array of strings.
• It must be noted that the number of arguments
•
• in an array. To ensure this, we can make use of the length property
of the array. This is illustrated in
class vehicle
public static void main(String args[])
{
int x = [Link];
for(int i=0; i<x; i++)
{
[Link](args[i]);
}
}
Output
(After compiling, type the following lines on the command prompt. It produces
the output as)
class Sum
{
public static void main{String args)
int s=1;
s=s+[Link](args(1]);
Output
Declaration of Variables
Examples:
class PrintOut
{
public static void main (String args[])
{
String name = "Sunita"; //"name" is variable, value is "Sunita"
String str = "Hello"; //String set has value- "Hello!"
System. [Link]();
c:\>javac [Link]
c:\>java PrintOut
Name= SunitaStr = Hello
Length 50
Width 8
HelloSunita
• The class Scanner of package [Link] to carry out input to the program.
• Java Scanner class is a text scanner that breaks the input into
tokens using a delimiter. The delimiter is whitespace by default.
• Importing the class is the first step.
import [Link];
• The object of the class Scanner is declared as follows.
Scanner scaninput = new Scanner (System. in);
• The object “scaninput” invokes the method nextInt() which reads
the value typed by the user. This value is assigned to n. The value of
m is similarly obtained.
• The other useful methods of Scanner class are nextDouble() and nextLine().
Program 2.6: Illustration of a user's input from keyboard into
program
import [Link];
public class Arithmetic
{
public static void main(String[] args)
{
Scanner scaninput = new Scanner (System. in);
int n;
int m;
[Link]. print( "Enter the value of n : ");
n=[Link]();
[Link]. print( "Enter the value of m : ");
m=[Link]();
Output
C:\>javac [Link]
C:\>java Arithmetic
Enter the value of n : 10
Enter the value of m : 3
Sum of two numbers is =13
Product of two numbers is =30
Modulus of (n % m) is =1
Division of two numbers is =3
C:\>
Escape Sequences
Escape Sequences character is preceded by a backslash (\)has a
special meaning to the compiler. Escape sequences are as follows.
class Escape
{
public static void main(String[] args)
{
int n=256, a=0, b=70;
[Link]("Value of a =" + a + "\n b= "+b +"\n");
[Link]("\u0041 \t" + " \u0042 \t"+"\132");
[Link]("\"Value of b\" = "+b);
[Link]("\'Value of n\' = " +n);
}
}
Output:
C:\>javac [Link]
C:\>java Escape
Value of a =0
b= 70
A B Z
"Value of b" = 70
'Value of n' = 256
Comments
• Comments are Line of Text which is not a part of the compiled
program.
• Comments are used for documentation to explain source code.
• They are added to the source code of the program.
• Java supports three types of comments as:
1. Single-line comment: These comments are started with
two front slash characters (//)
Example:
// This is Single line comment
Programming Style.
Indenting is another method often used to improve the looks and readability
Use of Lambda expression and method reference of Java 8 enhances the look
The program should be easy to understand. The programmer should take care
of the following aspects:
The makers of Java have a set of rules which are followed in the Java
library. The same rules or an even better convention may be set.
The vertical alignment of a similar item enhances the ability to find errors.
• The names used should imply the output type such as price, weight, length,
and so on.
I. Primitive data
3. Arrays
4. Methods
The primitive data and their types are defined independent of the classes
and interfaces, and the arrays and methods derive their types from the
first three entities.
• Data Type is the type of the data which computer accepts. Every
variable and expression has a data type that is known at the compile
time.
• The declaration of data type with a variable or expression limits the
types of values that a variable can have or the expression it can
evaluate.
• Java is an object-oriented programming language based on classes and
interfaces.
• Java defines some primitive (basic) data types that are not reference
types of any class or interface. Eight primitive (basic) types of data are
defined in Java. The type names are also the keywords shown here in
bold letters
• Integral types—byte, short, int, long
• Floating point types - float, double
• Character type -char
• Boolean type – Boolean values – True, False
There is a non-data type called void and no data can be of type void.
This type is used for methods that do not return any value.
Java is a case-sensitive language. This means that it takes Area, area, and
AREA are three different objects.
type Identifier;
Here type is the primitive data type and Identifier is the name of the
Ex:
ch.
Non-primitive Types
These are the class and interface types. The name of a class or interface
is the name of type. A class object is declared as
Class_identifier object_identifier;
Interface_identifier reference_identifier;
Example:
Data Types
Integers
Integers are whole numbers, that is, they represent numbers that do not
have a fractional part. The integers can be declared in four types
according to the size of memory allocated for them
class DataType
{
public static void main (String args[])
{
byte a= 4, b=8 ;// variables of type byte
short c = 67, d = 98; // variables of type short
int e = 7000, f = 20000; // variables of type int
long secondsInYear = 365 * 24 * 60 * 60; // long type
//e=d+f;
[Link]("(b + a) = " + (b+a));
[Link]("b + a = " + b + a);
[Link]("c = "+ c + " \td = " + d);
[Link]("e = " + e + "\t f= " + f);
[Link]("Seconds in a year = "+ secondsInYear);
}
}
Output:
Characters
• A variable may have value in terms of a character in which the type of
variable is char.
• These characters represent integer values.
• Java supports Unicode for the representation of characters.
• Unicode supports all the character sets of all the major languages of the
world.
• The initial version of Unicode allocated 2 bytes for storing characters.
• The range of values for characters in the initial version of Unicode
comprised from ‘\u0000’ to ‘\uffff ’ that is from 0 to 65535 both
end values inclusive.
• Program 3 2 illustrates anthmetic operations on character
constants and variables
class Datachar {
public static void main (String args[])
{
char ch1='E', ch2, ch3 ;
ch2=ch1++;
[Link]("ch2 =" + ch2); // printing ch2
ch3=++ch1;
[Link]("ch3 =" + ch3); // printing ch3
}
}
Output:
C:\ >javac [Link]
C:\ >java Datachar
ch1 =E
ch2 =E
ch3 =G
Floating Point Numbers
• The numbers that are not whole numbers, or those that have
fractional part, Examples are 3.141, 476.6, and so on.
• Java supports two types of such numbers.
Float: This type is used for single-precision decimal floating point
numbers, that is, 7 digits after the decimal point. These numbers are
stored on 4 bytes.
Program 3.4: Illustration for working with float and double data
class FloatType
{
public static void main (String args[])
{
float width =20.0f, length = 40.5f;
float rectArea = length * width;
C:\>javac [Link]
C:\>java FloatType
Width = 20.0
Length = 40.5
Rectangle Area = 810.0
Diameter 10.0
Area of Circle = 78.53975
class Boolean
{
public static void main (String args[])
{
double x= 5.5, y=10.5, p=4.0;
int n=40, m=50;
boolean a,b,c,d;
a= x>y;
b= y>p;
c= y==x;
d= x<=y;
C:\>javac [Link]
C:\>java Boolean
a = false and b =true
Now c= false and d = true
o Type Casting
Converting one data type to another data type is called as Type Casting.
There are two types of type casting. They are,
int A = (int) D;
d=c/a;
k=a+y;
e = a + (int)y;
z=(double)c/a;
1. The scope starts from the point the variable is defined in the block
(declared and value assigned to it).
If there are nested blocks, a variable defined in the outer block is visible in
the inner blocks also and it cannot be redefined with the same name in
the inner blocks
E:\>java ScopeA
Class Scope variable - outside main() x = 5
Variable y Scope within main() y = 10
Variable z Scope within Anonymous Block z = 20
E:\>java ScopeA
C:\>javac [Link]
C:\>java SymbolicConst
radius=25.0
Perimeter of circle = 157.079632675
class FormatPrintf
{
public static void main(String args[])
{
int n = 713;
float x = 45.86f;
double d= 56.754;
C:\>javac [Link]
C:\>java FormatPrintf
713 45.860001 56.754000 A Delhi
Hexadecimal value of 163 = A3
Octal value of 163 = 243
Static Variables:
a) The static variables are class variables. Only one copy of such
variables is kept in the memory and all the objects share that
copy.
b) The static variables are accessed through class reference,
whereas the instance variables are accessed through class
object reference
c) The variables in a class may be modified by modifier static.
d) The non-static variables declared in a class are instance variables Each
object of the class keeps a copy of the values of these variables.
Static Methods:
e) The static methods are similar to class methods and can be invoked
without any reference of object of class, however, class reference
(name of class) is needed, as in the following example The method
like sart() is declared as static method in Math class and is called
The static method is called using the method name that is preceded by
the class name; in this case. Math and period ().
E:\>java StaticMethods
The Square root root of 16 = 4.0
The cubroot root of 27 = 3.0
Random Number 1 = 77
Random Number 2 = 69
Random Number 3 = 83
Random Number 4 = 2
Random Number 5 = 66
E:\>java StaticMethods
The Square root root of 16 = 4.0
The cubroot root of 27 = 3.0
Random Number 1 = 67
Random Number 2 = 31
Random Number 3 = 10
Random Number 4 = 13
Random Number 5 = 40
3. Attribute Final
Final Variable:
The value of a variable declared final cannot be changed in the
program. It makes the variable a constant. A few examples of
declarations are as follows:
Final Method:
b) The attribute final may be used for methods as well as for classes.
These are basically connected with inheritance of classes.
c) When final keyword is used with Java method, it becomes the final method.
d) A final method cannot be overridden in a sub-class.
Final Class:
e) A Java class with final modifier is called final class A final class cannot
be sub-classed or inherited. Several classes in Java are final including
String, Integer, and other wrapper classes.
f) There are certain important points to be noted when using final keyword in
Java
• New value cannot be reassigned to a variable defined as final in Java.
• Final keyword can be applied to a member variable, local variable,
method, or class.
• Final member variable must be initialized at the time of declaration.
• Final method cannot be overridden in Java
• Final class cannot be inheritable in Java
• Final is different from finally keyword, which is used on Exception handling
in Java
Example- 1:
public class Final
{
public static void main (String args[])
{
Output:
C:\>javac [Link]
[Link]: error: cannot assign a value to final variable f
f = 60; // Error : f is final variable can not be changed
^
1 error
C:\>
Example-2:
C:\>java Final
n = 10
f = 20
n = 50
4. Introduction to Operators
An operator is a symbol that tells the computer to perform certain
mathematical and logical calculations.
-The different types of Java operators are,
(a) Arithmetic operators
(b) Relational operators
(c) Logical operators
(d) Increment or decrement operators
(e) Assignment operators
(f) Conditional operators
(g) Bitwise operators
(h) Special operators
Example:
if(a>b)
[Link](“a is
greater”); else
[Link] (“b is greater”);
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
~ One’s complement
Bitwise AND operator:
-The Bitwise AND (&) is a binary operator that requires two integral
operands(character or integer).
-It does a bit-by-bit comparison between two operands.
-The result of the comparison is 1 only when both bits are 1, otherwise it is
0.
First operand Second operand Result(&)
bit bit
0 0 0
0 1 0
1 0 0
1 1 1
Bitwise OR operator:
-The Bitwise inclusive OR (|) is a binary operator that requires
two integral operands(character or integer).
-It does a bit-by-bit comparison between two operands.
-The result of the comparison is 0 only when both bits are 0, otherwise it is
1.
Special Operators.
(a) Java supports some special operators such as,
• instanceof operator
• member selection operator
(a) instanceof operator:
(b) The instanceof is an object reference operator and returns true if the
object on the left-hand side is an instance of the class given on the right
hand side.
(c) This operator allows us to determine whether the object belongs to a
particular class or not. Example:
person instanceof student
(d) It is true if the object person belongs to the class student, otherwise it is
false.
• Introduction
CONTROL STATEMENTS: (FLOW OF CONTROL)
- A Control statement is a statement used to control the flow of execution in a
Java Program.
SELECTION STATEMENTS:
-Also called as conditional or decision-making control statements.
-There are two types in Selection control statements.
[Link]-way selection control statements
2. Multi-way selection control statements
• Two-way selection control statements:
-The different two-way selection statements are,
• if-else statement
• null else statement
• Nested-if statement
Syntax:
if(condition)
{
statements;
}
next statement;
Example:
if(a==2)
{
p++;
}
[Link](“program over”);
• Nested if Expressions
-if within if is called as
Nested-if. Syntax:
if(condition-1)
{
if(condition-2)
{
Statement-1;
}
else
{
Statement-2;
}
}
else
{
if(condition-3)
{
Statement-3;
}
else
{
Statement-4;
}
}
next statement;
Example:
if(a>b)
{
if(a>c)
{
[Link](“a is greater”);
}
else
{
[Link] (“c is greater”);
}
}
else
{
if(b>c)
{
}
}
else
{
}
[Link]
.println(“ [Link](“c is greater”);
b is
greater”); if–else Expressions Syntax: if(condition)
{
true-block statements;
}
else
{
false-block statements;
}
next statement;
} [Link](“b is greater”);
else
{
• Ternary Operator?:
In Java, the ternary operator is a type of Java conditional
operator. The meaning of ternary is composed of three parts.
The ternary operator (? :) consists of three operands. It is used to
evaluate Boolean expressions. The operator decides which value will be
assigned to the variable. It is the only conditional operator that accepts
three operands.
It can be used instead of the if-else statement. It makes the code much
more easy, readable, and shorter.
Syntax:
Expression1 ? Expression2 : Expression3
Example-1:
int a=10;
int b = (a<20)? 100 :200; // a < 20 if statement
[Link]("b= "+b);
}
}
Output:
C:\>javac [Link]
C:\>java Ternary
b= 100
Example-2:
Output:
C:\>javac [Link]
C:\>java Ternary
b= 200
• Switch Statement
Syntax:
switch(expression)
{
case value-1:statement-1;break; case
value-2:statement-2;break;
………………………….
………………………….
case value-n:statement-n;break;
default: default statement;
}
next statement;
Example:
switch(digit)
{
case 0: [Link](“ZERO”);break;
case 1: [Link](“ONE”);break;
case 2: [Link](“TWO”);break;
case 3: [Link](“THREE”);break;
case 4: [Link](“FOUR”);break;
case 5: [Link](“FIVE”);break;
case 6: [Link](“SIX”);break;
case 7: [Link](“SEVEN”);break;
case 8: [Link](“EIGHT”);break;
case 9: [Link](“NINE”);break;
default: [Link](“Enter between 0-9”);
}
• Iteration Statements
LOOP STATEMENTS:
-The iteration control statements are also called as Repetition or Iteration
control statements.
-A looping process includes the following four
steps.
-Setting and initialization of a counter.
-Execution of the statements in the loop body.
-Test for a specified condition (loop control expression) for execution of a
loop
-Incrementing or Decrementing counter.
• Pretest and Posttest loops:
-In a Pretest loop, the condition is checked before we execute a loop body.
-It is also called as entry-controlled loop.
-In the Posttest loop, we always execute the loop body atleast once.
-It is also called as exit-controlled loop.
• while Expression
a) while statement:
Syntax:
while(condition)
{
loop body;
}
next statement;
Example:
n=10,i=1,sum
=0;
while(i<=n)
{
sum=sum+i
; i++;
}
[Link](“sum=”+sum);
• do–while Loop - forLoop
Syntax:
do
{
loop body;
}while(condition);
next statement;
Example:
n=10,i=1,sum=0;
do
{
sum=sum+i;
i++;
} while(i<=n);
[Link](“sum=”+sum);
• forLoop
for statement:
Syntax:
for(initialization;condition;inc or dec)
{
loop body;
}
next statement;
Example:
n=10,i,sum=0;
for(i=1;i<=n;i+
+)
{
sum=sum+i;
}
[Link](“sum=”+sum);
• Nested for Loop
Syntax:
for(initialization;condition;inc or dec)
{
for(initialization;condition;inc or dec)
{
Inner loop body;
}
Example:
n=10,i, j, sum=0;
for(i=1;i<=n;i++)
{
sum=sum+i;
}
[Link](“sum=”+sum);
• For–Each for Loop
Example:
Output:
C:\>javac [Link]
C:\>java ForEach
10
20
30
4050
• Break Statement
Unconditional control statements:
-The unconditional control statements are,
a) break statement
b)continue statement
break statement:
-The break statement skips from the loop or block in which it is defined.
-The control then automatically goes to the first statement after the loop or
block.
-The general format is
break;
Example:
Output:
C:\>javac [Link]
C:\>java Break
0
1
2
3
4
Example:
C:\>javac [Link]
C:\>java Continue
0
1
2
3
4
6
7
8
9
51