SlideShare a Scribd company logo
20IT301 JAVA PROGRAMMING
By
M.Mohanraj
Assistant Professor
Department of Artificial Intelligence and Data Science
Kongunadu College of Engineering
UNIT
I
⚫ OOP concepts- Data abstraction-
encapsulation- inheritance- benefits of inheritance-
polymorphism-classes and objects- procedural and
object oriented programming paradigm.
⚫Java programming – History of java- comments
data types-variables-constants-scope and life time
of variables- operators-operator hierarchy-
expressions-type conversion and casting-
enumerated types- control flow – block scope-
conditional statements-loops-break and
continue statements- simple java stand alone
programs-arrays- console input and output-
formatting output-constructors- methods-
parameter passing- static fields and methods-
access control- this reference- overloading methods
and constructors-recursion-garbage collection-
building strings- exploring string class
Need for OOP Paradigm
 OOP is an approach to program organization and development,
which attempts to eliminate some of the drawbacks of conventional
programming methods by incorporating the best of structured
programming features with several new concepts.
 OOP allows us to decompose a problem into number of
entities called objects and then build data and methods (functions)
around these entities.
 The data of an object can be accessed only by the
methods
associated with the object.
Introduction
⚫Object-oriented programming (OOP) is a programming
paradigm that uses “Objects “and their interactions to
design applications.
⚫ It simplifies the software development and maintenance
by
providing some concepts:
⚫Object
⚫Class
⚫Data Abstraction & Encapsulation
⚫Inheritance
⚫Polymorphism
⚫Dynamic Binding
Object
⚫ Objects are the basic run time entities in an
object- oriented system. They may represent a person,
a place, a bank account, a table of data or any item
that the program has to handle.
UNIT I 	OOP AND JAVA FUNDAMENTALS CONSTRUCTOR
Class
⚫The entire set of data and code of an object can be made of a
user defined data type with the help of a class.
⚫In fact, Objects are variables of the type class. Once a class has
been defined, we can create any number of objects belonging to
that class.
⚫Classes are data types based on which objects are created.
Objects with similar properties and methods are
grouped together to form a Class. Thus a Class
represents a set of individual objects.
⚫Characteristics of an object are represented in a class as
Properties. The actions that can be performed by objects
become functions of the class and is referred to as
Methods.
⚫ A class is thus a collection of objects of similar type .
for example: mango, apple, and orange are members of
the class fruit . ex: fruit mango; will create an object
mango belonging to the class fruit.
Example for class
⚫class Human
⚫{
private:
⚫ EyeColor IColor;
⚫ NAME personname;
⚫ public:
⚫ void SetName(NAME anyName);
⚫ void SetIColor(EyeColor eyecolor);
⚫};
Data abstraction
⚫Abstraction refers to the act of representing essential features
without including the background details or explanations. since the
classes use the concept of data abstraction ,they are known as
abstraction data type(ADT).
For example, a class Car would be made up of an Engine, Gearbox,
Steering objects, and many more components. To build the Car
class, one does not need to know how the different components
work internally, but only how to interface with them, i.e., send
messages to them, receive messages from them, and perhaps make
the different objects composing the class interact with each other.
An example for abstraction
⚫ Humans manage complexity through abstraction. When you
drive your car you do not have to be concerned with the
exact internal working of your car(unless you are a
mechanic). What you are concerned with is
interacting with your car via its interfaces like steering
wheel, brake pedal, accelerator pedal etc. Various
manufacturers of car has different implementation of car
working but its basic interface has not changed (i.e. you still
use steering wheel, brake pedal, accelerator pedal etc to
interact with your car). Hence the knowledgeyou have of your
UNIT I 	OOP AND JAVA FUNDAMENTALS CONSTRUCTOR
Some of the Object-Oriented Paradigm are:
1. Emphasis is on data rather than procedure.
2. Programs are divided into objects.
3. Data Structures are designed such that they
Characterize the objects.
4 Methods that operate on the data of an object
are tied together in the data structure.
5 Data is hidden and can not be accessed by
external functions.
6 Objects may communicate with each other
through
methods.
A way of viewing world – Agents
⚫OOP uses an approach of treating a real world agent as an
object.
⚫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 by switching the controlling entity to
data.
Start
Messag
e
0 bj
ect
Objec
t
0
bject
0bj
ect
”Object
PFogrammi
ng
Sheì1
Message paths
0 bject
0bj
ect
0
bject
message to
environme
nt
Message
from
environmen
t
Responsibility
⚫primary motivation is the need for a platform-independent
(that is, architecture- neutral) language that could be used to
create software to be embedded in various consumer
electronic devices, such as microwave ovens and remote
controls.
⚫Objects with clear responsibilities.
⚫Each class should have a clear responsibility.
⚫If you can't state the purpose of a class in a single, clear
sentence, then perhaps your class structure needs
some thought.
Messages
⚫We all like to use programs that let us know what's going on.
Programs that keep us informed often do so by
displaying status and error messages.
⚫These messages need to be translated so they can be
understood by end users around the world.
⚫
⚫The Section discusses translatable text messages. Usually,
you're done after you move a message String into
a ResourceBundle.
⚫If you've embedded variable data in a message, you'll have to
take some extra steps to prepare it for translation.
Methods
⚫A method is a group of instructions that is given a name and can be
called up at any point in a program simply by quoting that name.
⚫Drawing a Triangle require draw of three straight lines. This
instruction three times to draw a simple triangle.
⚫We can define a method to call this instruction three times and draw
the triangle(i.e. create a method drawLine() to draw lines and
this method is called repeatedly to achieve the needed task)
⚫The idea of methods appears in all programming languages, although
sometimes it goes under the name functions and sometimes
under the name procedures.
⚫The name methods is a throw-back to the language C++, from which
Java was developed.
⚫In C++, there is an object called a class which can contain methods.
However, everything in Java is enclosed within a class .so
the functions within it are called methods
CLASSES
• Class is blue print or an idea of an Object
• From One class any number of Instances can be
created
• It is an encapsulation of attributes and methods
FIGUR
E
CIRCL
E
SQUARE
Ob1
Ob2
RECTANGLE
Ob3
class
syntax of CLASS
class <ClassName>
{
attributes/variables;
Constructors();
methods();
}
INSTANCE
• Instance is an Object of a class which is an entity with its
own
attribute values and methods.
• Creating an Instance
ClassName
refVariable;
refVariable = new
Constructor();
or
ClassName
refVariable = new
Java Class Hierarchy
• In Java, class “Object” is the base class to all other classes
– If we do not explicitly say extends in a new class definition,
it implicitly extends Object
– The tree of classes that extend from Object and all of
its subclasses are is called the class hierarchy
– All classes eventually lead back up to Object
– This will enable consistent access of objects of different
classes.
Inheritance
⚫Methods allows to reuse a sequence of statements
⚫Inheritance allows to reuse classes by deriving a new class
from an existing one
⚫The existing class is called the parent class, or superclass, or
base class
⚫The derived class is called the child class or subclass.
⚫The child class inherits characteristics of the parent class(i.e
the child class inherits the methods and data defined for the
parent class
Inheritance
⚫Inheritance relationships are often shown graphically
in a class diagram, with the arrow pointing to the
parent class
Animal
weight : int
+ getWeight() : int
Bird
+ fly() : void
Method Binding
⚫Objects are used to call methods.
⚫MethodBinding is an object that can be used to call an
arbitrary public method, on an instance that is acquired
by evaluating the leading portion of a method binding
expression via a value binding.
⚫It is legal for a class to have two or more methods with the
same
name.
⚫Java has to be able to uniquely associate the invocation of a
method with its definition relying on the number and types of
arguments.
⚫Therefore the same-named methods must be distinguished:
1) by the number of arguments, or
2) by the types of arguments
⚫Overloading and inheritance are two ways to implement
polymorphism.
Method Overriding.
 There may be some occasions when we want an object to
respond to the same method but have different behavior
when that method is called.
 That means, we should override the method defined in the
super class. This is possible by defining a method in a sub class
that has the same name, same arguments and same return
type as a method in the super class.
 Then when that method is called, the method defined in the
