UNIT-1 OBJECT ORIENTED THINKING: Need For OOP Paradigm, OOP Concepts
UNIT-1 OBJECT ORIENTED THINKING: Need For OOP Paradigm, OOP Concepts
Java History:
• Computer language innovation and development occurs for two fundamental reasons:
1) to adapt to changing environments and uses
2) to implement improvements in the art of programming
• The development of Java was driven by both in equal measures.
• Many Java features are inherited from the earlier languages:
B C C++ Java
Before Java: C
• Designed by Dennis Ritchie in 1970s.
• Before C: BASIC, COBOL, FORTRAN, PASCAL
• C- structured, efficient, high-level language that could replace assembly code when
creating systems programs.
• Designed, implemented and tested by programmers.
Before Java: C++
• Designed by Bjarne Stroustrup in 1979.
• Response to the increased complexity of programs and respective improvements in
the programming paradigms and methods:
1) assembler languages
2) high-level languages
3) structured programming
4) object-oriented programming (OOP)
• OOP – methodology that helps organize complex programs through the use of
inheritance, encapsulation and polymorphism.
• C++ extends C by adding object-oriented features.
Java: History:
• In 1990, Sun Microsystems started a project called Green.
• Objective: to develop software for consumer electronics.
• Project was assigned to James Gosling, a veteran of classic network software design.
Others included Patrick Naughton, ChrisWarth, Ed Frank, and Mike Sheridan.
• The team started writing programs in C++ for embedding into toasters, washing
machines, VCR’s
• Aim was to make these appliances more “intelligent”.
• C++ is powerful, but also dangerous. The power and popularity of C derived from the
extensive use of pointers. However, any incorrect use of pointers can cause memory
leaks, leading the program to crash.
• In a complex program, such memory leaks are often hard to detect.
• Robustness is essential. Users have come to expect that Windows may crash or that a
program running under Windows may crash. (“This program has performed an illegal
operation and will be shut down”)
• However, users do not expect toasters to crash, or washing machines to crash.
• A design for consumer electronics has to be robust.
• Replacing pointers by references, and automating memory management was the
proposed solution.
• Hence, the team built a new programming language called Oak, which avoided
potentially dangerous constructs in C++, such as pointers, pointer arithmetic, operator
overloading etc.
• Introduced automatic memory management, freeing the programmer to concentrate on
other things.
• Architecture neutrality (Platform independence)
• Many different CPU’s are used as controllers. Hardware chips are evolving rapidly.
As better chips become available, older chips become obsolete and their production is
stopped. Manufacturers of toasters and washing machines would like to use the chips
available off the shelf, and would not like to reinvest in compiler development every
two-three years.
• So, the software and programming language had to be architecture neutral.
• It was soon realized that these design goals of consumer electronics perfectly suited
an ideal programming language for the Internet and WWW, which should be:
• object-oriented (& support GUI)
• – robust
• – architecture neutral
• Internet programming presented a BIG business opportunity. Much bigger than
programming for consumer electronics.
• Java was “re-targeted” for the Internet
• The team was expanded to include Bill Joy (developer of Unix), Arthur van Hoff,
Jonathan Payne, Frank Yellin, Tim Lindholm etc.
• In 1994, an early web browser called WebRunner was written in Oak. WebRunner
was later renamed HotJava.
• In 1995, Oak was renamed Java.
• A common story is that the name Java relates to the place from where the
development team got its coffee. The name Java survived the trade mark search.
• Designed by James Gosling, Patrick Naughton, Chris Warth, Ed Frank and Mike
Sheridan at Sun Microsystems in 1991.
• The original motivation is not Internet: platform-independent software embedded in
consumer electronics devices.
• With Internet, the urgent need appeared to break the fortified positions of Intel,
Macintosh and Unix programmer communities.
• Java as an “Internet version of C++”? No.
• Java was not designed to replace C++, but to solve a different set of problems.
The Java Buzzwords
• The key considerations were summed up by the Java team in the following list of
buzzwords:
Simple
Secure
Portable
Object-oriented
Robust
Multithreaded
Architecture-neutral
Interpreted
High performance
Distributed
Dynamic
• simple – Java is designed to be easy for the professional programmer to learn and use.
• object-oriented: a clean, usable, pragmatic approach to objects, not restricted by the
need for compatibility with other languages.
• Robust: restricts the programmer to find the mistakes early, performs compile-time
(strong typing) and run-time (exception-handling) checks, manages memory
automatically.
• Multithreaded: supports multi-threaded programming for writing program that
perform concurrent computations
• Architecture-neutral: Java Virtual Machine provides a platform independent
environment for the execution of Java byte code
• Interpreted and high-performance: Java programs are compiled into an
intermediate representation – byte code:
a) can be later interpreted by any JVM
b) can be also translated into the native machine code for efficiency.
• Distributed: Java handles TCP/IP protocols, accessing a resource through its URL
much like accessing a local file.
• Dynamic: substantial amounts of run-time type information to verify and resolve
access to objects at run-time.
• Secure: programs are confined to the Java execution environment and cannot access
other parts of the computer.
• Portability: Many types of computers and operating systems are in use throughout
the world—and many are connected to the Internet.
• For programs to be dynamically downloaded to all the various types of platforms
connected to the Internet, some means of generating portable executable code is
needed. The same mechanism that helps ensure security also helps create portability.
• Indeed, Java's solution to these two problems is both elegant and efficient.
Data Types
• Java defines eight simple types:
1)byte – 8-bit integer type
2)short – 16-bit integer type
3)int – 32-bit integer type
4)long – 64-bit integer type
5)float – 32-bit floating-point type
6)double – 64-bit floating-point type
7)char – symbols in a character set
8)boolean – logical values true and false
• byte: 8-bit integer type.
Range: -128 to 127.
Example: byte b = -15;
Usage: particularly when working with data streams.
• short: 16-bit integer type.
Range: -32768 to 32767.
Example: short c = 1000;
Usage: probably the least used simple type.
• int: 32-bit integer type.
Range: -2147483648 to 2147483647.
Example: int b = -50000;
Usage:
1) Most common integer type.
2) Typically used to control loops and to index arrays.
3) Expressions involving the byte, short and int values are promoted to int before
calculation.
• long: 64-bit integer type.
Range: -9223372036854775808 to 9223372036854775807.
Example: long l = 10000000000000000;
Usage: 1) useful when int type is not large enough to hold the desired value
• float: 32-bit floating-point number.
Range: 1.4e-045 to 3.4e+038.
Example: float f = 1.5;
Usage:
1) fractional part is needed
2) large degree of precision is not required
• double: 64-bit floating-point number.
Range: 4.9e-324 to 1.8e+308.
Example: double pi = 3.1416;
Usage:
1) accuracy over many iterative calculations
2) manipulation of large-valued numbers
char: 16-bit data type used to store characters.
Range: 0 to 65536.
Example: char c = ‘a’;
Usage:
1) Represents both ASCII and Unicode character sets; Unicode defines a
character set with characters found in (almost) all human languages.
2) Not the same as in C/C++ where char is 8-bit and represents ASCII only.
• boolean: Two-valued type of logical values.
Range: values true and false.
Example: boolean b = (1<2);
Usage:
1) returned by relational operators, such as 1<2
2) required by branching expressions such as if or for
Variables::
• declaration – how to assign a type to a variable
• initialization – how to give an initial value to a variable
• scope – how the variable is visible to other parts of the program
• lifetime – how the variable is created, used and destroyed
• type conversion – how Java handles automatic type conversion
• type casting – how the type of a variable can be narrowed down
• type promotion – how the type of a variable can be expanded
• Java uses variables to store data.
• To allocate memory space for a variable JVM requires:
1) to specify the data type of the variable
2) to associate an identifier with the variable
3) optionally, the variable may be assigned an initial value
• All done as part of variable declaration.
• Scope determines the visibility of program elements with respect to other program
elements.
• In Java, scope is defined separately for classes and methods:
1) variables defined by a class have a global scope
2) variables defined by a method have a local scope
Variable Lifetime::
• Variables are created when their scope is entered by control flow and destroyed when
their scope is left:
• A variable declared in a method will not hold its value between different invocations
of this method.
• A variable declared in a block looses its value when the block is left.
• Initialized in a block, a variable will be re-initialized with every re-entry. Variables
lifetime is confined to its scope!
Arrays::
• An array is a group of liked-typed variables referred to by a common
• name, with individual variables accessed by their index.
• Arrays are:
1) declared
2) created
3) initialized
4) used
• Also, arrays can have one or several dimensions.
Array Declaration
• Array declaration involves:
1) declaring an array identifier
2) declaring the number of dimensions
3) declaring the data type of the array elements
• Two styles of array declaration:
type array-variable[]; or type [] array-variable;
Array Creation
• After declaration, no array actually exists.
• In order to create an array, we use the new operator:
type array-variable[];
array-variable = new type[size];
• This creates a new array to hold size elements of type type, which reference will be
kept in the variable array-variable.
Array Indexing
• Later we can refer to the elements of this array through their indexes:
• array-variable[index]
• The array index always starts with zero!
• The Java run-time system makes sure that all array indexes are in the correct range,
otherwise raises a run-time error.
Array Initialization
• Arrays can be initialized when they are declared:
• int monthDays[] = {31,28,31,30,31,30,31,31,30,31,30,31};
• Note:
1) there is no need to use the new operator
2) the array is created large enough to hold all specified elements
Multidimensional Arrays:
• Multidimensional arrays are arrays of arrays:
1) declaration: int array[][];
2) creation: int array = new int[2][3];
3) initialization
int array[][] = { {1, 2, 3}, {4, 5, 6} };
Operators Types::
• Java operators are used to build value expressions.
• Java provides a rich set of operators:
1) assignment
2) arithmetic
3) relational
4) logical
5) bitwise
Arithmetic assignments
+= v += expr; v = v + expr ;
-= v -=expr; v = v - expr ;
*= v *= expr; v = v * expr ;
/= v /= expr; v = v / expr ;
%= v %= expr; v = v % expr ;
Relational operator
== Equals to Apply to any type
Logical operators
& op1 & op2 Logical AND
! ! op Logical NOT
>> op1 >> op2 Shifts all bits in op1 right by the value of
op2
<< op1 << op2 Shifts all bits in op1 left by the value of
op2
Expressions::
• An expression is a construct made up of variables, operators, and method invocations,
which are constructed according to the syntax of the language, that evaluates to a
single value.
• Examples of expressions are in bold below:
int number = 0;
anArray[0] = 100;
System.out.println ("Element 1 at index 0: " + anArray[0]);
int result = 1 + 2; // result is now 3 if(value1 == value2)
System.out.println("value1 == value2");
• The data type of the value returned by an expression depends on the elements used in
the expression.
• The expression number = 0 returns an int because the assignment operator returns a
value of the same data type as its left-hand operand; in this case, number is an int.
• As you can see from the other expressions, an expression can return other types of
values as well, such as boolean or String.
• The Java programming language allows you to construct compound expressions from
various smaller expressions as long as the data type required by one part of the
expression matches the data type of the other.
• Here's an example of a compound expression: 1*2*3
Control Statements
• Java control statements cause the flow of execution to advance and branch based on
the changes to the state of the program.
• Control statements are divided into three groups:
• 1) selection statements allow the program to choose different parts of the execution
based on the outcome of an expression
• 2) iteration statements enable program execution to repeat one or more statements
• 3) jump statements enable your program to execute in a non-linear fashion
Selection Statements
• Java selection statements allow to control the flow of program’s execution based upon
conditions known only during run-time.
• Java provides four selection statements:
1) if
2) if-else
3) if-else-if
4) switch
Iteration Statements
• Java iteration statements enable repeated execution of part of a program until a certain
termination condition becomes true.
• Java provides three iteration statements:
1) while
2) do-while
3) for
Jump Statements
• Java jump statements enable transfer of control to other parts of program.
• Java provides three jump statements:
1) break
2) continue
3) return
• In addition, Java supports exception handling that can also alter the control flow of a
program.
Type Conversion
• Size Direction of Data Type
– Widening Type Conversion (Casting down)
• Smaller Data Type Larger Data Type
– Narrowing Type Conversion (Casting up)
• Larger Data Type Smaller Data Type
• Conversion done in two ways
– Implicit type conversion
• Carried out by compiler automatically
– Explicit type conversion
• Carried out by programmer using casting
• Widening Type Converstion
– Implicit conversion by compiler automatically
• Narrowing Type Conversion
– Programmer should describe the conversion explicitly
String Handling
• String is probably the most commonly used class in Java's class library. The obvious
reason for this is that strings are a very important part of programming.
• The first thing to understand about strings is that every string you create is actually an
object of type String. Even string constants are actually String objects.
• For example, in the statement
System.out.println("This is a String, too");
the string "This is a String, too" is a String constant
• Java defines one operator for String objects: +.
• It is used to concatenate two strings. For example, this statement
• String myString = "I" + " like " + "Java.";
results in myString containing
"I like Java."
• The String class contains several methods that you can use. Here are a few. You can
• test two strings for equality by using
equals( ). You can obtain the length of a string by calling the length( ) method. You
can obtain the character at a specified index within a string by calling charAt( ). The general
forms of these three methods are shown here:
• // Demonstrating some String methods.
class StringDemo2 {
public static void main(String args[]) {
String strOb1 = "First String";
String strOb2 = "Second String";
String strOb3 = strOb1;
System.out.println("Length of strOb1: " +
strOb1.length());
System.out.println ("Char at index 3 in strOb1: " +
strOb1.charAt(3));
if(strOb1.equals(strOb2))
System.out.println("strOb1 == strOb2");
else
System.out.println("strOb1 != strOb2");
if(strOb1.equals(strOb3))
System.out.println("strOb1 == strOb3");
else
System.out.println("strOb1 != strOb3");
}}
This program generates the following output:
Length of strOb1: 12
Char at index 3 in strOb1: s
strOb1 != strOb2
strOb1 == strOb3
The String class is defined in the java.lang package and hence is implicitly available to all the
programs in Java. The String class is declared as final, which means that it cannot be
subclassed. It extends the Object class and implements the Serializable, Comparable, and
CharSequence interfaces.
Java implements strings as objects of type String. A string is a sequence of characters. Unlike
most of the other languages, Java treats a string as a single value rather than as an array of
characters.
The String objects are immutable, i.e., once an object of the String class is created, the string
it contains cannot be changed. In other words, once a String object is created, the characters
that comprise the string cannot be changed. Whenever any operation is performed on a String
object, a new String object will be created while the original contents of the object will
remain unchanged. However, at any time, a variable declared as a String reference can be
changed to point to some other String object.
Though there could be many possible answer for this question and only designer of String
class can answer this, I think below three does make sense
1) Imagine StringPool facility without making string immutable, its not possible at all
because in case of string pool one string object/literal e.g. "Test" has referenced by many
reference variables , so if any one of them change the value others will be automatically gets
affected i.e. lets say
String A = "Test"
String B = "Test"
Now String B called "Test".toUpperCase() which change the same object into "TEST" , so A
will also be "TEST" which is not desirable.
2) String has been widely used as parameter for many java classes e.g. for opening network
connection you can pass hostname and port number as stirng , you can pass database URL as
string for opening database connection, you can open any file by passing name of file as
argument to File I/O classes.
In case if String is not immutable, this would lead serious security threat , I mean some one
can access to any file for which he has authorization and then can change the file name either
deliberately or accidentally and gain access of those file.
3) Since String is immutable it can safely shared between many threads, which is very
important for multithreaded programming.
String
Creating Strings:
We can declare a String variable and directly store a String literal using assignment
operator.
We can create String object using new operator with some data.
Here starting from 2nd character a total of 3 characters are copied into String s3.
String represents a sequence of characters. It has fixed length of character sequence. Once a
string object has been created than we can't change the character that comprise that string. It
is immutable. This allows String to be shared. String object can be instantiated like any other
object
The String class defines several constructors. The most common constructor of the String
class is the one given below:
This constructor constructs a new String object initialized with the same sequence of the
characters passed as the argument. In other words, the newly created String object is the copy
of the string passed as an argument to the constructor.
public String()
This constructor creates an empty String object. However, the use of this constructor is
unnecessary because String objects are immutable.
This constructor creates a new String object initialized with the same sequence of characters
currently contained in the array that is passed as the argument to it.
This constructor creates a new String object initialized with the same sequence of characters
currently contained in the subarray. This subarray is derived from the character array and the
two integer values that are passed as arguments to the constructor. The int variable startindex
represents the index value of the starting character of the subarray, and the int variable len
represents the number of characters to be used to form the new String object.
public String(StringBuffer sbf)
This constructor creates a new String object that contains the same sequence of characters
currently contained in the string buffer argument.
The array of bytes that is passed as an argument to the constructor contains the ASCII
character set. Therefore, this array of bytes is first decoded using the default charset of the
platform. Then the constructor creates a new String object initialized with same sequence of
characters obtained after decoding the array.
This constructor creates the String object after decoding the array of bytes and by using the
subarray of bytes.
StringBuffer
StringBuffer: StringBuffer objects are mutable, so they can be modified. The methods
that directly manipulate data of the object are available in StringBuffer class.
Creating StringBuffer:
We can create a StringBuffer object by using new operator and pass the string to the
object, as: StringBuffer sb = new StringBuffer ("Kiran");
We can create a StringBuffer object by first allotting memory to the
StringBuffer object using new operator and later storing the String into it as:
In general a StringBuffer object will be created with a default capacity of 16 characters. Here,
StringBuffer object is created as an empty object with a capacity for storing 30 characters.
Even if we declare the capacity as 30, it is possible to store more than 30 characters into
StringBuffer.
Sb.append (“Kiran”);
import java.io.*;
class Mutable
String sur=br.readLine ( );
String mid=br.readLine ( );
String last=br.readLine ( );
sb.append (sur);
sb.append (last);
Output:
3. String has concat() for append character but StringBuffer has append() method
4. while you create String like String str = new String(); it create 2 object 1 on heap and 1 on
String Constant pool and that refered by str but in StringBuffer it Create 1 object on heap
StringBuilder
StringBuilder class is introduced in Java 5.0 version. This class is an alternative to the
existing StringBuffer class. If you look into the operations of the both the classes, there is no
difference. The only difference between StringBuilder and StringBuffer is that StringBuilder
class is not synchronized so it gives better performance. Whenever there are no threading
issues, its preferable to use StringBuilder. StringBuffer class can be replaced by StringBuilder
with a simple search and replace with no compilation issue.
java.lang
Class StringBuilder
java.lang.Object
java.lang.StringBuilder
All Implemented Interfaces:
The principal operations on a StringBuilder are the append and insert methods, which
are overloaded so as to accept data of any type. Each effectively converts a given datum to a
string and then appends or inserts the characters of that string to the string builder. The
append method always adds these characters at the end of the builder; the insert method
adds the characters at a specified point.
For example, if z refers to a string builder object whose current contents are "start", then
the method call z.append("le") would cause the string builder to contain "startle",
whereas z.insert(4, "le") would alter the string builder to contain "starlet".
Instances of StringBuilder are not safe for use by multiple threads. If such synchronization
is required then it is recommended that StringBuffer be used.
Constructor Summary
StringBuilder()
Constructs a string builder with no characters in it and an initial capacity of 16
characters.
StringBuilder(CharSequence seq)
Constructs a string builder that contains the same characters as the specified
CharSequence.
StringBuilder(int capacity)
Constructs a string builder with no characters in it and an initial capacity specified by
the capacity argument.
StringBuilder(String str)
Constructs a string builder initialized to the contents of the specified string.
Method Summary
StringBuilder append(boolean b)
Appends the string representation of the boolean argument to the
sequence.
StringBuilder append(char c)
Appends the string representation of the char argument to this
sequence.
StringBuilder append(CharSequence s)
Appends the specified character sequence to this Appendable.
StringBuilder append(double d)
Appends the string representation of the double argument to this
sequence.
StringBuilder append(float f)
Appends the string representation of the float argument to this
sequence.
StringBuilder append(int i)
Appends the string representation of the int argument to this
sequence.
int capacity()
Returns the current capacity.
char charAt(int index)
Returns the char value in this sequence at the specified index.
int length()
Returns the length (character count).
StringBuilder reverse()
Causes this character sequence to be replaced by the reverse of the
sequence.
void trimToSize()
Attempts to reduce storage used for the character sequence.
StringTokenizer: The StringTokenizer class is useful to break a String into small pieces
called tokens. We can create an object to StringTokenizer as:
StringTokenizer st = new StringTokenizer (str, "delimeter");
Output: