Object Oriented Programming Basics
Object Oriented Programming Basics
1
OOP allows us to decompose the problem into number of entities called Objects.
Data of object can be accessed only by the methods associated with that object.
It follows Bottom-Up approach in program development.
2
Explain the basic concepts of Object - Oriented Programming?
OOP is programming model that uses “objects “ and their interaction to design applications
and computer programs. The basic concepts of Oops language are:
Class:
A class is a template definition of the methods and variables for a particular kind of
object. In other words , class is the blue print ( logical representation) from which an
individual objects is created.
Object:
An Object is a real time entity. It is also known as instance of a class.
An object will have some properties and it can perform some actions. Object contains
variables and methods.
The objects which exhibit similar properties and actions are grouped under one class.
Encapsulation:
Wrapping up of data (variables) and methods into single unit is called Encapsulation.
Encapsulation can be described as a protective mechanism that prevents the code and
data being accessed by other code defined outside the class.
Abstraction:
Providing the essential features without its inner details is called abstraction (or)
hiding internal implementation is called Abstraction.
We can enhance the internal implementation without effecting outside world.
Abstraction provides security.
Inheritance:
Acquiring the properties from one class to another class is called inheritance (or)
producing new class from already existing class is called inheritance.
3
Reusability of code is main advantage of inheritance.
The relation between the two class is known as “is a” relation.
Polymorphism:
The word polymorphism came from two Greek words „poly‟ means „many‟ and
„morphos‟ means „forms‟. Polymorphism represents the ability to assume several
different forms. The ability to define more than one function with the same name is
called Polymorphism.
Dynamic Binding:
It is also known as dynamic dispatch, it is the process of linking function call to a
specific function definition at run-time.
Dynamic binding is also known as late binding.
Message Passing:
OOPS includes objects which communicate with each other.
Objects communicate with one another by sending and receiving information much
the same way as people pass messages to one another.
4
Data
Data
Function Function
Delegation:
When objects of one class is used as data member in another class, such composition
of objects is known as delegation.
Such a relation between two classes is known as “ has a” relation.
1. Main program is divided into small parts 1. Main program is divided into small object
depending on the functions depending on the problem
2. Functions get more importance than data 2. Data gets more importance than functions
in program. in Program
3. Most of the functions use global data. 3. Each object controls its own data
[Link] data may be transfer from one [Link] does not possible transfer from one
function to another object to another
5. There is no perfect way for data hiding 5. Data hiding possible in OOP which
prevent illegal access of function
from outside of it. This is one of the
best advantages of OOP also.
6. More data or functions can not be added 6. More data or functions can be added with
easily Program very easily
.
7. Top down process is followed for 7. Bottom up process is followed for
program design. program design.
5
Explain java features?
The development team of java wanted the language to be portable, reliable and
distributed but also simple. Apart from above the java has the following features.
Simple
Java inherits the C/C++ syntax and many of the object-oriented features of C++. Also,
some of the more confusing concepts from C++ are eliminated from Java
Object-Oriented
Java designed as pure object oriented language. We require minimum one class to
develop a program. The object model in Java is simple and easy to extend.
Robust
The ability to create robust programs was given a high priority in the design of Java.
Java is a strictly typed language; it checks your code at compile time also at run time.
Java eliminates manually disallocati0n of dynamically allocated memory i.e.
deallocation is completely automatic.
Java provides object-oriented exception handling. In a well-written Java program, all
run-time errors can and should be managed by your program.
Multithreaded
Java supports multithreaded programming, which allows you to write programs that
do many things simultaneously.
This feature greatly improves the interactive performance of graphical and game
applications.
Platform independent and Architecture-Neutral
Java programs can be easily moved from one computer to another , anywhere and
anytime.
The Java Virtual Machine (JVM) made the java language platform independent and
architecture neutral.
Interpreted and High Performance
Java enables the creation of cross-platform programs by compiling into an
intermediate representation called Java bytecode.
The Java bytecode was carefully designed so that it would be easy to translate directly
into native machine code for very high performance by using a just-in-time compiler.
6
Portable:
Java ensures portability in two ways. First java compiler generates bytecode
instructions that can be implemented on any machine. Secondly the size of the
primitive data types are machine – independent.
Distributed
Java is designed for the distributed environment of the Internet, because it handles
TCP/IP protocols
Java included features for intraaddress-space messaging. This allowed objects on two
different computers to execute procedures remotely.
Dynamic
Java programs carry with them substantial amounts of run-time type information that
is used to verify and resolve accesses to objects at run time. This makes it possible to
dynamically link code in a safe and expedient manner.
Security
Java systems not only verify all memory access but also ensure that no viruses are
communicated with an applet . the absence of pointers in java ensures that programs
can not gain access to memory locations.
7
Overview of Java language
Differentiate between C and JAVA?
1. JAVA is Object-Oriented while C is procedural.
2. Java is an Interpreted language while C is a compiled language.
3. C is a low-level language while JAVA is a high-level language.
4. C uses the top-down approach while JAVA uses the bottom-Up approach.
5. JAVA cannot support pointers while C requires explicit handling of pointers.
6. JAVA supports Method Overloading while C does not support overloading at all.
7. Unlike C, JAVA does not support Preprocessors.
8. Exception Handling is strong in JAVA where as in C language very difficult to handle
run time errors.
Explain java environment?
Java environment includes a large number of development tools and hundreds of
classes and methods. The development tools are the part of the system known as Java
Development Kit (JDK) and the classes and methods are the part of Java Standard
Library (JSL) also known as the application Programming Interface (API).
8
[Link] [Link]
[Link] [Link]
[Link] [Link]
9
Documentation Section:
The documentation comprises a set of comment lines giving the name of the program,
the author and other details, which the programmer would like to refer at a latter
stage.
Java supports three types of comments single line comments ( // ), multi line
comments(/*… */) , documentation comments(/** ... */)
Package Statements:
The first statement allowed in java file is a package statement, this statements declares
a package name and informs the compiler that the classes defined here belong to this
package.
package pack_name;
The package statement is optional, that is our classes do not have to be a part of a
package.
Import statement:
The next statement after a package statement may be a number of import statements.
This is similar to the #include statement in C.
import java . lang.
* ; import java . awt .
*;
This statement instructs the interpreter to load the classes contained in the packages
mentioned.
Interface statement:
An interface is like a class but includes a group of method declarations. This is also an
optional statement and is used only when we wish to implement the multiple
inheritance feature in the program. Interface is new concept in the java.
Class Definition:
A java program may contain multiple class definitions. Classes are the primary
essential elements of a java program. The no 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 defined 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.
10
What is byte code?
Bytecode is a highly optimized set of instructions designed to be executed by the Java
run-time system, which is called the Java Virtual Machine (JVM). That is, in its
standard form, the JVM is an interpreter for bytecode.
Bytecode is the result of compiling source code written in a language that supports
this approach.
JAVA JAVA
BYTE CODE
PROGRAM COMPILER
The best-known language today that uses the bytecode is java, LISP , ICON, Prolog.
First of all, the .java program is converted into a .class file consisting of byte code
instructions by the java compiler at the time of compilation.
The JVM exists only inside the computer memory . it is a simulated computer with in
the computer
11
Explain Java Tokens?
A token is the smallest element of a program that is meaningful to the compiler. These tokens
define the structure of the Java language. The compiler recognizes them for building up
expressions and statements. Java tokens can be broken into five categories:
Identifiers
keywords
literals
operators
separators
Keywords:
It is a special type of reserved word for a specific purpose in the program
development.
There are 50 keywords currently defined in the Java language. All the keywords must
be written in lower case
Ex: abstract, byte, class extends, private , protected , case , switch, if , else
Identifiers:
Identifiers are the names given by the programmer to variables, methods, and classes to
identify them to the compiler
The can have letters, numbers, or the underscore( _ ) and dollar-sign($) characters
Must not begin with a number.
Upper case and Lower case letters are distinct.
They can be of any length.
Valid Invalid
HelloWorld Hello World (uses a space)
Hi_JAVA Hi JAVA! (uses a space and punctuation mark)
value3 3value(begins with a number)
Tall short (this is a Java keyword)
$age #age (does not begin with any other symbol except _ $ )
12
Literals:
Literals in java are sequence of characters that represents constant values to be stored
in variables. Java language specifies five major types of literals:
Integer Literals. (10,20)
Floating point literals.(10.234)
Character literals.(„J‟)
String literals. (“java”)
Boolean literals. (true, false)
Operators:
Operator is a special symbol that takes one or more arguments and operates on them
to produce a result. Java provides a rich set of operators to manipulate variables. We
can divide all the Java operators into the following groups:
Arithmetic Operators
Relational Operators
Bitwise Operators
Logical Operators
Assignment Operators
Misc Operators
Separators:
Separators are used to inform the Java compiler of how things are grouped in the
code. For example, items in a list are separated by commas much like lists of items in
a sentence. The most commonly used separator in Java is the semicolon.
Symbol Name
; Semicolon
, Comma
{} Braces
() Parentheses
[] Brackets
. Period
13
Explain how to implement java program?
(OR)
14
double sal;
Assignment statement:
The statement that stores (assigns) a value in a variable. An assignment statement uses
the equal sign (=) as an assignment operator. Like other statements, an assignment
statement ends with a semicolon:
VariableName = Value ;
greeting = "Hello World";
num1 = 50; // (a) Assign 50 to num1
num2 = 10 + 15; // (b) Assign 25 to num2
num1 = num2; // (c) Copy num2's value (25) into num1
Control flow statements
Regulate the order in which statements get executed. We can write statements using
if, switch, loops.
Jump Statements:
Jump statements pass control to the beginning or end of the current block, or to a
labelled statement. The labels must be in the same block.. java supports four types of
jump statements:
break
continue
return
throw
Blocks
A block is a group of zero or more statements between balanced braces and can be
used anywhere a single statement is allowed.
15
Constants, variables, and Data types
Write all about constants?
Constants in java refer to fixed values that do not change during the execution of a
[Link] supports five types of constants:
Integer literals
Floating literals
Character literals
String literal
Boolean literals
Integer literals:
An integer constant refers to a sequence of digits. Java supports three types of integer
literals.
Decimal (Base 10)
Octal (Base 8)
Hexadecimal (Base 16)
Floating-Point Literals
Floating-point numbers represent decimal values with a fractional component. They
can be expressed in either standard or scientific notation.
Floating-point literals in Java default to double precision..
double d1 = 123.4;
double d2 = 1.234e2; // same value as d1, but in scientific notation
float f1 = 123.4f;
Character constants:
A single character constant contains a single character enclosed with in a pair of
single quote marks. Java supports Unicode character set.
String Literals
A string constant is a sequence of characters enclosed between double quotes. The
characters may be alphabets , digits, special characters and blank spaces.
“Hello World”
“two\nlines”
Java string is that they must begin and end on the same line.
16
Boolean Literals
Constants which stores either true or false.
The values of true and false do not convert into any numerical representation. The
true literal in Java does not equal 1, nor does the false literal equal 0.
Java defines eight primitive types of data: byte, short, int, long, char, float, double, and
boolean. The simple types are defined to have an explicit range and mathematical behavior.
These can be put in four groups:
Integers This group includes byte, short, int, and long, which are for whole valued
signed numbers.
17
Floating-point numbers This group includes float and double, which represent
numbers with fractional precision.
Characters This group includes char, which represents symbols in a character set,
like letters and numbers.
Boolean This group includes boolean, which is a special type for representing
true/false values.
Integer types:
Integer types can hold whole numbers such as 123, -90, 5678. The size of the values
that can be stored depends on the integer type we choose. Java supports four types of
integers , they are byte , short, int, long.
We can make integers long by appending the letter L or l at the end of the number
Ex:
123L or 123 l
Floating point types:
This type holds numbers containing fractional parts such as 27.68 and -1.342. java
supports two types of floating point storage float (single precision), double (double
precision)
18
By default all floating point numbers are double precision numbers. To make them
single precision numbers append f or F
Ex:
1.23 F
Type Size (bytes) Range
float 4 3.4 e -38 To 1.7 e+38
double 8 3.4e-38 To 1.7 e+308
Character type:
In order to store character constants in memory , java provides a character data type
called “char” . Java supports Unicode format of characters i.e. it can support 65536 no
of characters. It occupies 2 bytes of memory.
19
initializer. In addition, all variables have a scope, which defines their visibility, and a
lifetime.
Declaring a Variable
In Java, all variables must be declared before they can be used. The basic form of a
variable declaration is shown here:
type identifier [ = value][, identifier [= value] ...] ;
To declare more than one variable of the specified type, use a comma-separated list
Ex:
int m1,m2,m3;
Initializing Variables
You can initialize the variable by specifying an equal sign(assignment operator) and a
value. The initialization expression must result in a value of the same (or compatible)
type as that specified for the variable.
byte z = 22; // initializes z.
double pi = 3.14159; // declares an approximation of pi.
char x = 'x'; // the variable x has the value 'x'.
Dynamic Initialization
Java allows variables to be initialized dynamically, using any expression valid at the
time the variable is declared.
double a = 3.0, b = 4.0;
double c = [Link](a * a + b * b); // c is dynamically initialized
20
What is a default value of a variable?
It's not always necessary to assign a value when a field is declared. Fields that are
declared but not initialized will be set to a reasonable default by the compiler.
Data Type Default Value (for fields)
byte 0
short 0
int 0
long 0L
float 0.0f
double 0.0d
char '\u0000'
String (or any object) null
boolean false
The compiler never assigns a default value to an uninitialized local variable.
21
2. Explicit casting (narrowing conversion)
A data type of higher size (occupying more memory) cannot be assigned to a data
type of lower size. This is not done implicitly by the JVM and requires explicit
casting; a casting operation to be performed by the programmer. The higher size is
narrowed to lower size.
Syn: type variable1 = (type) variable2
double x = 10.5;
int y = (int) x;
A boolean value cannot be assigned to any other data type. Except boolean, all the
remaining 7 data types can be assigned to one another either implicitly or explicitly;
but boolean cannot.
class cast_ex{
public static void main (String args[ ] ){
float x =254.01f;
byte b;
b = (byte) x ; /*type conversion*/
[Link]( " 'value of b ' "+b);
}}
22
Explain all about operators?
Operator is special symbol which performs a specific operation the operands. An
operator takes one or more arguments and produces a new value. All operators
produce a value from their operands. In addition, an operator can change the value of
an operand. This is called a side effect. Operators can be categorised into two ways
Based on no of operands
Based on type of operation
Based on no of operands that an operator requires to perform its operation the
operators are three types
Unary operators
Binary operators
Ternary operators
Based on type of operation that an operator performs the operators are
1. Arithmetic Operators.
2. Relational Operators.
3. Logical Operators.
4. Assignment Operators.
5. Increment, Decrement Operators.
6. Conditional Operators.
7. Bitwise Operators.
8. Special Operators.
Arithmetic Operators:
Arithmetic operators are used to construct mathematical expressions as in algebra.
Java provides all the basic arithmetic operators.
+ Addition
- Subtraction
* Multiplication
/ Division
% modulo division
These can operate on any built in numeric data type of java. We cannot use these operators on
boolean data types. All these are binary operators.
23
Relational operators
Relational operators generate a boolean result and binary operators. They evaluate the
relationship between the values of the operands.. The relational operators are
< Less than,
> Greater than,
<= Less than or equal to
>= Greater than or equal to
== Equivalent
!= Not equivalent
A simple relational expression contains only one relational operator and is of the
following form:
Op1 Relational Operator Op2
Ex:
a > b
Logical Operators:
The logical operators are used to form compound conditions by combining two or
more relations. The logical expressions also give a value of true or false according to
the truth [Link] supports three types of logical operators:
&& Logical AND
|| Logical OR
! Logical NOT
Truth Table:
A B A || B A && B !A
false false false false true
true false true false false
false true true false true
true true true true false
Bitwise operators
The bitwise operators allow you to manipulate individual bits in an integral primitive
data type. Java the following bit wise operators :
bitwise AND operator ( & )
bitwise OR operator ( | )
24
bitwise, EXCLUSIVE OR, or XOR ( ^ )
bitwise NOT ( ~ )
Assignment Operator
The assignment operator is the single equal sign, =. The assignment operator works in
Java much as it does in any other computer language. It has this general form:
var = expression;
Conditional Operator:
Java includes a special ternary (three-way) operator that can replace certain types of if-else
statements. The ? : has this general form:
Here, exp1 can be any expression that evaluates to a boolean value. If exp1 is true, then exp2
is evaluated; otherwise, exp3 is evaluated.
Shift operators
The shift operators also manipulate bits. They can be used solely with primitive,
integral types.
left-shift operator (<<)
right-shift operator (>>)
SPECIAL OPERATORS
Java supports some special operations of interest such as instanceof operator and
member selection operator( . ) and comma operator.
25
What is an Operator Precedence and Associativity?
Each operator in java has a precedence associated with it. This precedence is used to
determine how an expression involving more than one operator is evaluated. The operators of
the same precedence are evaluated either from left to right or from right to left depending on
the level.
26