sub class is invoked and executed instead of the one in the
super class. This is known as overriding.
Exceptions in Java
• Exception is an abnormal condition that arises in the code
sequence.
• Exceptions occur during compile time or run time.
• “throwable” is the super class in exception hierarchy.
• Compile time errors occurs due to incorrect syntax.
• Run-time errors happen when
– User enters incorrect input
– Resource is not available (ex. file)
– Logic error (bug) that was not fixed
Exception classes
⚫In Java, exceptions are objects. When you throw an exception, you
throw an object. You can't throw just any object as an
exception, however -- only those objects whose classes descend
from Throwable.
⚫Throwable serves as the base class for an entire family of classes,
declared in java.lang, that your program can instantiate and throw.
⚫Throwable has two direct subclasses, Exception and Error.
⚫Exceptions are thrown to signal abnormal conditions that can often be
handled by some catcher, though it's possible they may not be
caught and therefore could result in a dead thread.
⚫Errors are usually thrown for more serious problems, such as
OutOfMemoryError, that may not be so easy to handle. In general,
code you write should throw only exceptions, not errors.
⚫Errors are usually thrown by the methods of the Java API, or by the
Java virtual machine itself.
EXCeptlo
n
ThrowablC
InlCrrupt CdE xCCpti0i› Ru tImCE <CCptigI1
arithmCtiCExCrption NullPointcr
l
ErrD
r
ThrCadoreth
çIassCas‹Ex:cpti0i›
Summary of
OOPS
The following are the basic oops concepts: They are as
follows:
1. Objects.
2. Classes.
3. Data Abstraction.
4. Data Encapsulation.
5. Inheritance.
6. Polymorphism.
7. Dynamic Binding.
8. Message Passing.
Abstraction in Object-Oriented Programming
Procedural Abstraction
• Procedural Abstractions organize instructions.
Function Power
Give me two numbers (base & exponent)
I’ll return baseexponent
Implementation
Data Abstraction
• Data Abstractions organize data.
Name (string)
Marks (num)
Grade (char)
Student Number (num)
StudentTyp
e
Behavioral Abstraction
Is
Empty
Dequeu
e
Initializ
e
• Behavioral Abstractions combine
procedural and data abstractions.
Queue Object
Enqueue
Is Full
Data State
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
theart of programming
⚫The development of Java was driven by both
in equal measures.
⚫Many Java features are inherited from
theearlier 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 theseappliances more “intelligent”.
Java: History (contd.)
program to
crash.
machines to
crash.
⚫ C++ is powerful, butalso dangerous. The powerand
popularity of C derived from the extensive use of pointers.
However, any incorrect use of pointers can cause memory
leaks, leading the
⚫ 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 thata 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
⚫ A design for consumerelectronics has to be robust.
⚫ Replacing pointers by references, and automating
memory management was the proposed solution.
L
1.5
Java: History (contd.)
⚫ Hence, the team built a new programming language called
Oak, which avoided potentially dangerous constructs in C+
+, such as pointers, pointerarithmetic, operatoroverloading
etc.
⚫ Introduced automaticmemory management, freeing the
programmerto concentrate on other things.
⚫ Architectureneutrality (Platform independence)
⚫ Manydifferent CPU’s are used as controllers.
Hardwarechipsare evolving rapidly. As better chips become
available, older chips becomeobsolete 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 softwareand programming language had to be
architecture
neutral.
Java: History (contd)
⚫ 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
⚫ Internetprogramming 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.
Java History
⚫ 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
cannotaccess other parts of the computer.
⚫Portability: Many types of computers
and operating systemsare in use
throughout the world—and many are
connected to the Internet.
⚫For programs to be dynamically
downloaded to all thevarious 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.
L
1.13
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
⚫ 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
⚫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.
L
1.16
⚫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
⚫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
L
1.18
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.
⚫ 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
L
1.20
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
Variables
⚫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.
L
2.2
Basic Variable Declaration
⚫datatype identifier [=value];
⚫datatype must be
⚫A simple datatype
⚫User defined datatype (class type)
⚫Identifier is a recognizable name confirm to
identifier rules
⚫Value is an optional initial value.
Variable Declaration
⚫We can declare several variables at the
same time: type identifier [=value][,
identifier [=value] …];
Examples:
int a, b, c;
int d = 3, e, f =
5; byte g = 22;
double pi =
3.14159; charch
= 'x';
L
2.4
Variable Scope
⚫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 A scope is defined by a block:
{
…
}
A variable declared inside the scope is not
visible outside:
{
int n;
}
n = 1;// this is illegal
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;
L
2.8
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: int array[][];
int array = new int[2]
[3];
1)declaration:
2) creation:
3) initializatio
nint 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
L
2.13
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 ;
Basic Arithmetic Operators
+ op1 + op2 ADD
- op1 - op2 SUBSTRACT
* op1 * op2 MULTIPLY
/ op1 / op2 DIVISION
% op1 % op2 REMAINDER
L
2.15
Relational operator
== Equals to Apply to any type
!= Not equals to Apply to any type
> Greater than Apply to numerical type
< Less than Apply to numerical type
>= Greater than or equal Apply to numerical type
<= Less than or equal Apply to numerical type
Logical operators
& op1 & op2 Logical AND
| op1 | op2 Logical OR
&& op1 && op2 Short-
circuit AND
|| op1 || op2 Short-circuit OR
! ! op Logical NOT
^ op1 ^ op2 Logical XOR
L
2.17
Bit wise operators
~ ~op Inverts all bits
& op1 & op2 Produces 1 bit if both operands are 1
| op1 |op2 Produces 1 bit if either operand is 1
^ op1 ^ op2 Produces 1 bit if exactly one operand is
1
>> 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
⚫ 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 index0:
" + anArray[0]);
int result = 1 + 2; // result
is now 3 if(value1 == value2)
System.out.println("value1 == value2");
L 2.19
Expressions
Expressions
⚫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 f low 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
L
3.1
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
L
3.3
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 f low of a
program.
L
3.5
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
Type Conversion
• Widening Type Converstion
– Implicit conversion by
compilerautomatically
byte -> short, int, long, float,
double short -> int, long, float,
double char -> int, long, float,
double
int -> long, float, double
long -> float, double
Type Conversion
the conversion
• Narrowing Type
Conversion
– Programmer should
describe explicitly
byte -> char
short -> byte, char
char -> byte, short
int -> byte, short, char
long -> byte, short, char,
int
float -> byte, short, char, int, long
double -> byte, short, char, int, long,
Type Conversion
⚫byte and short are always promoted to
int
⚫if one operand is long, the whole
expression is promoted to long
⚫if one operand is float, the entire
expression is promoted to float
⚫if any operand is double, the result is
double
Type Casting
byte
s
⚫General form: (targetType) value
⚫Examples:
⚫ 1) integer value will be reduced
module range:
int i;
byte b = (byte) i;
⚫ 2) floating-pointvalue will be
truncated to integer value:
f loat f;
int i = (int) f;
L 3.9
Simple Java
Program
⚫A class to display a simple
message: class MyProgram
{
public static void
main(String[] args)
{
System.out.println(“First Java
program.");
}
}
What is an Object?
⚫Real world objects are things that have:
1)state
2)behavi
or
Example:
your dog:
⚫ state – name, color, breed, sits?, barks?,
wages tail?, runs?
⚫behavior – sitting, barking, waging tail,
running
⚫ A software object is a bundle of
What is a Class?
⚫A class is a blueprint that defines the
variables and methods common to all
objects of a certain kind.
⚫Example: ‘your dog’ is a object of the class
Dog.
⚫An object holds values for the variables defines
in the class.
⚫An object is called an instance of the Class
L
4.3
Object Creation
⚫ A variable is declared to refer to the
objects of type/class String:
String s;
⚫ Thevalue of s is null; it does not yet
refer to any object.
⚫ A new String object is created in
memory with initial “abc” value:
⚫String s = new String(“abc”);
⚫Now s contains the address of this new
object.
Object Destruction
⚫A program accumulates memory
through its execution.
⚫Two mechanism to free memory that is no
longer need by the program:
1)manual – done in C/C++
2) automatic – done in Java
⚫In Java, when an object is no longer accessible
through any variable, it is eventually
removed from the memory by the garbage
collector.
⚫Garbage collector is parts of the Java Run-
Time Environment.
L
4.5
Class
⚫A basis for the Java language.
⚫Each concept we wish to describe in Java
must be included inside a class.
⚫A class defines a new data type, whose
values are objects:
⚫A class is a template for objects
⚫An object is an instance of a class
Class Definition
⚫A class contains a name, several variable
declarations (instance variables) and several
method declarations. All are called members of
the class.
⚫General form of a class:
class classname {
type instance-variable-1;
…
type instance-variable-n;
type method-name-1(parameter-list)
{ … }
type method-name-2(parameter-list)
{ … }
…
type method-name-m(parameter-list)
L
4.7
Example: Class Usage
class Box
{ double
width;
double
height;
double
depth;
}
class
BoxDemo {
public static
void
main(String
args[]) {
Box mybox = new
Box(); double vol;
mybox.width = 10;
mybox.height = 20;
Constructor
⚫A constructor initializes the instance variables of an
object.
⚫It is called immediately after the object is created but
before the new operator completes.
1)it is syntactically similar to a method:
2) it has the same name as the name of its class
3) it is written without return type;
the default return type of a class
⚫constructor is the same classWhen the class has no
constructor, the default constructor automatically
initializes all its instance variables with zero.
Example: Constructor
class Box
{ double
width;
double
height;
double
depth; Box()
{
System.out.p
rintln("Const
ructing
Box");
width = 10;
height = 10; L
5.2
Parameterized Constructor
class Box
{ double
width;
double
height;
double
depth;
Box(double w, double h, double
d) { width = w; height = h;
depth = d;
}
double volume()
{ return width * height *
Methods
⚫ General form of a method
definition: type
name(parameter-list) {
…
ret
ur
n
val
ue;
…
}
⚫Components:
1) type - type of values returned by the method. If a
method does not return any value, its return type
must be void.
2) name is the name of the method
L
5.4
Example: Method
⚫ Classes declare methods to hide their internal
data structures, as well as for their own internal
use: Within a class, we can referdirectly to its
member variables:
class Box {
double width, height, depth;
void volume()
{ System.out.print("Volume
is ");
System.out.println(width *
height * depth);
Parameterized Method
⚫ Parameters increase generality and
applicability of a method:
⚫1) method without parameters
int square() { return 10*10; }
⚫2) method with parameters
int square(int i) { return i*i; }
⚫ Parameter: a variable receiving value at
the time the method is invoked.
⚫ Argument: a value passed to the method
when it is invoked.
L
5.6
Access Control: Data Hiding
and Encapsulation
• Java provides control over the visibility of
variables and methods.
• Encapsulation, safely sealing data within the
capsule of the class Prevents programmers
from relying on details of class
implementation, so you can update without
worry
• Helps in protecting against accidental or
wrong usage.
• Keeps code elegant and clean (easier to
maintain)
L
6.2
Access Modifiers: Public,
Private, Protected
• Public: keyword applied to a class,
makes it available/visible everywhere.
Applied to a method orvariable,
completely visible.
• Default(No visibility modifier is
specified): it behaves like public in its
package and private in other
packages.
• Default Public keyword applied to a
class, makes it available/visible
everywhere. Applied to a method or
variable, completely visible.
⚫Private fields or methods for a class only visible
within that class. Private members are not
visible within subclasses, and are not inherited.
⚫Protected members of a class are visible
within the class, subclasses and also within all
classes that are in the same package as that
class.
L
6.4
Visibilit
y
public class Circle {
private double x,y,r;
// Constructor
public Circle (double x, double y, double r)
{ this.x = x;
this.y = y; this.r
= r;
}
//Methods to return circumference and area
public double circumference() { return
2*3.14*r;} public double area() { return 3.14 * r
* r; }
}
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."
L
8.4
⚫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
Charat index 3 in strOb1: s
strOb1 !=
strOb2 strOb1
Ad

More Related Content

Similar to UNIT I OOP AND JAVA FUNDAMENTALS CONSTRUCTOR (20)

Synapseindia strcture of dotnet development part 1
Synapseindia strcture of dotnet development part 1Synapseindia strcture of dotnet development part 1
Synapseindia strcture of dotnet development part 1
Synapseindiappsdevelopment
 
Introduction to OOP concepts
Introduction to OOP conceptsIntroduction to OOP concepts
Introduction to OOP concepts
Ahmed Farag
 
python.pptx
python.pptxpython.pptx
python.pptx
Dhanushrajucm
 
Oops concepts
Oops conceptsOops concepts
Oops concepts
ACCESS Health Digital
 
UNIT1-JAVA.pptx
UNIT1-JAVA.pptxUNIT1-JAVA.pptx
UNIT1-JAVA.pptx
ssuser99ca78
 
Advance oops concepts
Advance oops conceptsAdvance oops concepts
Advance oops concepts
Sangharsh agarwal
 
FAL(2022-23)_CSE0206_ETH_AP2022232000455_Reference_Material_I_16-Aug-2022_Mod...
FAL(2022-23)_CSE0206_ETH_AP2022232000455_Reference_Material_I_16-Aug-2022_Mod...FAL(2022-23)_CSE0206_ETH_AP2022232000455_Reference_Material_I_16-Aug-2022_Mod...
FAL(2022-23)_CSE0206_ETH_AP2022232000455_Reference_Material_I_16-Aug-2022_Mod...
AnkurSingh340457
 
Object oriented basics
Object oriented basicsObject oriented basics
Object oriented basics
vamshimahi
 
Object Oriented Programming (OOP) Introduction
Object Oriented Programming (OOP) IntroductionObject Oriented Programming (OOP) Introduction
Object Oriented Programming (OOP) Introduction
SamuelAnsong6
 
Cs2305 programming paradigms lecturer notes
Cs2305   programming paradigms lecturer notesCs2305   programming paradigms lecturer notes
Cs2305 programming paradigms lecturer notes
Saravanakumar viswanathan
 
SAP-ABAP-Object-Oriented-Programming.pptx
SAP-ABAP-Object-Oriented-Programming.pptxSAP-ABAP-Object-Oriented-Programming.pptx
SAP-ABAP-Object-Oriented-Programming.pptx
aryans3n
 
Jedi slides 2.1 object-oriented concepts
Jedi slides 2.1 object-oriented conceptsJedi slides 2.1 object-oriented concepts
Jedi slides 2.1 object-oriented concepts
Maryo Manjaruni
 
Concepts of oops
Concepts of oopsConcepts of oops
Concepts of oops
Sourabrata Mukherjee
 
Md02 - Getting Started part-2
Md02 - Getting Started part-2Md02 - Getting Started part-2
Md02 - Getting Started part-2
Rakesh Madugula
 
Object Oriented Analysis and Design - OOAD
Object Oriented Analysis and Design - OOADObject Oriented Analysis and Design - OOAD
Object Oriented Analysis and Design - OOAD
PreethaV16
 
java part 1 computer science.pptx
java part 1 computer science.pptxjava part 1 computer science.pptx
java part 1 computer science.pptx
MUHAMMED MASHAHIL PUKKUNNUMMAL
 
Object oriented javascript
Object oriented javascriptObject oriented javascript
Object oriented javascript
Usman Mehmood
 
object oriented programming through java basics
object oriented programming through java basicsobject oriented programming through java basics
object oriented programming through java basics
Rohit Kumar
 
Oops
OopsOops
Oops
PRABHAHARAN429
 
Classes2
Classes2Classes2
Classes2
phanleson
 
Synapseindia strcture of dotnet development part 1
Synapseindia strcture of dotnet development part 1Synapseindia strcture of dotnet development part 1
Synapseindia strcture of dotnet development part 1
Synapseindiappsdevelopment
 
Introduction to OOP concepts
Introduction to OOP conceptsIntroduction to OOP concepts
Introduction to OOP concepts
Ahmed Farag
 
FAL(2022-23)_CSE0206_ETH_AP2022232000455_Reference_Material_I_16-Aug-2022_Mod...
FAL(2022-23)_CSE0206_ETH_AP2022232000455_Reference_Material_I_16-Aug-2022_Mod...FAL(2022-23)_CSE0206_ETH_AP2022232000455_Reference_Material_I_16-Aug-2022_Mod...
FAL(2022-23)_CSE0206_ETH_AP2022232000455_Reference_Material_I_16-Aug-2022_Mod...
AnkurSingh340457
 
Object oriented basics
Object oriented basicsObject oriented basics
Object oriented basics
vamshimahi
 
Object Oriented Programming (OOP) Introduction
Object Oriented Programming (OOP) IntroductionObject Oriented Programming (OOP) Introduction
Object Oriented Programming (OOP) Introduction
SamuelAnsong6
 
SAP-ABAP-Object-Oriented-Programming.pptx
SAP-ABAP-Object-Oriented-Programming.pptxSAP-ABAP-Object-Oriented-Programming.pptx
SAP-ABAP-Object-Oriented-Programming.pptx
aryans3n
 
Jedi slides 2.1 object-oriented concepts
Jedi slides 2.1 object-oriented conceptsJedi slides 2.1 object-oriented concepts
Jedi slides 2.1 object-oriented concepts
Maryo Manjaruni
 
Md02 - Getting Started part-2
Md02 - Getting Started part-2Md02 - Getting Started part-2
Md02 - Getting Started part-2
Rakesh Madugula
 
Object Oriented Analysis and Design - OOAD
Object Oriented Analysis and Design - OOADObject Oriented Analysis and Design - OOAD
Object Oriented Analysis and Design - OOAD
PreethaV16
 
Object oriented javascript
Object oriented javascriptObject oriented javascript
Object oriented javascript
Usman Mehmood
 
object oriented programming through java basics
object oriented programming through java basicsobject oriented programming through java basics
object oriented programming through java basics
Rohit Kumar
 

More from mohanrajm63 (19)

METHOD OVERLOADING AND INHERITANCE INTERFACE
METHOD OVERLOADING AND INHERITANCE INTERFACEMETHOD OVERLOADING AND INHERITANCE INTERFACE
METHOD OVERLOADING AND INHERITANCE INTERFACE
mohanrajm63
 
EVENT DRIVEN PROGRAMMING SWING APPLET AWT
EVENT DRIVEN PROGRAMMING SWING APPLET AWTEVENT DRIVEN PROGRAMMING SWING APPLET AWT
EVENT DRIVEN PROGRAMMING SWING APPLET AWT
mohanrajm63
 
MULTITHREADING PROGRAMMING AND I/O THREAD
MULTITHREADING PROGRAMMING AND I/O THREADMULTITHREADING PROGRAMMING AND I/O THREAD
MULTITHREADING PROGRAMMING AND I/O THREAD
mohanrajm63
 
PACKAGES, INTERFACES AND EXCEPTION HANDLING
PACKAGES, INTERFACES AND EXCEPTION HANDLINGPACKAGES, INTERFACES AND EXCEPTION HANDLING
PACKAGES, INTERFACES AND EXCEPTION HANDLING
mohanrajm63
 
UNIT - 5 INTERFACE APPLIATIONS GROUP WARE SYSTEMS
UNIT - 5 INTERFACE APPLIATIONS GROUP WARE SYSTEMSUNIT - 5 INTERFACE APPLIATIONS GROUP WARE SYSTEMS
UNIT - 5 INTERFACE APPLIATIONS GROUP WARE SYSTEMS
mohanrajm63
 
MODELS AND EVALUATION FRAMEWORK GOALS AND TASK
MODELS AND EVALUATION FRAMEWORK GOALS AND TASKMODELS AND EVALUATION FRAMEWORK GOALS AND TASK
MODELS AND EVALUATION FRAMEWORK GOALS AND TASK
mohanrajm63
 
DESIGN RULES , PROCESS OF DESIGN, USER FOCUS
DESIGN RULES , PROCESS OF DESIGN, USER FOCUSDESIGN RULES , PROCESS OF DESIGN, USER FOCUS
DESIGN RULES , PROCESS OF DESIGN, USER FOCUS
mohanrajm63
 
INTERACTION AND INTERFACES MODEL OF THE INTERACTION
INTERACTION AND INTERFACES MODEL OF THE INTERACTIONINTERACTION AND INTERFACES MODEL OF THE INTERACTION
INTERACTION AND INTERFACES MODEL OF THE INTERACTION
mohanrajm63
 
THE INTRODUCTION - HUMAN AND COMPUTER BASICS
THE INTRODUCTION - HUMAN AND COMPUTER BASICSTHE INTRODUCTION - HUMAN AND COMPUTER BASICS
THE INTRODUCTION - HUMAN AND COMPUTER BASICS
mohanrajm63
 
OBJECT ORIENTED PROGRAMMING , S3 CLASS, S4 CLASS
OBJECT ORIENTED PROGRAMMING , S3 CLASS, S4 CLASSOBJECT ORIENTED PROGRAMMING , S3 CLASS, S4 CLASS
OBJECT ORIENTED PROGRAMMING , S3 CLASS, S4 CLASS
mohanrajm63
 
FACTORS AND TABLES, MINIMUM AND MAXIMA, DISTRIBUTIONS
FACTORS AND TABLES, MINIMUM AND MAXIMA, DISTRIBUTIONSFACTORS AND TABLES, MINIMUM AND MAXIMA, DISTRIBUTIONS
FACTORS AND TABLES, MINIMUM AND MAXIMA, DISTRIBUTIONS
mohanrajm63
 
LISTS, CREATING LIST, ACCESSING LIST AND INDEX
LISTS, CREATING LIST, ACCESSING LIST AND INDEXLISTS, CREATING LIST, ACCESSING LIST AND INDEX
LISTS, CREATING LIST, ACCESSING LIST AND INDEX
mohanrajm63
 
CONTROL STRUCTURES, DATA TYPES AND OBJECTS
CONTROL STRUCTURES, DATA TYPES AND OBJECTSCONTROL STRUCTURES, DATA TYPES AND OBJECTS
CONTROL STRUCTURES, DATA TYPES AND OBJECTS
mohanrajm63
 
R PROGRAMMING INTRODUCTION AND FEATURES,
R PROGRAMMING INTRODUCTION AND FEATURES,R PROGRAMMING INTRODUCTION AND FEATURES,
R PROGRAMMING INTRODUCTION AND FEATURES,
mohanrajm63
 
GRAPHS, BREADTH FIRST TRAVERSAL AND DEPTH FIRST TRAVERSAL
GRAPHS, BREADTH FIRST TRAVERSAL AND DEPTH FIRST TRAVERSALGRAPHS, BREADTH FIRST TRAVERSAL AND DEPTH FIRST TRAVERSAL
GRAPHS, BREADTH FIRST TRAVERSAL AND DEPTH FIRST TRAVERSAL
mohanrajm63
 
TREE ADT, TREE TRAVERSALS, BINARY TREE ADT
TREE ADT, TREE TRAVERSALS, BINARY TREE ADTTREE ADT, TREE TRAVERSALS, BINARY TREE ADT
TREE ADT, TREE TRAVERSALS, BINARY TREE ADT
mohanrajm63
 
SEARCHING AND SORTING ALGORITHMS, TYPES OF SORTING
SEARCHING AND SORTING ALGORITHMS, TYPES OF SORTINGSEARCHING AND SORTING ALGORITHMS, TYPES OF SORTING
SEARCHING AND SORTING ALGORITHMS, TYPES OF SORTING
mohanrajm63
 
STACK AND QUEUES APPLICATIONS, INFIX TO POST FIX
STACK AND QUEUES APPLICATIONS, INFIX TO POST FIXSTACK AND QUEUES APPLICATIONS, INFIX TO POST FIX
STACK AND QUEUES APPLICATIONS, INFIX TO POST FIX
mohanrajm63
 
ALGORITHM ANALYSIS AND LISTS ABSTACTS DT
ALGORITHM ANALYSIS AND LISTS ABSTACTS DTALGORITHM ANALYSIS AND LISTS ABSTACTS DT
ALGORITHM ANALYSIS AND LISTS ABSTACTS DT
mohanrajm63
 
METHOD OVERLOADING AND INHERITANCE INTERFACE
METHOD OVERLOADING AND INHERITANCE INTERFACEMETHOD OVERLOADING AND INHERITANCE INTERFACE
METHOD OVERLOADING AND INHERITANCE INTERFACE
mohanrajm63
 
EVENT DRIVEN PROGRAMMING SWING APPLET AWT
EVENT DRIVEN PROGRAMMING SWING APPLET AWTEVENT DRIVEN PROGRAMMING SWING APPLET AWT
EVENT DRIVEN PROGRAMMING SWING APPLET AWT
mohanrajm63
 
MULTITHREADING PROGRAMMING AND I/O THREAD
MULTITHREADING PROGRAMMING AND I/O THREADMULTITHREADING PROGRAMMING AND I/O THREAD
MULTITHREADING PROGRAMMING AND I/O THREAD
mohanrajm63
 
PACKAGES, INTERFACES AND EXCEPTION HANDLING
PACKAGES, INTERFACES AND EXCEPTION HANDLINGPACKAGES, INTERFACES AND EXCEPTION HANDLING
PACKAGES, INTERFACES AND EXCEPTION HANDLING
mohanrajm63
 
UNIT - 5 INTERFACE APPLIATIONS GROUP WARE SYSTEMS
UNIT - 5 INTERFACE APPLIATIONS GROUP WARE SYSTEMSUNIT - 5 INTERFACE APPLIATIONS GROUP WARE SYSTEMS
UNIT - 5 INTERFACE APPLIATIONS GROUP WARE SYSTEMS
mohanrajm63
 
MODELS AND EVALUATION FRAMEWORK GOALS AND TASK
MODELS AND EVALUATION FRAMEWORK GOALS AND TASKMODELS AND EVALUATION FRAMEWORK GOALS AND TASK
MODELS AND EVALUATION FRAMEWORK GOALS AND TASK
mohanrajm63
 
DESIGN RULES , PROCESS OF DESIGN, USER FOCUS
DESIGN RULES , PROCESS OF DESIGN, USER FOCUSDESIGN RULES , PROCESS OF DESIGN, USER FOCUS
DESIGN RULES , PROCESS OF DESIGN, USER FOCUS
mohanrajm63
 
INTERACTION AND INTERFACES MODEL OF THE INTERACTION
INTERACTION AND INTERFACES MODEL OF THE INTERACTIONINTERACTION AND INTERFACES MODEL OF THE INTERACTION
INTERACTION AND INTERFACES MODEL OF THE INTERACTION
mohanrajm63
 
THE INTRODUCTION - HUMAN AND COMPUTER BASICS
THE INTRODUCTION - HUMAN AND COMPUTER BASICSTHE INTRODUCTION - HUMAN AND COMPUTER BASICS
THE INTRODUCTION - HUMAN AND COMPUTER BASICS
mohanrajm63
 
OBJECT ORIENTED PROGRAMMING , S3 CLASS, S4 CLASS
OBJECT ORIENTED PROGRAMMING , S3 CLASS, S4 CLASSOBJECT ORIENTED PROGRAMMING , S3 CLASS, S4 CLASS
OBJECT ORIENTED PROGRAMMING , S3 CLASS, S4 CLASS
mohanrajm63
 
FACTORS AND TABLES, MINIMUM AND MAXIMA, DISTRIBUTIONS
FACTORS AND TABLES, MINIMUM AND MAXIMA, DISTRIBUTIONSFACTORS AND TABLES, MINIMUM AND MAXIMA, DISTRIBUTIONS
FACTORS AND TABLES, MINIMUM AND MAXIMA, DISTRIBUTIONS
mohanrajm63
 
LISTS, CREATING LIST, ACCESSING LIST AND INDEX
LISTS, CREATING LIST, ACCESSING LIST AND INDEXLISTS, CREATING LIST, ACCESSING LIST AND INDEX
LISTS, CREATING LIST, ACCESSING LIST AND INDEX
mohanrajm63
 
CONTROL STRUCTURES, DATA TYPES AND OBJECTS
CONTROL STRUCTURES, DATA TYPES AND OBJECTSCONTROL STRUCTURES, DATA TYPES AND OBJECTS
CONTROL STRUCTURES, DATA TYPES AND OBJECTS
mohanrajm63
 
R PROGRAMMING INTRODUCTION AND FEATURES,
R PROGRAMMING INTRODUCTION AND FEATURES,R PROGRAMMING INTRODUCTION AND FEATURES,
R PROGRAMMING INTRODUCTION AND FEATURES,
mohanrajm63
 
GRAPHS, BREADTH FIRST TRAVERSAL AND DEPTH FIRST TRAVERSAL
GRAPHS, BREADTH FIRST TRAVERSAL AND DEPTH FIRST TRAVERSALGRAPHS, BREADTH FIRST TRAVERSAL AND DEPTH FIRST TRAVERSAL
GRAPHS, BREADTH FIRST TRAVERSAL AND DEPTH FIRST TRAVERSAL
mohanrajm63
 
TREE ADT, TREE TRAVERSALS, BINARY TREE ADT
TREE ADT, TREE TRAVERSALS, BINARY TREE ADTTREE ADT, TREE TRAVERSALS, BINARY TREE ADT
TREE ADT, TREE TRAVERSALS, BINARY TREE ADT
mohanrajm63
 
SEARCHING AND SORTING ALGORITHMS, TYPES OF SORTING
SEARCHING AND SORTING ALGORITHMS, TYPES OF SORTINGSEARCHING AND SORTING ALGORITHMS, TYPES OF SORTING
SEARCHING AND SORTING ALGORITHMS, TYPES OF SORTING
mohanrajm63
 
STACK AND QUEUES APPLICATIONS, INFIX TO POST FIX
STACK AND QUEUES APPLICATIONS, INFIX TO POST FIXSTACK AND QUEUES APPLICATIONS, INFIX TO POST FIX
STACK AND QUEUES APPLICATIONS, INFIX TO POST FIX
mohanrajm63
 
ALGORITHM ANALYSIS AND LISTS ABSTACTS DT
ALGORITHM ANALYSIS AND LISTS ABSTACTS DTALGORITHM ANALYSIS AND LISTS ABSTACTS DT
ALGORITHM ANALYSIS AND LISTS ABSTACTS DT
mohanrajm63
 
Ad

Recently uploaded (20)

Lecture - 7 Canals of the topic of the civil engineering
Lecture - 7  Canals of the topic of the civil engineeringLecture - 7  Canals of the topic of the civil engineering
Lecture - 7 Canals of the topic of the civil engineering
MJawadkhan1
 
Building-Services-Introduction-Notes.pdf
Building-Services-Introduction-Notes.pdfBuilding-Services-Introduction-Notes.pdf
Building-Services-Introduction-Notes.pdf
Lawrence Omai
 
Surveying through global positioning system
Surveying through global positioning systemSurveying through global positioning system
Surveying through global positioning system
opneptune5
 
ATAL 6 Days Online FDP Scheme Document 2025-26.pdf
ATAL 6 Days Online FDP Scheme Document 2025-26.pdfATAL 6 Days Online FDP Scheme Document 2025-26.pdf
ATAL 6 Days Online FDP Scheme Document 2025-26.pdf
ssuserda39791
 
twin tower attack 2001 new york city
twin  tower  attack  2001 new  york citytwin  tower  attack  2001 new  york city
twin tower attack 2001 new york city
harishreemavs
 
sss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptx
sss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptx
sss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptx
ajayrm685
 
Evonik Overview Visiomer Specialty Methacrylates.pdf
Evonik Overview Visiomer Specialty Methacrylates.pdfEvonik Overview Visiomer Specialty Methacrylates.pdf
Evonik Overview Visiomer Specialty Methacrylates.pdf
szhang13
 
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
ijflsjournal087
 
hypermedia_system_revisit_roy_fielding .
hypermedia_system_revisit_roy_fielding .hypermedia_system_revisit_roy_fielding .
hypermedia_system_revisit_roy_fielding .
NABLAS株式会社
 
JRR Tolkien’s Lord of the Rings: Was It Influenced by Nordic Mythology, Homer...
JRR Tolkien’s Lord of the Rings: Was It Influenced by Nordic Mythology, Homer...JRR Tolkien’s Lord of the Rings: Was It Influenced by Nordic Mythology, Homer...
JRR Tolkien’s Lord of the Rings: Was It Influenced by Nordic Mythology, Homer...
Reflections on Morality, Philosophy, and History
 
Control Methods of Noise Pollutions.pptx
Control Methods of Noise Pollutions.pptxControl Methods of Noise Pollutions.pptx
Control Methods of Noise Pollutions.pptx
vvsasane
 
Computer Security Fundamentals Chapter 1
Computer Security Fundamentals Chapter 1Computer Security Fundamentals Chapter 1
Computer Security Fundamentals Chapter 1
remoteaimms
 
Transport modelling at SBB, presentation at EPFL in 2025
Transport modelling at SBB, presentation at EPFL in 2025Transport modelling at SBB, presentation at EPFL in 2025
Transport modelling at SBB, presentation at EPFL in 2025
Antonin Danalet
 
Artificial intelligence and machine learning.pptx
Artificial intelligence and machine learning.pptxArtificial intelligence and machine learning.pptx
Artificial intelligence and machine learning.pptx
rakshanatarajan005
 
Dynamics of Structures with Uncertain Properties.pptx
Dynamics of Structures with Uncertain Properties.pptxDynamics of Structures with Uncertain Properties.pptx
Dynamics of Structures with Uncertain Properties.pptx
University of Glasgow
 
Prediction of Flexural Strength of Concrete Produced by Using Pozzolanic Mate...
Prediction of Flexural Strength of Concrete Produced by Using Pozzolanic Mate...Prediction of Flexural Strength of Concrete Produced by Using Pozzolanic Mate...
Prediction of Flexural Strength of Concrete Produced by Using Pozzolanic Mate...
Journal of Soft Computing in Civil Engineering
 
Novel Plug Flow Reactor with Recycle For Growth Control
Novel Plug Flow Reactor with Recycle For Growth ControlNovel Plug Flow Reactor with Recycle For Growth Control
Novel Plug Flow Reactor with Recycle For Growth Control
Chris Harding
 
最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制
最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制
最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制
Taqyea
 
Machine foundation notes for civil engineering students
Machine foundation notes for civil engineering studentsMachine foundation notes for civil engineering students
Machine foundation notes for civil engineering students
DYPCET
 
Slide share PPT of NOx control technologies.pptx
Slide share PPT of  NOx control technologies.pptxSlide share PPT of  NOx control technologies.pptx
Slide share PPT of NOx control technologies.pptx
vvsasane
 
Lecture - 7 Canals of the topic of the civil engineering
Lecture - 7  Canals of the topic of the civil engineeringLecture - 7  Canals of the topic of the civil engineering
Lecture - 7 Canals of the topic of the civil engineering
MJawadkhan1
 
Building-Services-Introduction-Notes.pdf
Building-Services-Introduction-Notes.pdfBuilding-Services-Introduction-Notes.pdf
Building-Services-Introduction-Notes.pdf
Lawrence Omai
 
Surveying through global positioning system
Surveying through global positioning systemSurveying through global positioning system
Surveying through global positioning system
opneptune5
 
ATAL 6 Days Online FDP Scheme Document 2025-26.pdf
ATAL 6 Days Online FDP Scheme Document 2025-26.pdfATAL 6 Days Online FDP Scheme Document 2025-26.pdf
ATAL 6 Days Online FDP Scheme Document 2025-26.pdf
ssuserda39791
 
twin tower attack 2001 new york city
twin  tower  attack  2001 new  york citytwin  tower  attack  2001 new  york city
twin tower attack 2001 new york city
harishreemavs
 
sss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptx
sss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptx
sss1.pptxsss1.pptxsss1.pptxsss1.pptxsss1.pptx
ajayrm685
 
Evonik Overview Visiomer Specialty Methacrylates.pdf
Evonik Overview Visiomer Specialty Methacrylates.pdfEvonik Overview Visiomer Specialty Methacrylates.pdf
Evonik Overview Visiomer Specialty Methacrylates.pdf
szhang13
 
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
6th International Conference on Big Data, Machine Learning and IoT (BMLI 2025)
ijflsjournal087
 
hypermedia_system_revisit_roy_fielding .
hypermedia_system_revisit_roy_fielding .hypermedia_system_revisit_roy_fielding .
hypermedia_system_revisit_roy_fielding .
NABLAS株式会社
 
Control Methods of Noise Pollutions.pptx
Control Methods of Noise Pollutions.pptxControl Methods of Noise Pollutions.pptx
Control Methods of Noise Pollutions.pptx
vvsasane
 
Computer Security Fundamentals Chapter 1
Computer Security Fundamentals Chapter 1Computer Security Fundamentals Chapter 1
Computer Security Fundamentals Chapter 1
remoteaimms
 
Transport modelling at SBB, presentation at EPFL in 2025
Transport modelling at SBB, presentation at EPFL in 2025Transport modelling at SBB, presentation at EPFL in 2025
Transport modelling at SBB, presentation at EPFL in 2025
Antonin Danalet
 
Artificial intelligence and machine learning.pptx
Artificial intelligence and machine learning.pptxArtificial intelligence and machine learning.pptx
Artificial intelligence and machine learning.pptx
rakshanatarajan005
 
Dynamics of Structures with Uncertain Properties.pptx
Dynamics of Structures with Uncertain Properties.pptxDynamics of Structures with Uncertain Properties.pptx
Dynamics of Structures with Uncertain Properties.pptx
University of Glasgow
 
Novel Plug Flow Reactor with Recycle For Growth Control
Novel Plug Flow Reactor with Recycle For Growth ControlNovel Plug Flow Reactor with Recycle For Growth Control
Novel Plug Flow Reactor with Recycle For Growth Control
Chris Harding
 
最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制
最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制
最新版加拿大魁北克大学蒙特利尔分校毕业证(UQAM毕业证书)原版定制
Taqyea
 
Machine foundation notes for civil engineering students
Machine foundation notes for civil engineering studentsMachine foundation notes for civil engineering students
Machine foundation notes for civil engineering students
DYPCET
 
Slide share PPT of NOx control technologies.pptx
Slide share PPT of  NOx control technologies.pptxSlide share PPT of  NOx control technologies.pptx
Slide share PPT of NOx control technologies.pptx
vvsasane
 
Ad

UNIT I OOP AND JAVA FUNDAMENTALS CONSTRUCTOR

  • 1. 20IT301 JAVA PROGRAMMING By M.Mohanraj Assistant Professor Department of Artificial Intelligence and Data Science Kongunadu College of Engineering
  • 2. UNIT I ⚫ OOP concepts- Data abstraction- encapsulation- inheritance- benefits of inheritance- polymorphism-classes and objects- procedural and object oriented programming paradigm. ⚫Java programming – History of java- comments data types-variables-constants-scope and life time of variables- operators-operator hierarchy- expressions-type conversion and casting- enumerated types- control flow – block scope- conditional statements-loops-break and continue statements- simple java stand alone programs-arrays- console input and output- formatting output-constructors- methods- parameter passing- static fields and methods- access control- this reference- overloading methods and constructors-recursion-garbage collection- building strings- exploring string class
  • 3. Need for OOP Paradigm  OOP is an approach to program organization and development, which attempts to eliminate some of the drawbacks of conventional programming methods by incorporating the best of structured programming features with several new concepts.  OOP allows us to decompose a problem into number of entities called objects and then build data and methods (functions) around these entities.  The data of an object can be accessed only by the methods associated with the object.
  • 4. Introduction ⚫Object-oriented programming (OOP) is a programming paradigm that uses “Objects “and their interactions to design applications. ⚫ It simplifies the software development and maintenance by providing some concepts: ⚫Object ⚫Class ⚫Data Abstraction & Encapsulation ⚫Inheritance ⚫Polymorphism ⚫Dynamic Binding
  • 5. Object ⚫ Objects are the basic run time entities in an object- oriented system. They may represent a person, a place, a bank account, a table of data or any item that the program has to handle.
  • 7. Class ⚫The entire set of data and code of an object can be made of a user defined data type with the help of a class. ⚫In fact, Objects are variables of the type class. Once a class has been defined, we can create any number of objects belonging to that class. ⚫Classes are data types based on which objects are created. Objects with similar properties and methods are grouped together to form a Class. Thus a Class represents a set of individual objects.
  • 8. ⚫Characteristics of an object are represented in a class as Properties. The actions that can be performed by objects become functions of the class and is referred to as Methods. ⚫ A class is thus a collection of objects of similar type . for example: mango, apple, and orange are members of the class fruit . ex: fruit mango; will create an object mango belonging to the class fruit.
  • 9. Example for class ⚫class Human ⚫{ private: ⚫ EyeColor IColor; ⚫ NAME personname; ⚫ public: ⚫ void SetName(NAME anyName); ⚫ void SetIColor(EyeColor eyecolor); ⚫};
  • 10. Data abstraction ⚫Abstraction refers to the act of representing essential features without including the background details or explanations. since the classes use the concept of data abstraction ,they are known as abstraction data type(ADT). For example, a class Car would be made up of an Engine, Gearbox, Steering objects, and many more components. To build the Car class, one does not need to know how the different components work internally, but only how to interface with them, i.e., send messages to them, receive messages from them, and perhaps make the different objects composing the class interact with each other.
  • 11. An example for abstraction ⚫ Humans manage complexity through abstraction. When you drive your car you do not have to be concerned with the exact internal working of your car(unless you are a mechanic). What you are concerned with is interacting with your car via its interfaces like steering wheel, brake pedal, accelerator pedal etc. Various manufacturers of car has different implementation of car working but its basic interface has not changed (i.e. you still use steering wheel, brake pedal, accelerator pedal etc to interact with your car). Hence the knowledgeyou have of your
  • 13. Some of the Object-Oriented Paradigm are: 1. Emphasis is on data rather than procedure. 2. Programs are divided into objects. 3. Data Structures are designed such that they Characterize the objects. 4 Methods that operate on the data of an object are tied together in the data structure. 5 Data is hidden and can not be accessed by external functions. 6 Objects may communicate with each other through methods.
  • 14. A way of viewing world – Agents ⚫OOP uses an approach of treating a real world agent as an object. ⚫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 by switching the controlling entity to data.
  • 15. Start Messag e 0 bj ect Objec t 0 bject 0bj ect ”Object PFogrammi ng Sheì1 Message paths 0 bject 0bj ect 0 bject message to environme nt Message from environmen t
  • 16. Responsibility ⚫primary motivation is the need for a platform-independent (that is, architecture- neutral) language that could be used to create software to be embedded in various consumer electronic devices, such as microwave ovens and remote controls. ⚫Objects with clear responsibilities. ⚫Each class should have a clear responsibility. ⚫If you can't state the purpose of a class in a single, clear sentence, then perhaps your class structure needs some thought.
  • 17. Messages ⚫We all like to use programs that let us know what's going on. Programs that keep us informed often do so by displaying status and error messages. ⚫These messages need to be translated so they can be understood by end users around the world. ⚫ ⚫The Section discusses translatable text messages. Usually, you're done after you move a message String into a ResourceBundle. ⚫If you've embedded variable data in a message, you'll have to take some extra steps to prepare it for translation.
  • 18. Methods ⚫A method is a group of instructions that is given a name and can be called up at any point in a program simply by quoting that name. ⚫Drawing a Triangle require draw of three straight lines. This instruction three times to draw a simple triangle. ⚫We can define a method to call this instruction three times and draw the triangle(i.e. create a method drawLine() to draw lines and this method is called repeatedly to achieve the needed task) ⚫The idea of methods appears in all programming languages, although sometimes it goes under the name functions and sometimes under the name procedures. ⚫The name methods is a throw-back to the language C++, from which Java was developed. ⚫In C++, there is an object called a class which can contain methods. However, everything in Java is enclosed within a class .so the functions within it are called methods
  • 19. CLASSES • Class is blue print or an idea of an Object • From One class any number of Instances can be created • It is an encapsulation of attributes and methods FIGUR E CIRCL E SQUARE Ob1 Ob2 RECTANGLE Ob3 class
  • 20. syntax of CLASS class <ClassName> { attributes/variables; Constructors(); methods(); }
  • 21. INSTANCE • Instance is an Object of a class which is an entity with its own attribute values and methods. • Creating an Instance ClassName refVariable; refVariable = new Constructor(); or ClassName refVariable = new
  • 22. Java Class Hierarchy • In Java, class “Object” is the base class to all other classes – If we do not explicitly say extends in a new class definition, it implicitly extends Object – The tree of classes that extend from Object and all of its subclasses are is called the class hierarchy – All classes eventually lead back up to Object – This will enable consistent access of objects of different classes.
  • 23. Inheritance ⚫Methods allows to reuse a sequence of statements ⚫Inheritance allows to reuse classes by deriving a new class from an existing one ⚫The existing class is called the parent class, or superclass, or base class ⚫The derived class is called the child class or subclass. ⚫The child class inherits characteristics of the parent class(i.e the child class inherits the methods and data defined for the parent class
  • 24. Inheritance ⚫Inheritance relationships are often shown graphically in a class diagram, with the arrow pointing to the parent class Animal weight : int + getWeight() : int Bird + fly() : void
  • 25. Method Binding ⚫Objects are used to call methods. ⚫MethodBinding is an object that can be used to call an arbitrary public method, on an instance that is acquired by evaluating the leading portion of a method binding expression via a value binding. ⚫It is legal for a class to have two or more methods with the same name. ⚫Java has to be able to uniquely associate the invocation of a method with its definition relying on the number and types of arguments. ⚫Therefore the same-named methods must be distinguished: 1) by the number of arguments, or 2) by the types of arguments ⚫Overloading and inheritance are two ways to implement polymorphism.
  • 26. Method Overriding.  There may be some occasions when we want an object to respond to the same method but have different behavior when that method is called.  That means, we should override the method defined in the super class. This is possible by defining a method in a sub class that has the same name, same arguments and same return type as a method in the super class.  Then when that method is called, the method defined in the sub class is invoked and executed instead of the one in the super class. This is known as overriding.
  • 27. Exceptions in Java • Exception is an abnormal condition that arises in the code sequence. • Exceptions occur during compile time or run time. • “throwable” is the super class in exception hierarchy. • Compile time errors occurs due to incorrect syntax. • Run-time errors happen when – User enters incorrect input – Resource is not available (ex. file) – Logic error (bug) that was not fixed
  • 28. Exception classes ⚫In Java, exceptions are objects. When you throw an exception, you throw an object. You can't throw just any object as an exception, however -- only those objects whose classes descend from Throwable. ⚫Throwable serves as the base class for an entire family of classes, declared in java.lang, that your program can instantiate and throw. ⚫Throwable has two direct subclasses, Exception and Error. ⚫Exceptions are thrown to signal abnormal conditions that can often be handled by some catcher, though it's possible they may not be caught and therefore could result in a dead thread. ⚫Errors are usually thrown for more serious problems, such as OutOfMemoryError, that may not be so easy to handle. In general, code you write should throw only exceptions, not errors. ⚫Errors are usually thrown by the methods of the Java API, or by the Java virtual machine itself.
  • 29. EXCeptlo n ThrowablC InlCrrupt CdE xCCpti0i› Ru tImCE <CCptigI1 arithmCtiCExCrption NullPointcr l ErrD r ThrCadoreth çIassCas‹Ex:cpti0i›
  • 30. Summary of OOPS The following are the basic oops concepts: They are as follows: 1. Objects. 2. Classes. 3. Data Abstraction. 4. Data Encapsulation. 5. Inheritance. 6. Polymorphism. 7. Dynamic Binding. 8. Message Passing.
  • 31. Abstraction in Object-Oriented Programming Procedural Abstraction • Procedural Abstractions organize instructions. Function Power Give me two numbers (base & exponent) I’ll return baseexponent Implementation
  • 32. Data Abstraction • Data Abstractions organize data. Name (string) Marks (num) Grade (char) Student Number (num) StudentTyp e
  • 33. Behavioral Abstraction Is Empty Dequeu e Initializ e • Behavioral Abstractions combine procedural and data abstractions. Queue Object Enqueue Is Full Data State
  • 34. 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 theart of programming ⚫The development of Java was driven by both in equal measures. ⚫Many Java features are inherited from theearlier languages: B  C  C++  Java
  • 35. 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.
  • 36. 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.
  • 37. 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 theseappliances more “intelligent”.
  • 38. Java: History (contd.) program to crash. machines to crash. ⚫ C++ is powerful, butalso dangerous. The powerand popularity of C derived from the extensive use of pointers. However, any incorrect use of pointers can cause memory leaks, leading the ⚫ 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 thata 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 ⚫ A design for consumerelectronics has to be robust. ⚫ Replacing pointers by references, and automating memory management was the proposed solution. L 1.5
  • 39. Java: History (contd.) ⚫ Hence, the team built a new programming language called Oak, which avoided potentially dangerous constructs in C+ +, such as pointers, pointerarithmetic, operatoroverloading etc. ⚫ Introduced automaticmemory management, freeing the programmerto concentrate on other things. ⚫ Architectureneutrality (Platform independence) ⚫ Manydifferent CPU’s are used as controllers. Hardwarechipsare evolving rapidly. As better chips become available, older chips becomeobsolete 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 softwareand programming language had to be architecture neutral.
  • 40. Java: History (contd) ⚫ 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 ⚫ Internetprogramming 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.
  • 41. Java History ⚫ 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.
  • 42. 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
  • 43. ⚫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
  • 44. ⚫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.
  • 45. ⚫ 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 cannotaccess other parts of the computer.
  • 46. ⚫Portability: Many types of computers and operating systemsare in use throughout the world—and many are connected to the Internet. ⚫For programs to be dynamically downloaded to all thevarious 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. L 1.13
  • 47. 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
  • 48. ⚫ 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
  • 49. ⚫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. L 1.16
  • 50. ⚫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
  • 51. ⚫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 L 1.18
  • 52. 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.
  • 53. ⚫ 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 L 1.20
  • 54. 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
  • 55. Variables ⚫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. L 2.2
  • 56. Basic Variable Declaration ⚫datatype identifier [=value]; ⚫datatype must be ⚫A simple datatype ⚫User defined datatype (class type) ⚫Identifier is a recognizable name confirm to identifier rules ⚫Value is an optional initial value.
  • 57. Variable Declaration ⚫We can declare several variables at the same time: type identifier [=value][, identifier [=value] …]; Examples: int a, b, c; int d = 3, e, f = 5; byte g = 22; double pi = 3.14159; charch = 'x'; L 2.4
  • 58. Variable Scope ⚫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 A scope is defined by a block: { … } A variable declared inside the scope is not visible outside: { int n; } n = 1;// this is illegal
  • 59. 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!
  • 60. 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.
  • 61. 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; L 2.8
  • 62. 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.
  • 63. 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.
  • 64. 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
  • 65. Multidimensional Arrays ⚫Multidimensional arrays are arrays of arrays: int array[][]; int array = new int[2] [3]; 1)declaration: 2) creation: 3) initializatio nint array[][] = { {1, 2, 3}, {4, 5, 6} };
  • 66. 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 L 2.13
  • 67. 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 ;
  • 68. Basic Arithmetic Operators + op1 + op2 ADD - op1 - op2 SUBSTRACT * op1 * op2 MULTIPLY / op1 / op2 DIVISION % op1 % op2 REMAINDER L 2.15
  • 69. Relational operator == Equals to Apply to any type != Not equals to Apply to any type > Greater than Apply to numerical type < Less than Apply to numerical type >= Greater than or equal Apply to numerical type <= Less than or equal Apply to numerical type
  • 70. Logical operators & op1 & op2 Logical AND | op1 | op2 Logical OR && op1 && op2 Short- circuit AND || op1 || op2 Short-circuit OR ! ! op Logical NOT ^ op1 ^ op2 Logical XOR L 2.17
  • 71. Bit wise operators ~ ~op Inverts all bits & op1 & op2 Produces 1 bit if both operands are 1 | op1 |op2 Produces 1 bit if either operand is 1 ^ op1 ^ op2 Produces 1 bit if exactly one operand is 1 >> 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
  • 72. ⚫ 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 index0: " + anArray[0]); int result = 1 + 2; // result is now 3 if(value1 == value2) System.out.println("value1 == value2"); L 2.19 Expressions
  • 73. Expressions ⚫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
  • 74. Control Statements ⚫Java control statements cause the f low 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 L 3.1
  • 75. 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
  • 76. 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 L 3.3
  • 77. 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 f low of a program.
  • 78. L 3.5 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
  • 79. Type Conversion • Widening Type Converstion – Implicit conversion by compilerautomatically byte -> short, int, long, float, double short -> int, long, float, double char -> int, long, float, double int -> long, float, double long -> float, double
  • 80. Type Conversion the conversion • Narrowing Type Conversion – Programmer should describe explicitly byte -> char short -> byte, char char -> byte, short int -> byte, short, char long -> byte, short, char, int float -> byte, short, char, int, long double -> byte, short, char, int, long,
  • 81. Type Conversion ⚫byte and short are always promoted to int ⚫if one operand is long, the whole expression is promoted to long ⚫if one operand is float, the entire expression is promoted to float ⚫if any operand is double, the result is double
  • 82. Type Casting byte s ⚫General form: (targetType) value ⚫Examples: ⚫ 1) integer value will be reduced module range: int i; byte b = (byte) i; ⚫ 2) floating-pointvalue will be truncated to integer value: f loat f; int i = (int) f; L 3.9
  • 83. Simple Java Program ⚫A class to display a simple message: class MyProgram { public static void main(String[] args) { System.out.println(“First Java program."); } }
  • 84. What is an Object? ⚫Real world objects are things that have: 1)state 2)behavi or Example: your dog: ⚫ state – name, color, breed, sits?, barks?, wages tail?, runs? ⚫behavior – sitting, barking, waging tail, running ⚫ A software object is a bundle of
  • 85. What is a Class? ⚫A class is a blueprint that defines the variables and methods common to all objects of a certain kind. ⚫Example: ‘your dog’ is a object of the class Dog. ⚫An object holds values for the variables defines in the class. ⚫An object is called an instance of the Class L 4.3
  • 86. Object Creation ⚫ A variable is declared to refer to the objects of type/class String: String s; ⚫ Thevalue of s is null; it does not yet refer to any object. ⚫ A new String object is created in memory with initial “abc” value: ⚫String s = new String(“abc”); ⚫Now s contains the address of this new object.
  • 87. Object Destruction ⚫A program accumulates memory through its execution. ⚫Two mechanism to free memory that is no longer need by the program: 1)manual – done in C/C++ 2) automatic – done in Java ⚫In Java, when an object is no longer accessible through any variable, it is eventually removed from the memory by the garbage collector. ⚫Garbage collector is parts of the Java Run- Time Environment. L 4.5
  • 88. Class ⚫A basis for the Java language. ⚫Each concept we wish to describe in Java must be included inside a class. ⚫A class defines a new data type, whose values are objects: ⚫A class is a template for objects ⚫An object is an instance of a class
  • 89. Class Definition ⚫A class contains a name, several variable declarations (instance variables) and several method declarations. All are called members of the class. ⚫General form of a class: class classname { type instance-variable-1; … type instance-variable-n; type method-name-1(parameter-list) { … } type method-name-2(parameter-list) { … } … type method-name-m(parameter-list) L 4.7
  • 90. Example: Class Usage class Box { double width; double height; double depth; } class BoxDemo { public static void main(String args[]) { Box mybox = new Box(); double vol; mybox.width = 10; mybox.height = 20;
  • 91. Constructor ⚫A constructor initializes the instance variables of an object. ⚫It is called immediately after the object is created but before the new operator completes. 1)it is syntactically similar to a method: 2) it has the same name as the name of its class 3) it is written without return type; the default return type of a class ⚫constructor is the same classWhen the class has no constructor, the default constructor automatically initializes all its instance variables with zero.
  • 92. Example: Constructor class Box { double width; double height; double depth; Box() { System.out.p rintln("Const ructing Box"); width = 10; height = 10; L 5.2
  • 93. Parameterized Constructor class Box { double width; double height; double depth; Box(double w, double h, double d) { width = w; height = h; depth = d; } double volume() { return width * height *
  • 94. Methods ⚫ General form of a method definition: type name(parameter-list) { … ret ur n val ue; … } ⚫Components: 1) type - type of values returned by the method. If a method does not return any value, its return type must be void. 2) name is the name of the method L 5.4
  • 95. Example: Method ⚫ Classes declare methods to hide their internal data structures, as well as for their own internal use: Within a class, we can referdirectly to its member variables: class Box { double width, height, depth; void volume() { System.out.print("Volume is "); System.out.println(width * height * depth);
  • 96. Parameterized Method ⚫ Parameters increase generality and applicability of a method: ⚫1) method without parameters int square() { return 10*10; } ⚫2) method with parameters int square(int i) { return i*i; } ⚫ Parameter: a variable receiving value at the time the method is invoked. ⚫ Argument: a value passed to the method when it is invoked. L 5.6
  • 97. Access Control: Data Hiding and Encapsulation • Java provides control over the visibility of variables and methods. • Encapsulation, safely sealing data within the capsule of the class Prevents programmers from relying on details of class implementation, so you can update without worry • Helps in protecting against accidental or wrong usage. • Keeps code elegant and clean (easier to maintain)
  • 98. L 6.2 Access Modifiers: Public, Private, Protected • Public: keyword applied to a class, makes it available/visible everywhere. Applied to a method orvariable, completely visible. • Default(No visibility modifier is specified): it behaves like public in its package and private in other packages. • Default Public keyword applied to a class, makes it available/visible everywhere. Applied to a method or variable, completely visible.
  • 99. ⚫Private fields or methods for a class only visible within that class. Private members are not visible within subclasses, and are not inherited. ⚫Protected members of a class are visible within the class, subclasses and also within all classes that are in the same package as that class.
  • 100. L 6.4 Visibilit y public class Circle { private double x,y,r; // Constructor public Circle (double x, double y, double r) { this.x = x; this.y = y; this.r = r; } //Methods to return circumference and area public double circumference() { return 2*3.14*r;} public double area() { return 3.14 * r * r; } }
  • 101. 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
  • 102. ⚫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." L 8.4
  • 103. ⚫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());
  • 104. 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 Charat index 3 in strOb1: s strOb1 != strOb2 strOb1
  翻译: