1. CDOE-ODL BSc(CS) SEMESTER IV Unit I
1
UNIT I
Objective: To provide fundamental knowledge of object-oriented programming and
basics of Java.
REVIEW OF OBJECT ORIENTED CONCEPTS
Object
Any entity that has state and behavior is known as an object. For example, a chair,
pen, table, keyboard, bike, etc. It can be physical or logical.
An Object can be defined as an instance of a class. An object contains an address
and takes up some space in memory.
Class
Collection of objects is called class. It is a logical entity.
A class can also be defined as a blueprint from which you can create an individual
object. Class doesn't consume any space.
Inheritance
When one object acquires all the properties and behaviours of a parent object, it is
known as inheritance. It provides code reusability. It is used to achieve runtime
polymorphism.
Polymorphism
If one task is performed in different ways, it is known as polymorphism. For example:
to convince the customer differently, to draw something, for example, shape,
triangle, rectangle, etc.
In Java, we use method overloading and method overriding to achieve
polymorphism.
Encapsulation
Binding (or wrapping) code and data together into a single unit are known as
encapsulation. For example, a capsule, it is wrapped with different medicines.
CDOE-ODL
2. CDOE-ODL BSc(CS) SEMESTER IV Unit I
2
A java class is the example of encapsulation. Java bean is the fully encapsulated
class because all the data members are private here.
HISTORY OF JAVA
Java History
Java is a high-level programming language originally developed by Sun
Microsystems and released in 1991.
Java runs on a variety of platforms, such as Windows, Mac OS, and the various
versions of UNIX. So java is platform independent.
Java was designed for the development of software for consumer electronic
devices like TVs, VCRs, toasters and such other electronic devices.
199
develop a special software that can be used to manipulate consumer electronic
devices.
n of their new language to control
a list of home applications.
developing web applets.
applet programs on internet.
3. CDOE-ODL BSc(CS) SEMESTER IV Unit I
3
JAVA BUZZWORDS
Object Oriented:
Java is truly 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 off classes, arranged in packages that we can
use in our programs by inheritance.
The object model in java is simple and easy to extend.
Robust and Secure:
Java is a robust language. It provides many safeguards to ensure reliable code. It
has strict compile time and runtime 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
errors and eliminates risk of crashing the system.
The absence of pointers in java ensures that programs cannot gain access to
memory locations without proper authorization.
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 as easily as
they can do in a local system.
This enables multiple programmers at multiple remote locations to collaborate
and work together on a single project.
Simple, Small and Familiar:
Java is a small and simple language. Many features of C and C++ that are either
redundant
For example java does not use pointers, preprocessor header files, goto
statement and overloading and multiple inheritance and many others.
4. CDOE-ODL BSc(CS) SEMESTER IV Unit I
4
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.
For example we can listen to an audio clip while scrolling a page and at the same
time download an applet from a distant computer.
This feature greatly improves the interactive performance of graphical
applications.
High performance
Java performance is impressive for an interpreted language, mainly due to the
use of intermediate byte code. According to sun, java speed is comparable to the
native C/C++.
Java architecture is also designed to reduce overheads during runtime. Further,
the incorporation of multithreading enhances the overall execution speed of java
programs.
Dynamic and Extensible
Java is a dynamic language.
It is capable of dynamically linking in new class libraries, methods, and objects.
Java program support functions written in other languages such as C and C++.
These functions are known as native methods.
JVM ARCHITECTURE
It facilitates the execution of programs developed in java. It comprises of the
following:
Java Virtual machine(JVM): It is a program that interprets the intermediate java
byte code and generates the desired output. It is because if byte code and JVM
concepts that programs written in Java are highly portable.
5. CDOE-ODL BSc(CS) SEMESTER IV Unit I
5
Runtime class libraries: There are a set of core class libraries that are required
for the execution of java programs.``
User interface toolkits: AWT and swing are examples of toolkits that support
varied input methods for the users to interact with application program.
Deployment technologies: JRE comprises the following key deployment
technologies:
Java plug-in: Enables the execution of a java applet on the browser.
Java Web start: Enables remote-deployment of an application.
DATA TYPES
Data types specify the size and type of values that can be stored.
Data types in Java
Integer Types
Integer types can hold whole numbers such as 123, -96, 5678. Java supports four
types of integers. They are byte, short, int, and long.
Type Size Minimum value Maximum value
Byte One byte -128 127
Short Two bytes -32,768 32,767
Int Four bytes -2,147,483,648 2,147,483,647
Long Eight bytes -
9,223,372,036,854,775,8
08
9,223,372,036,854,775,
807
Numeric
Floating Point Types
Floating point type contains fractional parts such as 26.78 and -7.890.
The float type values are single-precision numbers while the double types
represent double-precision numbers.
Floating point numbers are treated as double-precision quantities. We must
append f or F to the numbers. Example: 1.23f 7.67567e5F
6. CDOE-ODL BSc(CS) SEMESTER IV Unit I
6
Double-precision types are used when we need greater precision in storage of
floating point numbers. Floating point data types support a special value known as
Not-a-Number (NaN).
It is used to represent the result of operations such as dividing by zero, where
an actual number is not produced.
Type Size Minimum value Maximum value
Float 4 bytes 3.4e-038 1.7e+0.38
double 8 bytes 3.4e-038 1.7e+308
Character Type
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
It 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.
VARIABLES
A variable is an identifier that denotes a storage location used to store a data value.
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.
It should not be a keyword.
White space is not allowed.
Variable names can be of any length.
A variable must be given a value after it has been declared it is used in an
expression. This can be achieved in two ways:
1. By using an assignment statement
7. CDOE-ODL BSc(CS) SEMESTER IV Unit I
7
2. By using a read statement
SCOPE AND LIFE TIME OF VARIABLE
Java variables are actually classified into three types:
Instance variables
Class variables
Local variables
Instance and class variable are declared inside a class. Instance variables are
created when the objects are instantiated and they are associated with the objects.
Class variables are global to a class and belong to the entire set of objects
that class creates. Only one memory location is created for each class variable.
Variables declared and used inside methods are called local variables. They
are not available for use outside method definition.
We often encounter situations where there is a need to store a value on one type
into a variable of another type.
In such situation, we must cast the value to be stored by proceeding it with the
type name in parentheses. The syntax is
type variable1 = (type) variable2;
The process of converting one data type to another is called casting. Examples:
int m= 50;
byte n = (byte)m;
Four integer types can be cast to any other type except Boolean. Casting into a
smaller type may result in loss of data. Similarly, the float and double can be cast to
any other type except Boolean.
From To
byte short, char, int, long, float,
double
short int, long, float, double
char int, long, float, double
int long, float, double
8. CDOE-ODL BSc(CS) SEMESTER IV Unit I
8
long float, double
float Double
Casts that results in no loss of information
ARRAYS
An array is a group of related data items that share a common name. A particular
value is indicated by specifying a number called index number or subscript in square
brackets after the array name.
The arrays can be classified into two types. They are
1. One-dimensional array
2. Two-dimensional array
Creating An Array
Creation of array includes three steps:
1. Declare the array
2. Create memory locations
3. Put values into the memory locations.
One-dimensional array
A list of items can be given one variable name using only one subscript and such
variable is called a single-subscripted variable or a one-dimensional array.
Declaration of one-dimensional array:
Arrays in java may be declared in two forms.
Form 1: type arrayname[ ];
Form 2: type[ ] arrayname;
Ex: int mark[];
int[ ] mark;
Creation of one-dimensional array
Arrays are created by using new operator. The general form is
9. CDOE-ODL BSc(CS) SEMESTER IV Unit I
9
arrayname = new type[size];
Ex: mark = new int[10];
Initialization of one-dimensional array:
Values are assigned to the array by specifying the subscript.
arrayname[subscript] = value;
Ex: mark[2] = 65;
An array may also be initialized when they are declared.
type arrayname[ ] = {list-of-values};
The list-of-values are separated by comma and surrounded by curly braces. The
memory for the array is allocated by the compiler based on the number of values
given.
Ex: int x[] = {25,35,15,5,55}
Array length : In java, all arrays store the allocated size in a variable named length.
To know the size of an array, it can be accessed as
arrayname.length
Two-Dimensional Arrays
To store the values in a table form then two dimensional array is used. Two
subscript are needed to access a value in two dimensional array.
Declaration of two-dimensional array:
Arrays in java may be declared in two forms.
Form 1: type arrayname[ ][ ];
Form 2: type[ ][ ] arrayname;
Ex: int mata[ ][ ];
int[ ][ ] mata;
10. CDOE-ODL BSc(CS) SEMESTER IV Unit I
10
Creation of two-dimensional array
Arrays are created by using new operator. The general form is
arrayname = new type[row][col];
Ex: mata = new int[3][2];
Initialization of two-dimensional array:
Values are assigned to the array by specifying the subscript.
arrayname[subscript1][subsrcipt2] = value;
Ex: mata[2][2] = 15;
An array may also be initialized when they are declared.
type arrayname[ ][ ] = {list-of-values};
The list-of-values are separated by comma and surrounded by curly braces. The
memory for the array is allocated by the compiler based on the number of values
given.
Ex: int x[ ][ ] = {25,35,15,5,55,45}
Variable Size Arrays
two-dimensional array as follows.
int x[ ][ ] = new int [3][ ];
x[0] = new int[2];
x[1] = new int[5];
x[2] = new int[3];
OPERATORS
Java supports a rich set of operators.
An operator is a symbol that is used for manipulate data and variables.
Operators are used in programs to manipulate data and variables.
o Arithmetic operators
o Relational operators
11. CDOE-ODL BSc(CS) SEMESTER IV Unit I
11
o Logical operators
o Assignment operators
o Increment and decrement operators
o Conditional operators
o Bitwise operators
o Special operators
Java operators are classified into number of categories.
ARITHMETIC OPERATORS
Arithmetic operators are used to construct mathematical expressions as in algebra
Operator Meaning
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo division
RELATIONAL OPERATORS
Compares two quantities depending on their relation.
Java supports six relational operators.
Operator Meaning
< is less than
<= is less than or equal to
> is greater than
>= is greater than or equal to
= = is equal to
!= is not equal to
A simple relational expression contains only one relational operator and is of the
following form:
ae-1 relational operator ae-2
where ae-1 and ae-2 are arithmetic expressions
12. CDOE-ODL BSc(CS) SEMESTER IV Unit I
12
LOGICAL OPERATORS
Java has three logical operators.
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
A logical operator returns either TRUE or FALSE values.
Logical operator && and || are used to check compound condition (ie for
combining two or more relations)
When an expression combines two or more relational expressions then it is
called logical expression or a compound relational expression
ASSIGNMENT OPERATORS
Used to assign the value of an expression to a variable.
v op=exp;
INCREMENT AND DECREMENT OPERATORS
They are also called unary operator.
--
They may also use to increment subscripted variables
CONDITIONAL OPERATORS
The character pair ?: is used for conditional operator.
It is also called as ternary operator.
General Form exp1 ? exp2: exp3
where exp1, exp2, exp3 are expressions
The operator ?: works as follows
exp1 is evaluated first, if its is true then the exp2 is evaluated.
If exp1 is false, exp3 is evaluated
BITWISE OPERATORS:
13. CDOE-ODL BSc(CS) SEMESTER IV Unit I
13
Bitwise operators are used to manipulate data at values of bit level.
These operators are used for testing the bits, or shifting them to the right or left.
Bitwise operators may not to float or double.
Operator Meaning
& Bitwise AND
! Bitwise OR
^ Bitwise exclusive OR
~
<< Shift left
>> Shift right
>>> Shift right with zero fill
SPECIAL OPERATORS
Java supports special operators
Instance of operator
Dot operator (or) member selection operator (.)
Instance of operator:
Instance of operator is an object reference operator.
Allow us to determine whether the object belongs to a particular class or
not.
Return true, if the object on the left-hand side is an instance of the class
given on the right-hand side.
Dot operator
The dot operator (.) is used to access the instance variables and methods of class
objects.
It is also used to access classes and sub packages from a package.
14. CDOE-ODL BSc(CS) SEMESTER IV Unit I
14
CONTROL STATEMENTS
When a program breaks the sequential flow and jumps to another part of the code, it
is called branching.
When the branching is based on a particular condition, it is known as conditional
branching.
If branching takes place without any decision, it is known as unconditional
branching. if statement
switch statement
Conditional operator statement
The following statements are known as control or decision making statements.
if statement
switch statement
Conditional operator statement
IF Statement
The if statement is a powerful decision making statement and is used to control the
flow of execution of statements.
General form if (test expression)
The expression is first evaluated.
Depending on the value of the expression is true or false, control is transfer to a
particular statement.
The if statement are
1. simple if statement
2. statement
3. Nested statement
4. else if ladder
15. CDOE-ODL BSc(CS) SEMESTER IV Unit I
15
1. Simple If Statement
If the test expression is true the statement block will be executed; otherwise
the execution will jump to the statement-x
Statement block may be single statement or a group of statement.
Example
General form
if (test expression)
{
statement-block;
}
statement-x;
Example
if (category == SPORTS)
{
marks = marks +
bonus_marks;
}
System.out.println(marks);
2.
If the test expression is true, then the true-block statements are executed.
Otherwise, the false block statements are executed.
General form
if (test expression)
{
True block statements;
}
else
{
False block statements;
}
Statement-X;
Example
{
points = points+500;
}
else
{
Points = points + 100;
}
3. Nesting of if
Here if the condition-1 is false, the statement-3 will be executed; otherwise it
evaluates the condition-2.
If the condition-2 is true, then statement-1 will be executed; otherwise the
statement -2 will be evaluated and then control is transferred to the statement-x.
16. CDOE-ODL BSc(CS) SEMESTER IV Unit I
16
General form
if (test condition1)
{
if (test condition2)
{
True
blockstatements-1;
}
else
{
False block
statement-2;
}
}
else
{
False block statements-3;
}
Statement-x;
Example
{
if (balance>5000)
{
Bonus = 0.03 *
balance;
}
else
{
Bonus = 0.02 *
balance;
}
}
else
{
Bonus = 0.01 * balance;
}
balance=balance + bonus;
4. Else if ladder
Else If ladder is a chain of ifs in which the statement associated with each else is an
if.
The condition is evaluated from the top to downwards.
As soon as the condition is true, then the statements associated with it are
executed and the control is transferred to the statement -x.
When all the n condition is false, then the final else containing the default-
statement will be executed.
General form
If (condition-1)
statement-1;
else if (condition-2)
statement -2;
else if (condition-3)
statement -3;
else if (condition n)
statement -n;
else
default-statement;
Example
If (marks>79)
else if (marks>79)
else if (marks>79)
else if (marks>79)
else
-stmt
17. CDOE-ODL BSc(CS) SEMESTER IV Unit I
17
The Switch Statement
It an multiway decision statement.
The switch statement tests the value of a given variable against a list of case
values.
When a match is found, a block of statement associated with that case is
executed.
The expression is an integer expression or character known as case labels.
No need to put braces around each block
Case labels end with a colon (:)
The breakstatement at the end of each block signal the end of a particular case
and causes an exit from the switch statement, transferring the control to the
statement -x following the switch.
The default is an option case; it will be executed if the value of the expression
does not match with any of the case values.
If not present, no action takes place when all matches fail and the control goes to
the statement x.
General form
switch(expression)
{
case value-1:
block-1
break;
case value-2:
block-2
break;
case value-3:
block-3
break;
Example
switch(expression)
{
case
break;
case
break;
case
break;
18. CDOE-ODL BSc(CS) SEMESTER IV Unit I
18
default:
default-block
break;
}
statement-x;
case
break;
default:
break;
}
SIMPLE JAVA PROGRAM
Simple java program
class SampleOne
{
public static void main (String args[])
{
System.out.println(
}
}
Class declaration
The first line
Class SampleOne declares a class, java is a true object-oriented language and
therefore, everything must be placed inside a class.
class is a keyword and declares that a new class definition follows.
SampleOne 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 ends with a
matching closing brace
The main line
The third line
public static void main (String args[])
The above line defines a method named main.
19. CDOE-ODL BSc(CS) SEMESTER IV Unit I
19
This is similar to the main() function in C/C++.
Every java application program must include the main() method. This the
starting point for the interpreter to begin the execution of the program.
A java application can have any number of classes but only one of them must
include a main method to initiate the execution.
The 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 : Declares this method as one that belongs to the entire class and not a
part of any object of the class. The main methods must always be declared as
static since the interpreter uses this method before any object are created.
Void: The void states that the main method does not return any value.
The output line
The only executable statement in the program is
This is similar to printf() statement of C or cout<< construct of C++.
Since java is a true object oriented language, every method must be part of an
object.
The println method is a member of the out object, which is a static data member of
System class.
CONSTRUCTORS
Every class has a constructor. If we do not explicitly write a constructor for a class,
the Java compiler builds a default constructor for that class.
Each time a new object is created, at least one constructor will be invoked.
The main rule of constructors is that they should have the same name as the
class.
A class can have more than one constructor.
They does not return any value and do not specify even void.
Constructors are automatically called during the creation of the objects.
20. CDOE-ODL BSc(CS) SEMESTER IV Unit I
20
ADVANTAGES OF CONSTRUCTORS:
1. A constructor eliminates placing the default values.
2. A constructor eliminates calling the normal method implicitly.
TYPES OF CONSTRUCTORS:
Based on creating objects in JAVA we have two types of constructors.
They are
Default/parameter less/no argument constructor and Parameterized constructor.
STRING AND STRING BUFFER CLASSES
Strings, which are widely used in Java programming, are a sequence of characters.
In Java programming language, strings are treated as objects.
The Java platform provides the String class to create and manipulate strings.
String Class Methods
Method task performed
s2=s1.toLowerCase; Converts the string s1 to all lowercase
Converts the string s1 to all uppercase
Replace all appearances of x with y
s1.equal(s2); Returns true if s1 is equal to s2
s2=s1.trim(); Remove white space at the beginning and end of the String
s1
s1.equalsIgnoreCase(
s2);
Returns true if s1 is equal to s2, ignoring the case of
characters
s1.length(); Gives the length of s1.
s1.charAt(n) Gives nth character of s1
s1.concat(s2); Concatenates s1 and s2
s1.substring(n); Gives substring starting from nth character.
s1.substirng(n,m); Gives substring starting from nth character up to mth
character
String.valueOf(p); Creates a string object of the parameter p(simple type or
object)
21. CDOE-ODL BSc(CS) SEMESTER IV Unit I
21
p.toString(); Creates a string representation of object p
string s1
String.valueOf(variable
);
Converts the parameter value to string representation.
s1.compareTo(s2) Returns negative if s1<s2, positive if s1>s2, zero if s1 and s2
equal.
StringBuffer class methods
StringBuffer class is a peer class of String.
String creates strings of fixed_length
StringBuffer class creates string of flexible length that can be modified in terms of
both length and content.
In stringbuffer class we can insert characters and substrings in the middle of a
string, or append another string to the end.
1 public StringBuffer append(String s)
Updates the value of the object that invoked the method. The method takes boolean,
char, int, long, Strings, etc.
2 public StringBuffer reverse()
The method reverses the value of the StringBuffer object that invoked the method.
3 public delete(int start, int end)
Deletes the string starting from the start index until the end index.
4 public insert(int offset, int i)
This method inserts a string s at the position mentioned by the offset.
5 replace(int start, int end, String str)
This method replaces the characters in a substring of this StringBuffer with characters
in the specified String.
22. CDOE-ODL BSc(CS) SEMESTER IV Unit I
22
SUMMARY
The provided document covers a comprehensive overview of Object-Oriented
Concepts, Java History, Java Buzzwords, JVM Architecture, Data Types, Variables,
Operators, Control Statements, Simple Java Program, Constructors, String and
StringBuffer classes. Understand the basic Object-oriented concepts. Implement the
basic constructs of Core Java.
ACTIVITIES
o Identify and list objects and their corresponding classes from everyday scenarios
(e.g., car as an object, Car class).
o Create a hierarchy of classes related to vehicles (e.g., Vehicle -> Car, Truck) and
demonstrate inheritance by sharing properties and methods.
o Implement method overloading and overriding using simple scenarios (e.g.,
Shape class with various subclasses like Circle, Square).
o Design a Java class that demonstrates encapsulation (private fields, public
methods for access).
o Draw a diagram illustrating the components of the JVM and explain their
functions.
o Simulate scenarios where students must use if-else statements or switch
statements to control program flow based on different conditions.
o Create classes with multiple constructors and demonstrate how each constructor
is invoked during object instantiation.
SELF-ASSESSMENT QUESTIONS
1. How would you define an object in your own words?
2. What are the key characteristics of an object? Can you provide examples?
3. How do state and behavior relate to objects? Can you illustrate this with a specific object?
4. Why do objects occupy space in memory, and how does this affect program performance?
5. How is a class like a blueprint? Can you provide a real-world analogy?
6. What types of data and methods are typically included in a class definition?
7. How does inheritance promote code reusability? Can you give an example?
8. What is polymorphism, and why is it a key concept in object-oriented programming?
9. What are the two main types of polymorphism in Java? Can you briefly explain each?
10. How does method overloading demonstrate polymorphism? Can you give a code
example?
11. How does method overriding demonstrate polymorphism? Can you give a code example?
23. CDOE-ODL BSc(CS) SEMESTER IV Unit I
23
12. What is encapsulation, and how does it enhance data security in a program?
13. What are conditional statements, and why are they used in programming?
14. How do you structure an if-else statement to handle multiple conditions?
15. What is the purpose of the else if statement, and how does it differ from using multiple
if statements?
16. What are the logical operators (&&, ||, !) in Java, and how are they used in conditional
statements?
17. How would you test the correctness of your conditional statements in your code?
18. What are the different types of constructors in Java? Explain each type briefly.
19. How does a parameterized constructor differ from a default constructor? Provide an
example.
20. What is constructor overloading, and how is it implemented in Java?
21. What are the different types of loops available in Java? Describe each type.
22. What factors can affect the efficiency of a loop? How can you optimize looping
statements?
23. How would you test and debug your loop structures to ensure they function correctly?