0% found this document useful (0 votes)
91 views33 pages

Lecture Notes: Module-2: Subject: Object Oriented Concepts Course Code: 18CS45 Semester: 4

This document provides lecture notes on object oriented concepts for a 4th semester computer science course. The notes cover topics like classes and objects, arrays of objects, arrays inside objects, namespaces, nested classes, constructors, destructors, and the history and evolution of Java. The notes are prepared by an assistant professor in the department of computer science and engineering.

Uploaded by

Jugal Alan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
91 views33 pages

Lecture Notes: Module-2: Subject: Object Oriented Concepts Course Code: 18CS45 Semester: 4

This document provides lecture notes on object oriented concepts for a 4th semester computer science course. The notes cover topics like classes and objects, arrays of objects, arrays inside objects, namespaces, nested classes, constructors, destructors, and the history and evolution of Java. The notes are prepared by an assistant professor in the department of computer science and engineering.

Uploaded by

Jugal Alan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

LECTURE NOTES : MODULE-2

Subject: Object Oriented Concepts


Course Code : 18CS45
Semester : 4

Prepared by:
Mr Nithin Kumar Heraje
Asst Professor
Dept of CSE.
Object Oriented Concepts MODULE 2 18CS45

Class and Objects (contd): Objects and arrays, Namespaces, Nested classes, Constructors, Destructors.
Introduction to Java: Java’s magic: the Byte code; Java Development Kit (JDK); the Java Buzzwords, Object-
oriented programming; Simple Java programs. Data types, variables and arrays, Operators, Control
Statements.

1.8 Objects and Arrays


Arrays of Objects:
We can create arrays of objects. The following program shows how.

Arrays Inside Objects


An array can be declared inside a class. Such an array becomes a member of all objects of the
class. It can be manipulated/accessed by all member functions of the class.

Dept. of CSE, AJIET, Mangaluru Page 1


Object Oriented Concepts MODULE 2 18CS45

The class definition is self-explanatory. However, the comments indicate that it is better to
throw exceptions rather than terminate the function.

1.9 Namespaces
Namespaces enable the C++ programmer to prevent pollution of the global namespace that
leads to name clashes.
The term ‗global namespace‘ refers to the entire source code. It also includes all the directly
and indirectly included header files. By default, the name of each class is visible in the entire
source code, that is, in the global namespace.
Suppose a class with the same name is defined in two header files.

Now, let us include both these header ¿ les in a program and see what happens if we declare
an object of the class.

Dept. of CSE, AJIET, Mangaluru Page 2


Object Oriented Concepts MODULE 2 18CS45

The global visibility of the definition of class A makes the inclusion of the two header ¿ les
mutually exclusive. Consequently, this also makes use of the two definitions of class A
mutually exclusive. How can this problem be overcome? How can we ensure that an
application is able to use both definitions of class A simultaneously? Enclosing the two
definitions of the class in separate namespaces overcomes this problem.

Now, the two definitions of the class are enveloped in two different namespaces. The
corresponding namespace, followed by the scope resolution operator, must be prefixed to the
name of the class while referring to it anywhere in the source code. Thus, the ambiguity
encountered in the above listing can be overcome.

1.10 Nested Inner Classes


A class can be defined inside another class. Such a class is known as a nested class. The
class that contains the nested class is known as the enclosing class. Nested classes can be
defined in the private, protected, or public portions of the enclosing class (protected access
specifier is explained in the chapter on inheritance).

Dept. of CSE, AJIET, Mangaluru Page 3


Object Oriented Concepts MODULE 2 18CS45

How are the member functions of a nested class defined?


Member functions of a nested class can be defined outside the definition of the enclosing
class. This is done by prefixing the function name with the name of the enclosing class
followed by the scope resolution operator. This, in turn, is followed by the name of the nested
class followed again by the scope resolution operator.

1.11 Constructors
The constructor gets called automatically for each object that has just got created. It appears
as member function of each class, whether it is de¿ ned or not. It has the same name as that of
the class. It may or may not take parameters. It does not return anything (not even void). The
prototype of a constructor is
<class name> (<parameter list>);
Domain constraints on the values of data members can also be implemented via constructors.
For example, we want the value of data member inches of each object of the class Distance to
be between 0.0 and 12.0 at all times within the lifetime of the object. But this condition may
get violated in case an object has just got created. However, introducing a suitable constructor
to the class Distance can enforce this condition.
The compiler embeds a call to the constructor for each object when it is created. Suppose a
class A has been declared as follows:

Dept. of CSE, AJIET, Mangaluru Page 4


Object Oriented Concepts MODULE 2 18CS45

Constructor gets called automatically for each object when it is created

Zero-argument Constructor
We can and should de¿ ne our own constructors if the need arises. If we do so, the compiler
does not de¿ ne the constructor. However, it still embeds implicit calls to the constructor as
before. The constructor is a non-static member function. It is called for an object. It,
therefore, takes the this pointer as a leading formal argument just like other non-static
member functions. Correspondingly, the address of the invoking object is passed as a leading
parameter to the constructor call. This means that the members of the invoking object can be
accessed from within the definition of the constructor.
Parameterized Constructors
Constructors take arguments and can, therefore, be overloaded. Suppose, for the class
Distance, the library programmer decides that while creating an object, the application
programmer should be able to pass some initial values for the data members contained in the
object. For this, he/she can create a parameterized constructor

Explicit Constructors
Constructors are declared explicit by prefixing their declarations with the explicit keyword.
Let us first look at the syntax for declaring an explicit constructor

Copy Constructor
The copy constructor is a special type of parameterized constructor. As its name implies, it
copies one object to another. It is called when an object is created and equated to an existing
object at the same time. The copy constructor is called for the object being created. The

Dept. of CSE, AJIET, Mangaluru Page 5


Object Oriented Concepts MODULE 2 18CS45

preexisting object is passed as a parameter to it. The copy constructor member-wise copies
the object passed as a parameter to it into the object for which it is called.
The prototype and the definition of the default copy constructor defined by the compiler are
as follows

1.12 Destructors
The destructor gets called for each object that is about to go out of scope. It appears as a
member function of each class whether we de¿ ne it or not. It has the same name as that of
the class but prefixed with a tilde sign. It does not take parameters. It does not return anything
(not even void). The prototype of a destructor is
~<class name> ();
There is a need for a function that guarantees deinitialization of member data of a class and
frees up the resources acquired by the object during its lifetime, Destructors fulfil this need.

An example of a compiler-defined destructor follows.

A user-defined destructor

Dept. of CSE, AJIET, Mangaluru Page 6


Object Oriented Concepts MODULE 2 18CS45

The History and Evolution of Java


To fully understand Java, one must understand the reasons behind its creation, the
forces that shaped it, and the legacy that it inherits.
Although Java has become inseparably linked with the online environment of the Internet, it
is important to remember that Java is first and fore most a programming language. Computer
language innovation and development occurs for two fundamental reasons:
• To adapt to changing environments and uses
• To implement refinements and improvements in the art of programming

Java’s Lineage
Java is related to C++, which is a direct descendant of C. Much of the character of
Java is inherited from these two languages. From C, Java derives its syntax. Many of Java‘s
object-oriented features were influenced by C++.

The Birth of Modern Programming: C


Invented and first implemented by Dennis Ritchie on a DEC PDP-11 running the
UNIX operating system, C was the result of a development process that started with an older
language called BCPL, developed by Martin Richards. BCPL influenced a language called B,
invented by Ken Thompson, which led to the development of C in the 1970s. For many years,
the de facto standard for C was the one supplied with the UNIX operating system and
described in The C Programming Language by Brian Kernighan and Dennis Ritchie
(Prentice-Hall, 1978). C was formally standardized in December 1989, when the American
National Standards Institute (ANSI) standard for C was adopted.

C++: The Next Step


Although C is one of the world‘s great programming languages, there is a limit to its
ability to handle complexity. Once the size of a program exceeds a certain point, it becomes
so complex that it is difficult to grasp as a totality. While the precise size at which this occurs
differs, depending upon both the nature of the program and the programmer, there is always a

Dept. of CSE, AJIET, Mangaluru Page 7


Object Oriented Concepts MODULE 2 18CS45

threshold at which a program becomes unmanageable. C++ added features that enabled this
threshold to be broken, allowing programmers to comprehend and manage larger programs.

C++was invented by Bjarne Stroustrupin1979,while he was working at Bell Laboratories in


Murray Hill, New Jersey. Stroustrup initially called the new language ―C with Classes.‖
However, in 1983, the name was changed to C++. C++ extends C by adding object-oriented
features. Because C++ is built on the foundation of C, it includes all of C‘s features,
attributes, and benefits. This is a crucial reason for the success of C++ as a language. The
invention of C++ was not an attempt to create a completely new programming language.
Instead, it was an enhancement to an already highly successful one.

The Creation of Java


Java was conceived by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and
Mike Sheridan at Sun Microsystems, Inc. in 1991. It took 18 months to develop the first
working version. This language was initially called ―Oak,‖ but was renamed ―Java‖ in
1995the primarymotivationwastheneedforaplatform-independent(thatis,architecture-neutral)
languagethatcouldbeusedtocreatesoftwaretobeembeddedinvariousconsumerelectronic
devices,suchasmicrowaveovensandremotecontrols.

,theprimarymotivationwastheneedforaplatform-independent(thatis,architecture-neutral)
languagethatcouldbeusedtocreatesoftwaretobeembeddedinvariousconsumerelectronic
devices,suchasmicrowaveovensandremotecontrols.
This second force was, of course, the World Wide Web. Had the Web not taken shape at
about the same time that Java was being implemented, Java might have remained a useful but
obscure language for programming consumer electronics. However, with the emergence of
the World Wide Web, Java was propelled to the forefront of computer language design,
because the Web, too, demanded portable programs.

The C# Connection
Perhaps the most important example of Java‘s influence is C#. Created by Microsoft to
support the .NET Framework, C# is closely related to Java. For example, both share the same
general syntax, support distributed programming, and utilize the same object model. There
are, of course, differences between Java and C#, but the overall ―look and feel‖ of these
languages is very similar. This ―cross-pollination‖ from Java to C# is the strongest
testimonialtodatethatJavaredefinedthewaywethinkaboutanduseacomputerlanguage.

How Java Changed the Internet


The Internet helped catapult Java to the forefront of programming, and Java, in turn, had a
profound effect on the Internet. Java also addressed some of the thorniest issues
associatedwiththeInternet:portabilityandsecurity.

Java Applets
An applet is a special kind of Java program that is designed to be transmitted over the
Internet and automatically executed by a Java-compatible web browser. Furthermore, an
applet is downloaded on demand, without further interaction with the user. If the user clicks a
link that contains an applet, the applet will be automatically downloaded and run in the
browser. Applets are intended to be small programs. They are typically used to display data
provided by the server, handle user input, or provide simple functions, such as a loan
calculator, that execute locally, rather than on the server. In essence, the applet allows some
functionality to be moved from the server to the client.

Dept. of CSE, AJIET, Mangaluru Page 8


Object Oriented Concepts MODULE 2 18CS45

Security
In order for Java to enable applets to be downloaded and executed on the client computer
safely, it was necessary to prevent an applet from launching such an attack.
JavaachievedthisprotectionbyconfininganapplettotheJavaexecutionenvironment and not
allowing it access to other parts of the computer. The ability to download applets with
confidence that no harm will be done and that no security will be breached is considered by
many to be the single most innovative aspect of Java.

Portability
If a Java program were to be run on virtually any computer connected to the Internet, there
needed to be some way to enable that program to execute on different systems.

Java’s Magic: The Bytecode


ThekeythatallowsJavatosolveboththesecurityandtheportabilityproblemsjustdescribed is that
the output of a Java compiler is not executable code. Rather, it is bytecode. 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).

Servlets: Java on the Server Side

A servlet is a small program that executes on the server.


Just as applets dynamically extend the functionality of a web browser, servlets dynamically
extend the functionality of a web server.
Servlets are used to create dynamically generated content that is then served to the client.
For example, an online store might use a servlet to look up the price for an item in a database.
The price information is then used to dynamically generate a web page that is sent to the
browser.
Servlets increases performance.
Because servlets (like all Java programs) are compiled into bytecode and executed by the
JVM, they are highly portable. Thus, the same servlet can be used in a variety of different
server environments.

The Java Buzzwords

Dept. of CSE, AJIET, Mangaluru Page 9


Object Oriented Concepts MODULE 2 18CS45

• Simple
• Secure
• Portable
• Object-oriented
• Robust
• Multithreaded
• Architecture-neutral
• Interpreted
• High performance
• Distributed
• Dynamic

Simple
 Java was designed to be easy for the professional programmer to learn and use
effectively.
 As Java inherits the C/C++ syntax and many of the object-oriented features of C++,
its easy to learn.

Object-Oriented
 The object model in Java is simple and easy to extend, while primitive types, such as
integers, are kept as high-performance non objects.

Robust
 the program must execute reliably in a variety of systems. To gain reliability, Java
restricts us to find mistakes early in program development.
 As Java is a strictly typed language, it checks code at compile time. also checks code
at run time.
 Java programmes behave in a predictable way under diverse conditions is a key
feature of Java.
 Programs fail in 2 conditions, memory management mistakes and mishandled
exceptional conditions
 Java virtually eliminates memory management problems by managing memory
allocation and deallocation automatically.
 Exceptional conditions(run time errors) in Java is handled well by providing object
oriented exception handling
Multithreaded
 Java programs can do many things simultaneously.
 The Java run-time system supports multi process synchronization that enables to
construct smoothly running interactive systems.
 Java‘s easy-to-use approach to multithreading allows to work on specific behavior of
the program, not the multitasking subsystem.
Architecture-Neutral
 A central issue for the Java design was that of code longevity and portability.
 As Operating system upgrades, processor upgrades, and changes in core system
resources can all combine to make a program malfunction. (same program will not
execute in different platforms)

Dept. of CSE, AJIET, Mangaluru Page 10


Object Oriented Concepts MODULE 2 18CS45

 Java Virtual Machine in an attempt to alter this situation. The goal is ―write once; run
anywhere, any time, forever.‖
Interpreted and High Performance
 Java enables the creation of cross-platform programs by compiling into an
intermediate representation called Java bytecode. This code can be executed on any
system that implements the Java Virtual Machine.
 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.
Distributed
 Java is designed for the distributed environment of the Internet because it handles
TCP/IP protocols.
 Java supports Remote Method Invocation (RMI). This feature enables a program to
invoke methods across a network.

Dynamic
 Java programs carry 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 manner.
 This is crucial to the robustness of the Java environment, in which small fragments of
bytecode may be dynamically updated on a running system.

The Evolution of Java


Unlike most other software systems that usually settle into a pattern of small, incremental
improvements, Java continued to evolve at an explosive pace. Soon after the release of Java
1.0, the designers of Java had already created Java 1.1.
The next major release of Java was Java 2, where the ―2‖ indicates ―second generation.‖ The
creation of Java 2 was a watershed event, marking the beginning of Java‘s ―modern age.‖ The
first release of Java 2 carried the version number 1.2.ava 2 added support for a number of
new features, such as Swing and the Collections Framework, and it enhanced the Java Virtual
Machine and various programming tools. Java 2 also contained a few deprecations. The most
important affected the Thread class in which the methods suspend( ), resume( ), and stop( )
were deprecated.
J2SE 1.3 was the first major upgrade to the original Java 2 release. For the most part, it added
to existing functionality and ―tightened up‖ the development environment.The release of
J2SE 1.4 further enhanced Java. This release contained several important upgrades,
enhancements, and additions. For example, it added the new keyword assert, chained
exceptions, and a channel-based I/O subsystem. It also made changes to the Collections
Framework and the networking classes.
ThenextreleaseofJavawasJ2SE5,anditwasrevolutionary.Unlikemostoftheprevious
Javaupgrades,whichofferedimportant,butmeasuredimprovements,J2SE5fundamentally
expanded the scope, power, and range of the language.

Dept. of CSE, AJIET, Mangaluru Page 11


Object Oriented Concepts MODULE 2 18CS45

Java SE 6
ThenewestreleaseofJavaiscalledJavaSE6. Java SE 6 builds on the base of J2SE 5, adding
incremental improvements. Java SE 6 adds no major features to the Java language proper, but
it does enhance the API libraries, add several new packages, and offer improvements to the
run time.

Object-Oriented Programming
Object-orientedprogramming(OOP)isatthecoreofJava.Infact,allJavaprogramsaretoat least
some extent object-oriented. OOPis so integral to Java that it is best to understand its
basicprinciplesbeforeyoubeginwritingevensimpleJavaprograms.
Two Paradigms
All computer programs consist of two elements: code and data. Furthermore, a program can
be conceptually organized around its code or around its data.
The first way is called the process-oriented model. This approach characterizes a program as
a series of linear steps (that is, code). The process-oriented model can be thought of as code
acting on data. Procedural languages such as C employ this model to considerable success.
Tomanageincreasingcomplexity,thesecondapproach,called object-orientedprogramming, was
conceived. Object-oriented programming organizes a program around its data (that is,
objects) and a set of well-defined interfaces to that data. An object-oriented program can be
characterized as data controlling access to code.
Abstraction
An essential element of object-oriented programming is
abstraction.Apowerfulwaytomanageabstractionisthroughtheuseofhierarchicalclassifications.
This allows you to layer the semantics of complex systems, breaking them into more
manageable pieces.

The Three OOP Principles


All object-oriented programming languages provide mechanisms that help you implement
theobject-orientedmodel.Theyareencapsulation,inheritance,andpolymorphism.
1. Encapsulation
Encapsulation is the mechanism that binds together code and the data it manipulates, and
keepsbothsafefromoutsideinterferenceandmisuse.Onewaytothinkaboutencapsulation is as a
protective wrapper that prevents the code and data from being arbitrarily accessed by other
code defined outside the wrapper. Access to the code and data inside the wrapper
istightlycontrolledthroughawell-definedinterface.
When you create a class, you will specify the code and data that constitute that class.
Collectively, these elements are called members of the class. Specifically, the data defined by
the class are referred to as member variables or instance variables. The code that operates on
that data is referred to as member methods or just methods. (If you are familiar with C/C++,
it may help to know that what a Java programmer calls a method, a C/C++ programmer calls
a function.)

Dept. of CSE, AJIET, Mangaluru Page 12


Object Oriented Concepts MODULE 2 18CS45

2. Inheritance
Inheritance is the process by which one object acquires the properties of another
object.Adeeplyinheritedsubclassinheritsalloftheattributesfromeachofitsancestors in the class
hierarchy.Ifyouwantedtodescribeamorespecificclassofanimals,suchasmammals,theywould
have more specific attributes, such as type of teeth, and mammary glands. This is known as a
subclass of animals, where animals are referred to as mammals‘ superclass.

3. Polymorphism
Polymorphism (from Greek, meaning ―many forms‖) is a feature that allows one interface to
be used for a general class of actions.More generally, the concept of polymorphism is often
expressed by the phrase ―one interface, multiple methods.‖ This means that it is possible to
design a generic interface to a group of related activities. This helps reduce complexity by
allowing the same interface to be used to specify a general class of action. It is the compiler‘s
job to select the specific action (that is, method) as it applies to each situation.
A First Simple Program
/*

Dept. of CSE, AJIET, Mangaluru Page 13


Object Oriented Concepts MODULE 2 18CS45

This is a simple Java program. Call this file "Example.java".


*/
class Example {
// Your program begins with a call to main().
public static void main(String args[])
{
System.out.println("This is a simple Java program.");
}
}
Entering the Program
In Java, a source file is officially called a compilation unit. It is a text file that contains one or
more class definitions. The Java compiler requires that a source file use the .java filename
extension.As you can see by looking at the program, the name of the class defined by the
program is also Example. This is not a coincidence. In Java, all code must reside inside a
class. By convention, the name of that class should match the name of the file that holds the
program. You should also make sure that the capitalization of the filename matches the class
name.The reason for this is that Java is case-sensitive.
Compiling the Program
To compile the Example program, execute the compiler, javac, specifying the name of the
source file on the command line, as shown here:
C:\>javac Example.java
The javac compiler creates a file called Example.class that contains the bytecode version
oftheprogram
To actually run the program, you must use the Java application launcher, called java. To do
so, pass the class name Example as a command-line argument, as shown here:
C:\>java Example
When the program is run, the following output is displayed:
This is a simple Java program.
Explanation
 class Example { This line uses the keyword class to declare that a new class is being
defined.
 Example is an identifier that is the name of the class.
 The entire class definition, including all of its members, will be between the opening
curly brace ({) and the closing curly brace (}).
 public static void main(String args[]) {

Dept. of CSE, AJIET, Mangaluru Page 14


Object Oriented Concepts MODULE 2 18CS45

 This line begins the main( ) method. This is the line at which the program will begin
executing. All Java applications begin execution by calling main( ).
 The public keyword is an access specifier, which allows the programmer to control
the visibility of class members.
 When a class member is preceded by public, then that member may be accessed by
code outside the class in which it is declared.
 main( ) must be declared as public, since it must be called by code outside of its class
when the program is started.
 The keyword static allows main( ) to be called without having to instantiate a
particular instance of the class. This is necessary since main( ) is called by the Java
Virtual Machine before any objects are made.
 The keyword void tells the compiler that main( ) does not return a value.
 String args[ ] declares a parameter named args, which is an array of instances of the
class String.
 args receives any command-line arguments present when the program is executed.
 System.out.println("This is a simple Java program.");
 Output is actually accomplished by the built-in println( ) method, println( ) displays
the string which is passed to it.
 System is a predefined class that provides access to the system, and out is the output
stream that is connected to the console.

Two Control Statements:


The if Statement
The Java if statement works much like the IF statement in any other language. Further, it
is syntacticallyidenticaltotheifstatementsinC,C++,andC#.Itssimplestformisshownhere:
if(condition) statement;
Here, condition is a Boolean expression. If condition is true, then the statement is
executed. If condition is false, then the statement is bypassed.
Here is an example:if(num< 100) System.out.println("num is less than 100");
The for Loop
.Thesimplestformofthe for loop is shown here:
for(initialization; condition; iteration) statement;
Initsmostcommonform,the initializationportionoftheloopsetsaloopcontrolvariable to an
initialvalue.TheconditionisaBooleanexpressionthatteststheloopcontrol variable. If the
outcome of that test is true, the for loop continues to iterate. If it is false, the
loopterminates. The iteration expression determines how the loop control variable is
changed each time the loop iterates
Using Blocks of Code
Java allows two or more statements to be grouped into blocks of code, also called code
blocks. This is done by enclosing the statements between opening and closing curly
braces. Once a block of code has been created, it becomes a logical unit that can be used

Dept. of CSE, AJIET, Mangaluru Page 15


Object Oriented Concepts MODULE 2 18CS45

any place that a single statement can. For example, a block can be a target for Java‘s if
and for statements.
if(x < y)
{ // begin a block
x = y;
y = 0;
} // end

Lexical Issues
Javaprogramsareacollectionofwhitespace,identifiers,literals, comments, operators,
separators, and keywords.
Whitespace
Java isafree-formlanguage.Thismeansthatyoudonotneedtofollowanyspecialindentation
rules.In Java, whitespace is a space, tab, or newline.
Identifiers
Identifiers are used for class names, method names, and variable names. An identifier may be
any descriptive sequence of uppercase and lowercase letters, numbers, or the underscore and
dollar-sign characters. They must not begin with a number, lest they be confused with a
numeric literal. Again, Java is case-sensitive, so VALUE is a different identifier than Value.
Literals
A constant value in Java is created by using a literal representation of it.For example,
100, 98.6, 'X', "This is a test"
Left to right, the first literal specifies an integer, the next is a floating-point value, the third is
acharacterconstant,andthelastisastring.Aliteralcanbeusedanywhereavalueofitstype is allowed.
Comments
As mentioned ,there are three types of comments defined by Java. We have already seen two:
single-lineandmultiline.Thethirdtypeiscalledadocumentationcomment.Thistypeofcomment
isusedtoproduceanHTMLfilethatdocumentsyourprogram.Thedocumentationcomment begins
with a /**and ends with a */.
Separators
In Java, there are a few characters that are used as separators. The most commonly used
separator in Java is the semicolon. As you have seen, it is used to terminate statements. The
separators are shown in the following table:

Dept. of CSE, AJIET, Mangaluru Page 16


Object Oriented Concepts MODULE 2 18CS45

The Java Keywords


Thereare50keywordscurrentlydefinedintheJavalanguage, Thesekeywords, combined with the
syntax of the operators and separators, form the foundation oftheJava
language.Thesekeywordscannotbeusedasnamesforavariable,class,ormethod.

The Java Class Libraries


In the larger view, the Java environment relies on several built-in class libraries that contain
many built-in methods that provide support for such things as I/O, string handling,
networking, and graphics. The standard classes also provide support for windowed output.
Thus, Java as a totality is a combination of the Java language itself, plus its standard classes
Java Is a Strongly Typed Language
First, every variable has a type, every expression has a type, and every type is strictly defined.
Second, all assignments, whether explicit or via parameter passing in method calls, are
checked for type compatibility. There are no automatic coercions or conversions of
conflicting types as in some languages. The Java compiler checks all expressions and
parameters to ensure that the types are compatible. Any type mismatches are errors that must
be corrected before the compiler will finish compiling the class.
The Primitive Types
Javadefineseightprimitivetypesofdata:byte,short,int,long,char,float,double,andboolean. The
primitive types are also commonly referred to as simple types,These can be put in four
groups:

Dept. of CSE, AJIET, Mangaluru Page 17


Object Oriented Concepts MODULE 2 18CS45

 Integers This group includes byte, short, int, and long, which are for whole-valued
signed numbers
 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.
Integers
Java defines four integer types: byte, short, int, and long. All of these are signed, positive and
negative values. Java does not support unsigned, positive-only integers.

Floating-Point Types
Floating-point numbers, also known as real numbers, are used when evaluating expressions
thatrequirefractionalprecision. There are two kindsoffloating-pointtypes,
floatanddouble,whichrepresentsingle-anddouble-precision numbers, respectively. Their width
and ranges are shown here:

Characters
InJava,thedatatypeusedtostorecharactersis char. Java uses Unicode to represent characters.
Unicode defines a fully international character set that can represent all of the characters
found in all human languages.For this purpose, it requires 16 bits. Thus, in Java char is a 16-
bit type. The range of a char is 0 to 65,536. There are no negative chars. The standard set of
characters known as ASCII still ranges from 0 to 127 as always, andthe extended 8-bit
character set, ISO-Latin-1, ranges from 0 to 255.
Booleans
Java has a primitive type, called boolean, for logical values. It can have only one of two
possible values, true or false. This is the type returned by all relational operators, as in the
case of a < b. boolean is also the type required by the conditional expressions that govern the
control statements such as if and for.

A Closer Look at Literals

Dept. of CSE, AJIET, Mangaluru Page 18


Object Oriented Concepts MODULE 2 18CS45

Integer Literals
Integers are probably the most commonly used type in the typical program. Any whole
number value is an integer literal. Examples are 1, 2, 3, and 42. These are all decimal values,
meaning they are describing a base 10 number. There are two other bases which can be used
inintegerliterals,octal(baseeight)andhexadecimal(base16).OctalvaluesaredenotedinJava
byaleadingzero.Normaldecimalnumberscannothavealeadingzero.You signify a hexadecimal
constant with a leading zero-x, (0x or 0X). The range of a hexadecimal digit is 0 to 15, so A
through F (or a through f ) are substituted for 10 through 15. Integer literals create an int
value, which in Java is a 32-bit integer value.

Floating-Point Literals
Floating-point numbers represent decimal values with a fractional component. They can be
expressedineitherstandardorscientificnotation.Standardnotationconsistsofawholenumber
componentfollowedbyadecimalpointfollowedbyafractionalcomponent.Forexample,2.0,
3.14159,and0.6667representvalidstandard-notationfloating-pointnumbers.Scientificnotation
uses a standard-notation, floating-point number plus a suffix that specifies a power of 10 by
which the number is to be multiplied. The exponent is indicated by an E or e followed by a
decimalnumber,whichcanbepositiveornegative.Examplesinclude6.022E23,314159E–05, and
2e+100. Floating-point literals in Java default to double precision. To specify a float literal,
you must append an F or f to the constant.
Boolean Literals
Boolean literals are simple. There are only two logical values that a boolean value can have,
trueandfalse.Thevaluesoftrueandfalsedonotconvertintoanynumericalrepresentation.
ThetrueliteralinJavadoesnotequal1,nordoesthefalseliteralequal0.
Character Literals
Characters in Java are indices into the Unicode character set. They are 16-bit values.
Aliteralcharacter isrepresentedinsideapairofsinglequotes.
String Literals
String literals in Java are specified like they are in most other languages—by enclosing a
sequence of characters between a pair of double quotes.

Dept. of CSE, AJIET, Mangaluru Page 19


Object Oriented Concepts MODULE 2 18CS45

Variables
The variable is the basic unit of storage in a Java program. Avariable is defined by the
combinationofanidentifier,atype,andanoptionalinitializer.Inaddition,allvariableshave 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] ...] ;
The type is one of Java‘s atomic types, or the name of a class or interface. The identifier is
the name of the
variable.Todeclaremorethanonevariableofthespecifiedtype,useacommaseparated list.
Dynamic Initialization
Here is a short program that computes the length of the hypotenuse of a right triangle given
the lengths of its two opposing sides:
// Demonstrate dynamic initialization.
class DynInit {
public static void main(String args[])
{
double a = 3.0, b = 4.0;
// c is dynamically initialized
double c = Math.sqrt(a * a + b * b);
System.out.println("Hypotenuse is " + c);
}
}

Here, three local variables—a, b, and c—are declared. The first two, a and b, are initialized
by constants. However, c is initialized dynamically to the length of the hypotenuse.

The Scope and Lifetime of Variables

Sofar,allofthevariablesusedhavebeendeclaredatthestartofthemain()method.However, Java
allows variables to be declared within any block.block is begun with an opening curly brace
and ended by a closing curly brace. Ablock defines a

Dept. of CSE, AJIET, Mangaluru Page 20


Object Oriented Concepts MODULE 2 18CS45

scope.Thus,eachtimeyoustartanewblock,youarecreatinganewscope.Ascopedetermines what
objects are visible to other parts of your program. It also determines the lifetime of those
objects.
In Java, the two major scopes are those defined by a class and those defined by a method.

Type Conversion and Casting


If the two types are compatible, then Java will perform the conversion automatically. For
example, it is always possible to assign an int value to a long variable. However, not all types
are compatible, and thus, not
alltypeconversionsareimplicitlyallowed.Forinstance,thereisnoautomaticconversion
definedfrom double to byte. Fortunately, it is still possible to obtain a conversion between
incompatible types. To do so, you must use a cast, which performs an explicit conversion
between incompatible types.
Java’s Automatic Conversions
When one type of data is assigned to another type of variable, an automatic type conversion
will take place if the following two conditions are met:
• The two types are compatible.
• The destination type is larger than the source type.

Casting Incompatible Types


Whatifyouwanttoassignan intvaluetoabytevariable?Thisconversionwillnot be performed
automatically, because a byte is smaller than an int. This kind of conversion is sometimes
called a narrowing conversion, since you are explicitly making the value narrower so that it
will fit into the target type. To create a conversion between two incompatible types, you must
use a cast. Acast is simply an explicit type conversion. It has this general form:
(target-type) value
Here, target-type specifies the desired type to convert the specified value to.
int a;
byte b;
// ...
b = (byte) a;

Adifferent type of conversion will occur when a floating-point value is assigned to an integer
type: truncation. As you know, integers do not have fractional components. Thus, when a
floating-point value is assigned to an integer type, the fractional component is lost. For
example, if the value 1.23 is assigned to an integer, the resulting value will simply be 1. The
0.23 will have been truncated.

Automatic Type Promotion in Expressions

Dept. of CSE, AJIET, Mangaluru Page 21


Object Oriented Concepts MODULE 2 18CS45

In an expression, the precision required of an intermediate value will sometimes exceed the
range of either operand. For example, examine the following expression:
byte a = 40;
byte b = 50;
byte c = 100;
int d = a * b / c;
The result of the intermediate term a*beasily exceeds the range of either of its byte operands.
To handle this kind of problem, Java automatically promotes each byte, short,
orcharoperandtointwhenevaluatinganexpression. Thismeansthatthesubexpressiona*b
isperformedusingintegers—notbytes. Thus,2,000,theresultoftheintermediateexpression, 50
*40,islegaleventhoughaandbarebothspecifiedastypebyte.

The Type Promotion Rules


Java defines several typepromotionrules that apply to expressions. They are as follows: First,
all byte, short, and char values are promoted to int, as just described. Then, if one operand is
a long, the whole expression is promoted to long.Ifoneoperandisafloat,theentire
expressionispromotedtofloat.Ifanyoftheoperands is double, the result is double.

Arrays
An array is a group of like-typed variables that are referred to by a common name. Arrays of
anytypecanbecreatedandmayhaveoneormoredimensions.Aspecificelementinanarray is
accessed by its index. Arrays offer a convenient means of grouping related information.

One-Dimensional Arrays
Aone-dimensionalarrayis,essentially,alistoflike-typedvariables.Tocreateanarray,youfirst must
create an array variable of the desired type. The general form of a one-dimensional array
declaration is
type var-name[ ];
Here,typedeclaresthebasetypeofthearray.Thebasetypedeterminesthedatatypeofeach element
that comprises the array. Thus, the base type for the array determines what type of data the
array will hold.
Ex: int month_days[];
Thisexampleallocates a 12-element array of integers and links them to month_days.
month_days = new int[12];
Putting together all the pieces, here is a program that creates an array of the number of days
in each month.
// Demonstrate a one-dimensional array.
class Array
{
public static void main(String args[])
{
int month_days[];
month_days = new int[12];
month_days[0] = 31;
month_days[1] = 28;
month_days[2] = 31;
month_days[3] = 30;
month_days[4] = 31;
month_days[5] = 30;
month_days[6] = 31;
month_days[7] = 31;

Dept. of CSE, AJIET, Mangaluru Page 22


Object Oriented Concepts MODULE 2 18CS45

month_days[8] = 30;
month_days[9] = 31;
month_days[10] = 30;
month_days[11] = 31;
System.out.println("April has " + month_days[3] + " days.");
}
}

Multidimensional Arrays
InJava,multidimensionalarraysareactuallyarraysofarrays.. To declare a multidimensional
array variable, specify each additional index using another set of square brackets. For
example, the following declares a twodimensional array variable called twoD.
inttwoD[][] = new int[4][5];

Alternative Array Declaration Syntax

There is a second form that may be used to declare an array:


type[ ] var-name;

Here, the square brackets follow the type specifier, and not the name of the array variable.
For example, the following two declarations are equivalent:
intal[] = new int[3];
int[] a2 = new int[3];
The following declarations are also equivalent:
char twod1[][] = new char[3][4];
char[][] twod2 = new char[3][4];

A Few Words About Strings

The String type is used to declare string variables. You can also declare arrays of strings.
Aquoted string constant can be assigned to a String variable. Avariable of type String canbe
assigned to another variable of type String. You can use an object of type String as an
argument to println( ). For example, consider the following fragment:
String str = "this is a test";
System.out.println(str);

Dept. of CSE, AJIET, Mangaluru Page 23


Object Oriented Concepts MODULE 2 18CS45

Here, str is an object of type String. It is assigned the string ―this is a test‖. This string is
displayed by the println( ) statement.

Operators
Java provides a rich operator environment. Most of its operators can be divided into the
following four groups: arithmetic, bitwise, relational, and logical.

Arithmetic Operators:
Arithmetic operators are used in mathematical expressions in the same way that they are used
in algebra. The following table lists the arithmetic operators:

 The Basic Arithmetic Operators

The basic arithmetic operations—addition, subtraction, multiplication, and division— all


behaveasyouwouldexpectforallnumerictypes.Theminusoperatoralsohasaunaryform that
negates its single operand. Remember that when the division operator is applied to an integer
type, there will be no fractional component attached to the result.

Dept. of CSE, AJIET, Mangaluru Page 24


Object Oriented Concepts MODULE 2 18CS45

 The Modulus Operator


The modulus operator, %, returns the remainder of a division operation. It can be applied to
floating-point types as well as integer types. The following example program demonstrates
the %:
// Demonstrate the % operator.
class Modulus
{
public static void main(String args[])
{
int x = 42;
double y = 42.25;
System.out.println("x mod 10 = " + x % 10);
System.out.println("y mod 10 = " + y % 10);
}
}
When you run this program, you will get the following output:
x mod 10 = 2
y mod 10 = 2.25

 Arithmetic Compound Assignment Operators


Java provides special operators that can be used to combine an arithmetic operation with an
assignment. As you probably know, statements like the following are quite common in
programming:
a = a + 4;

Dept. of CSE, AJIET, Mangaluru Page 25


Object Oriented Concepts MODULE 2 18CS45

In Java, you can rewrite this statement as shown here:


a += 4;
This version uses the += compound assignment operator. Both statements perform the same
action: they increase the value of a by 4.

 Increment and Decrement


The ++ and the – – are Java‘s increment and decrement operators.The increment operator
increases its operand by one. The decrement operator decreases its operand by one. For
example, this statement:
x = x + 1;
can be rewritten like this by use of the increment operator:
x++;
Similarly, this statement:
x = x - 1;
is equivalent to
x--;

 The Bitwise Logical Operators


The bitwise logical operators are &, |, ^, and ~. The following table shows the outcome of
each operation.

 The Bitwise Operators


Java defines several bitwise operators that can be applied to the integer types, long, int, short,
char, and byte. These operators act upon the individual bits of their operands. They are
summarized in the following table:

Dept. of CSE, AJIET, Mangaluru Page 26


Object Oriented Concepts MODULE 2 18CS45

 The Left Shift


Theleftshiftoperator,<<,shiftsallofthebitsinavaluetotheleftaspecifiednumberoftimes.
Ithasthisgeneralform:
value <<num
Here, num specifies the number of positions to left-shift the value in value.

 The Right Shift


The right shift operator, >>, shifts all of the bits in a value to the right a specified number of
times. Its general form is shown here:
value >>num
Here, num specifies the number of positions to right-shift the value in value. That is, the >>
moves all of the bits in the specified value to the right the number of bit positions specified
by num.

 The Unsigned Right Shift


Asyouhavejustseen,the>>operatorautomaticallyfillsthehigh-orderbitwithitsprevious contents
each time a shift occurs. This preserves the sign of the value. However, sometimes
thisisundesirable.Forexample, ifyouareshiftingsomethingthatdoesnotrepresentanumeric value,
you may not want sign extension to take place. This situation is common when you are
working with pixel-based values and graphics. In these cases, you will generally want to shift
a zero into the high-order bit no matter what its initial value was. This is known as an
unsigned shift. To accomplish this, you will use Java‘s unsigned, shift-right operator, >>>,
which always shifts zeros into the high-order bit.

 Relational Operators
The relational operators determine the relationship that one operand has to the other.
Specifically, they determine equality and ordering. The outcome of these operations is a
boolean value.
The relational operators are shown here:

 Boolean Logical Operators


The Boolean logical operators shown here operate only on boolean operands. All of the
binary logical operators combine two boolean values to form a resultant boolean value.

Dept. of CSE, AJIET, Mangaluru Page 27


Object Oriented Concepts MODULE 2 18CS45

The logical Boolean operators, &, |, and ^, operate on boolean values in the same way that
they operate on the bits of an integer. The logical ! operator inverts the Boolean state:
!true==falseand!false==true.Thefollowingtableshowstheeffectofeachlogicaloperation:

 Short-Circuit Logical Operators


JavaprovidestwointerestingBooleanoperatorsnotfoundinmanyothercomputerlanguages. These
are secondary versions of the Boolean AND and OR operators, and are known as short-circuit
logical operators. As you can see from the preceding table, the OR operator results in true
when A is true, no matter what B is. Similarly, the AND operator results in false when A is
false, no matter what B is. If you use the || and && forms, rather than the | and & forms of
these operators, Java will not bother to evaluate the right-hand operand when the outcome of
the expression can be determined by the left operand alone. This is very useful when the
right-hand operand depends on the value of the left one in order to function properly.

 The Assignment Operator


Theassignmentoperatoristhesingleequalsign,=.Theassignmentoperatorworksin
Javamuchasitdoesinanyothercomputerlanguage.Ithasthisgeneralform:
var = expression;
Here, the type of var must be compatible with the type of expression.
int x, y, z;
x = y = z = 100; // set x, y, and z to 100

 The ? Operator
Javaincludesaspecialternary(three-way)operatorthatcanreplacecertaintypesofif-then-else
statements. This operator is the ?.The ? has this general form:
expression1 ? expression2 : expression3

Operator Precedence
The following table shows the order of precedence for Java operators, from highest to lowest

 Using Parentheses

Dept. of CSE, AJIET, Mangaluru Page 28


Object Oriented Concepts MODULE 2 18CS45

Parenthesesraisetheprecedenceoftheoperationsthatareinsidethem.
Considerthefollowingexpression:
a >> b + 3
Thisexpressionfirstadds3tobandthenshiftsarightbythatresult.Thatis,thisexpression
canberewrittenusingredundantparentheseslikethis:
a >> (b + 3)

Control Statements
Aprogramming language uses control statements to cause the flow of execution to advance
and branch based on changes to the state of a program. Java‘s program control statements can
be put into the following categories: selection, iteration, and jump. Selection statements allow
your program to choose different paths of execution based upon the outcome of an expression
or the state of a variable. Iteration statements enable program execution to repeat one or more
statements (that is, iteration statements form loops). Jump statements allow your program to
execute in a nonlinear fashion.

Java’s Selection Statements


Javasupportstwoselectionstatements:ifandswitch.Thesestatementsallowyoutocontrolthe
flowofyourprogram‘sexecutionbaseduponconditionsknownonlyduringruntime.
 If
The if statement is Java‘s conditional branch statement. It can be used to route program
execution through two different paths. Here is the general form of the if statement:
if (condition) statement1;
else statement2;
Here, each statement may be a single statement or a compound statement enclosed in curly
braces (that is, a block).The if works like this: If the condition is true, then statement1 is
executed. Otherwise, statement2 (if it exists) is executed. In no case will both statements be
executed.

 Nested ifs
Anestedifisanifstatementthatisthetargetofanother iforelse.Nestedifsareverycommon in
programming. When you nest ifs, the main thing to remember is that an else statement always
refers to the nearest if statement that is within the same block as the else and that is not
already associated with an else.
if(i == 10) {
if(j < 20) a = b;
if(k > 100) c = d; // this if is
else a = c; // associated with this else
} else a = d; // this else refers to if(i == 10)

 The if-else-if Ladder


Acommon programming construct that is based upon a sequence of nested ifs is the if-else-if
ladder. It looks like this:
if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;

Dept. of CSE, AJIET, Mangaluru Page 29


Object Oriented Concepts MODULE 2 18CS45

...
else statement;
Theifstatementsareexecutedfromthetopdown.Assoonasoneoftheconditionscontrolling the if is
true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If
none of the conditions is true, then the final else statement will be executed. The final else
acts as a default condition;

 Switch
TheswitchstatementisJava‘smultiwaybranchstatement.Itprovidesaneasywaytodispatch
executiontodifferentpartsofyourcodebasedonthevalueofanexpression.
Hereisthegeneralform ofaswitchstatement:
switch (expression)
{
case value1:
// statement sequence
break;
case value2:
// statement sequence
break;
...
case valueN:

default:
// default statement sequence
}

Iteration Statements
Java‘s iteration statements are for, while, and do-while. These statements create what we
commonly call loops.
 While
The while loop is Java‘s most fundamental loop statement. It repeats a statement or block
while its controlling expression is true. Here is its general form:
while(condition)
{
// body of loop
}
The condition can be any Boolean expression. The body of the loop will be executed as long
as the conditional expression is true. When condition becomes false, control passes to the
next line of code immediately following the loop. The curly braces are unnecessary if only a
single statement is being repeated.

 do-while
The do-while loop always executes its body at least once, because its conditional expression
is at the bottom of the loop. Its general form is
do
{
// body of loop
} while (condition);

Dept. of CSE, AJIET, Mangaluru Page 30


Object Oriented Concepts MODULE 2 18CS45

Eachiterationofthedo-whileloopfirstexecutesthebodyoftheloopandthenevaluates
theconditionalexpression.Ifthisexpressionistrue,theloopwillrepeat.Otherwise,theloop
terminates.

 For
Thefirstisthetraditionalform
thathasbeeninusesincetheoriginalversionofJava.Thesecondisthenew―for-each‖form.
Bothtypesofforloopsarediscussedhere,beginningwiththetraditionalform. Here is the general
form of the traditional for statement:
for(initialization; condition; iteration)
{
// body
}

 The For-Each Version of the for Loop


A second form of for was defined that implements a ―for-each‖ style
loop.Aforeachstyleloopisdesignedtocyclethroughacollectionofobjects,suchasanarray,instrictly
sequential fashion, from start to finish.Thefor-eachstyleof forisalsoreferredtoasthe enhanced
forloop. The general form of the for-each version of the for is shown here:
for(type itr-var : collection) statement-block
Here, type specifies the type and itr-var specifies the name of an iteration variable that will
receive the elements from a collection, one at a time, from beginning to end. The collection
being cycled through is specified by collection.

// Use a for-each style for loop.


class ForEach
{ public static void main(String args[])
{
intnums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;
// use for-each style for to display and sum the values
for(int x : nums)
{
System.out.println("Value is: " + x);
sum += x;
}
System.out.println("Summation: " + sum);
}
}

Jump Statements
Javasupportsthreejumpstatements: break,continue,andreturn.Thesestatementstransfer
controltoanotherpartofyourprogram.
 Using break
In Java, the break statement has three uses. First, as you have seen, it terminates a statement
sequence in a switch statement. Second, it can be used to exit a loop. Third, it can be used as
a ―civilized‖ form of goto.

Dept. of CSE, AJIET, Mangaluru Page 31


Object Oriented Concepts MODULE 2 18CS45

 Using continue
Sometimesitisusefultoforceanearlyiterationofaloop.Thatis,youmightwanttocontinue
runningtheloopbutstopprocessingtheremainderofthecodeinitsbodyforthisparticular
iteration..The continue statement performs such an action.
// Demonstrate continue.
class Continue
{
public static void main(String args[])
{
for(inti=0; i<10; i++)
{
System.out.print(i + " ");
if (i%2 == 0)
continue;
System.out.println("");
}
}
}

 Return
The last control statement is return. The return statement is used to explicitly return from a
method. That is, it causes program control to transfer back to the caller of the method.

QUESTION BANK

1) How is ― Compile once, and run anywhere‖ implemented in java? Explain?


2) Write a program to calculate the average among elements {8, 6, 2, 7} using for each
in java? Explain how is it different from for loop
3) Explain type conversion with an example
4) List and explain the java buzzword?
5) Explain the concept of arrays in java with examples? Also write a program that
initializes and creates a 4 integer element array. Find the sum and average of the
values?

Dept. of CSE, AJIET, Mangaluru Page 32

You might also like