Professional Documents
Culture Documents
Java 1
Java 1
Unit-I
UNIT-I 1
UNIT-I 2
Content
s:Data abstraction Control flow, block scope
Encapsulation Conditional statements
Inheritance Loops
Benefits of inheritance Break and continue statements
Polymorphism Simple java program
Classes and objects Arrays
Procedural and OOP paradigms Input and output, formatting output
Constructors
History of Java Methods, parameter passing
Java buzzwords static fields and methods
Comments Access control
Data types, variables, constants this reference
Scope and life time of variables Overloading methods
Operators, operator hierarchy Overloading constructors
Expressions Recursion
Type conversion and casting Garbage collection
Enumerated types Building strings
Exploring string class
UNIT-I 3
OOP Principles
Encapsulation:
Inheritance:
Polymorphism:
UNIT-I 4
OOP Principles
Encapsulation: Encapsulation is the mechanism that binds
together code and the data it manipulates.
In Java, the basis of encapsulation is the class.
A class defines the structure and behavior that
Inheritance: will be shared by a set of objects.
UNIT-I 5
OOP Principles
Encapsulation:
Polymorphism:
UNIT-I 6
OOP Principles
Encapsulation:
Inheritance:
UNIT-I 7
Forms of Inheritance:
Inheritance for Specialization: The child is special case of the parent class.
Inheritance for Specification: The parent class defines behavior that is
implemented in the child class but not in the parent class.
Inheritance for Construction: The child class makes use of the behavior provided
by the parent class but is not a subtype of the parent class.
Inheritance for Extension: The child class adds new functionality to the parent
class, but does not change any inherited behavior.
Inheritance for Limitation: The child class restricts the use of some of the behavior
inherited from the parent class.
Inheritance for Combination: The child class inherits features from more than one
parent class.
UNIT-I 8
UNIT-I
Benefits of Inheritance:
UNIT-I 9
UNIT-I
UNIT-I 10
Progra
ms
Computer programs, known as software, are instructions to
the computer.
UNIT-I 11
Programming
Languages
Machine Language :
Assembly Language :
High-Level Language
:
UNIT-I 12
Programming
Languages
High-Level Language
:COBOL (COmmon Business Oriented Language)
FORTRAN (FORmula TRANslation)
BASIC (Beginner All-purpose Symbolic Instructional Code)
Pascal (named for Blaise Pascal)
Ada (named for Ada Lovelace)
C (whose developer designed B first)
Visual Basic (Basic-like visual language developed by Microsoft)
Delphi (Pascal-like visual language developed by Borland)
C++ (an object-oriented language, based on C)
Java (We use it in the book)
UNIT-I 13
Compiling Source Code
A program written in a high-level language is called a source
program.
Since a computer cannot understand a source program.
Program called a compiler is used to translate the source
program into a machine language program called an object
program.
The object program is often then linked with other supporting
library code before the object can be executed on the machine.
UNIT-I 14
UNIT-I 15
Java’s History
• Java was conceived by James Gosling at Sun
Microsystems in 1991.
• It took 18 months to develop the first working version.
• This language was initially called “Oak”, but was renamed
“Java” in 1995.
• Java is the name of the island in Indonesia.
• The Java coffee is from the Java island.
• The name was chosen during one of several brainstorming
sessions held by the Java software team.
• "Java" was chosen from among many, many suggestions.
• The name is not an acronym, but rather a reminder of that
hot, aromatic stuff that many programmers like to drink lots
of
UNIT-I 16
UNIT-I 17
JDK Versions
UNIT-I 18
JDK Editions
• Java Standard Edition (J2SE)
• J2SE can be used to develop client-side standalone
applications or applets.
• Java Enterprise Edition (J2EE)
• J2EE can be used to develop server-side applications
such as Java servlets and Java ServerPages.
• Java Micro Edition (J2ME).
• J2ME can be used to develop applications for mobile
devices such as cell phones.
UNIT-I 19
Compiling Java Source
Code
Java was designed to run object programs on any platform.
With Java, you write the program once, and compile the source
program into a special type of object code, known as bytecode.
The bytecode can then run on any computer with a Java Virtual
Machine.
Java Virtual Machine is a software that interprets Java
bytecode.
UNIT-I 20
Java is Compiled and
Interpreted
Hardware and
Programmer
Operating System
UNIT-I 21
Java Translation and
Execution
Java source code
Java compiler
Java bytecode
UNIT-I 22
22
UNIT-I 23
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented
• Java Is Distributed
• Java Is Interpreted
• Java Is Robust
• Java Is Secure
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic
UNIT-I 24
Characteristics of Java
• Java Is Simple Because Java inherits C/
• Java Is Object-Oriented C++ syntax and many of
the object-oriented
• Java Is Distributed
features of C++, learning
• Java Is Interpreted Java will be easier.
• Java Is Robust
• Java Is Secure
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic
UNIT-I 25
Characteristics of Java
• Java Is Simple Java is inherently object-oriented.
• Java Is Object-Oriented Although many object-oriented
languages began strictly as
• Java Is Distributed procedural languages, Java was
designed from the start to be object-
• Java Is Interpreted oriented. Object-oriented
• Java Is Robust programming (OOP) is a popular
programming approach that is
• Java Is Secure replacing traditional procedural
• Java Is Architecture-Neutral
programming techniques.
• Java Is Secure
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic
UNIT-I 28
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented
Java compilers can detect many
• Java Is Distributed problems that would first show up at
execution time in other languages.
• Java Is Interpreted
• Java Is Robust Java has eliminated certain types of
error-prone programming constructs
• Java Is Secure found in other languages.
• Java Is Architecture-Neutral
Java has a runtime exception-
• Java Is Portable handling feature to provide
• Java's Performance programming support for robustness.
• Java Is Multithreaded
• Java Is Dynamic
UNIT-I 29
Characteristics of Java
• Java Is Simple By using a Java-compatible web
browser, we can safely download
• Java Is Object-Oriented Java applets without fear of viral
• Java Is Distributed infection or malicious intent.
• Java Is Dynamic
UNIT-I 32
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented
• Java Is Distributed
• Java Is Interpreted
• Java Is Robust
• Java Is Secure
• Java Is Architecture-Neutral
• Java Is Portable The Just-in-time compilers allow the
platform-independent Java programs to
• Java's Performance be executed with nearly the same run-
• Java Is Multithreaded time performance as conventional
compiled programs
• Java Is Dynamic
UNIT-I 33
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented
Multithread programming is smoothly
• Java Is Distributed integrated in Java, which allows you to
• Java Is Interpreted write programs that do many things
simultaneously. Whereas in other
• Java Is Robust languages you have to call procedures
specific to the operating system to
• Java Is Secure enable multithreading.
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic
UNIT-I 34
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented
• Java Is Distributed
• Java Is Interpreted
• Java Is Robust
• Java Is Secure
• Java Is Architecture-Neutral
Java programs carry with them substantial
• Java Is Portable amounts of run-time type information that
• Java's Performance is used to verify and resolve accesses to
objects at run time. This makes it possible
• Java Is Multithreaded to dynamically link code in a safe and
• Java Is Dynamic expedient manner.
UNIT-I 35
UNIT-I 36
Comment
s
Three types of comments
• Single-line //
• Multi-line /* */
• Documentation comment /** */
This type of comment is used to produce an HTML file
that documents your program.
UNIT-I 37
Naming Conventions
• Variables and method names:
• Use lowercase. If the name consists of several words,
concatenate all in one, use lowercase for the first word,
and capitalize the first letter of each subsequent word in
the name.
For example:- radius, area, computeArea.
• Class names:
• Capitalize the first letter of each word in the name.
Example:- FirstProgram, Sample, DemoBoxWeight.
• Constants:
• Capitalize all letters in constants, and use underscores
to connect words.
Example:- PI, MAX_VALUE.
UNIT-I 38
Identifiers
• An identifier is a sequence of characters that consist of
uppercase and lowercase letters, digits, underscores ( _ ),
and dollar signs ($).
• An identifier must start with a letter, an underscore (_), or a
dollar sign ($). It cannot start with a digit.
• An identifier cannot be a reserved word.
• An identifier cannot be true, false, or null.
• An identifier can be of any length.
UNIT-I 39
Separator
() s and invocation, defining precedence in
Method definition
expressions, in control statements and type casting.
{} Initializing arrays, define blocks of code for classes,
methods and local scopes.
[] Declare array types, dereference array types.
; Terminates statements.
, In variable declaration, in for statement.
. To separate package names from sub packages and
classes and to separate a variable or method from a
reference variable.
UNIT-I 40
Keyword
s words recognized by Java that
Keywords are reserved
cannot be used as identifiers.
Java defines 50 keywords as follows:
enum
UNIT-I 41
Data Types
Java defines eight primitive data types:
byte, short, int, long, char, float, double and boolean.
These are put into four groups:
→ Integers
→ Floating-point numbers
→ Characters
→ Boolean
UNIT-I 42
Integers
:
UNIT-I 43
Floating-Point Types:
UNIT-I 44
Characters:
► In Java, the data type used to store characters is char.
► Java uses Unicode to represent characters.
► Unicode defines a fully international character set that can
represent all of the characters found in all human languages.
Such as Latin, Greek, Arabic, Cyrillic, Hebrew, Katakana,
Hangul and many more.
► For this purpose char is 16 bits width.
► The range of char is 65,536.
► The standard set of characters known as ASCII in Unicode
ranges from 0 to 255.
UNIT-I 45
Booleans:
► Java has a primitive type called boolean for logical values.
► It can have only one of two possible values, true or false.
► It requires one bit.
► When a boolean value is output by println( ), “true” or “false
is displayed.
► If b is boolean variable, then there is no need to write an if
statement like this:
if(b==true) …
► The outcome of a relational operator is boolean value.
UNIT-I 46
Literals
Integer Literals:
► Integer literals can be represented using any of the three
bases decimal, octal, hexadecimal and binary(Java SE 7).
► Any whole number is a decimal(base 10) number.
► Octal(base 8) values are denoted in Java by a leading zero.
Ex: 05, 012,0734
► Hexadecimal(base 16) values are denoted in Java by a
leading zero-x(0x or0X). Digits is 0 to 9, A to F (a to f).
Ex: 0x12, 0X45, 0X1B
► Binary(base 2) values are denoted in by a leading 0b or0B.
UNIT-I 47
Ex: 0b1011, 0B11011
Integer Literals:
Ex: 1234L,0x52dfL
UNIT-I 48
Floating-Point Literals:
D or d.
Ex:- 24.89, 24.89d, 12.0056D
UNIT-I 49
Boolean
Literals:
► There are only two logical values that boolean can have,
true
and false.
► The true literal in Java does not equal 1 nor does the false
literal equal 0.
UNIT-I 50
Character Literals:
A character literal is represented inside a pair of single
quotes.
All of the visible ASCII characters can be directly entered
inside the quotes, such as ‘a’, ‘z’, ‘@’.
For characters that are impossible to enter directly, there
are several escape sequences to enter the character.
UNIT-I 51
Character Escape
Sequence
Escape Sequence Description
\ddd Octal character (ddd)
\uxxxx Hexadecimal Unicode character(xxxx)
\’ Single quote
\” Double quote
\\ Blackslash
\r Carriage return
\n New line
\f Form feed
\t Tab
\b Backspace
UNIT-I 52
Variables
Declaring a Variable:
In Java, all variables must be declared before they can be used.
UNIT-I 53
The Scope and Lifetime of Variables
► A scope determines what objects are visible to other parts of
your program.
► It also determines the lifetime of those objects.
► In Java, the two major scopes are those defined by a class
and those defined by a method.
UNIT-I 54
UNIT-I 55
Type Conversion and Casting
Java supports both automatic type conversion and casting.
UNIT-I 56
Casting Incompatible
Types:
To create a conversion between two incompatible types use
a cast. A cast is an explicit type conversion. The general
form is:
(target-type) value
This type of conversion is some times called a narrowing
conversion.
A different type of conversion will occur when a floating-point
value is assigned to an integer type: truncation.
One-Dimensional
Arrays
Multidimensional Arrays
UNIT-I 60
One-Dimensional Arrays:
UNIT-I 61
Multidimensional
Arrays:
Multidimensional arrays are arrays of arrays.
Ex:- int twoDim1[ ][ ]=new int[4][5];
UNIT-I 62
UNIT-I 63
Operators
Arithmetic Operators
Bitwise Operators
Relational Operators
Boolean Logical
Operators
UNIT-I 64
Arithmetic
Operators:
The operands of the arithmetic operators must be of a numeric
type. These can also be used on char types.
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus
++ Increment
-- Decrement
+= Addition assignment
-= Subtraction assignment
*= Multiplication assignment
/= Division assignment
%= Modulus assignment
UNIT-I 65
Bitwise Operators:
Java defines several bitwise operators which can be applied to the types,
long, int, short, char and byte. These operators act upon the individual bits
of their operands. Operator Description
~ Bitwise unary NOT
& Bitwise AND
| Bitwise OR
^ Bitwise exclisive OR
>> Shift right
>>> Shift right zero fill
<< Shift left
&= Bitwise AND assignment
|= Bitwise OR assignment
^= Bitwise exclisive OR assignment
>>= Shift right assignment
>>>= Shift right zero fill assignment
<<= Shift left assignment
UNIT-I 66
Relational
Operators:
The relational operators determine the relationship that one
operand has to the other. The outcome of these operations is a
boolean value.
Operator Description
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
UNIT-I 67
Boolean Logical
Operators:
These operators operate only on boolean operands and result
a boolean value.
Operator Description
& Logical AND
| Logical OR
^ Logical XOR
|| Short-circuit OR
&& Short-circuit AND
! Logical unary NOT
&= AND assignment
|= OR assignment
^= XOR assignment
== Equal to
!= Not equal to
?: Ternary if-then-else
UNIT-I 68
Operator Precedence:
() [] .
High
++ -- ~ !
* / %
+ -
>> >>> <<
> >= < <=
== !=
&
^
|
&&
||
Low
?:
= Op= UNIT-I 69
UNIT-I 70
Control Statements
Java’s control statements are put into three categories:
• Selection statements: if and switch.
• Iteration statements: for, while and do-while.
• Jump statements: break, continue and return.
UNIT-I 71
Selection statements:
if
if-else
Nested ifs
The if-else-if ladder
switch
Nested switch Statements.
UNIT-I 72
Iteration
statements:
while
do-while
for
In J2SE 5 a new version of for loop known as For-Each loop
was introduced.
Its general form is:
for( type itr-var : collection) statement-block
UNIT-I 73
Jump Statements:
break:
In java, the break statement has three uses,
• In a switch statement.
• To exit a loop.
• Can be used as a form of goto.
The general form of the third type of break is:
break label;
Label is the name of a label that identifies a block of code.
When this form of break executes control is transferred out of
the named block of code.
Java label is a valid identifier followed
UNIT-I
by a colon. 74
continue:
Used in loops.
Also used with label.
The general form of continue with label is:
continue label;
return:
The return statement is used to explicitly return from a method.
UNIT-I 75
UNIT-I 76
Class Fundamentals
• A class defines a new data type.
UNIT-I 77
The general form of a class definition is:
class classname {
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list){
// body of method
}
type methodname2(parameter-list){
// body of method
}
// . . .
type methodnameM(parameter-list){
// body of method
}
UNIT-I 78
}
Class Fundamentals
• The data (or) variables defined within a class are called instance
variables because each instance (object) of the class contains its own
copy of these variables.
• The code is contained within methods.
• Collectively, the methods and variables defined within a class are called
members of the class.
UNIT-I 79
Declaring Objects:
The object is defined in two-steps:
1. Declare a variable of the class type.
classname class-var;
2. Acquire an actual, physical copy of the object and assign it to that
variable using a new operator.
class-var=new classname( );
width
b1
height Box object
depth
nul
l
b2
UNIT-I 81
UNIT-I
UNIT-I
UNIT-I 84
Constructors:
A constructor initializes an object immediately upon creation.
It has the same name as the class in which it resides.
Similar to a method but does not have a return type.
Automatically called immediately after the object creation, before new
operator completes.
The constructor’s job is to initialize the internal state of an object.
Constructors can be with no parameters (default) as well as with
parameters.
Ex:-
Box( ) { Box(double w, double h, double d) { Box b1=new Box( );
width=10; width=w;
height=20; height=h;
depth=30; depth=d; Box b2=new Box(40,50,60);
} }
UNIT-I 85
UNIT-I
UNIT-I 87
Methods:
The general form of a method:
type name(parameter-list){
// body of method
}
Overloading Methods:
• In a class, if two or more methods are defined with the same name and
different parameter declarations, then the methods are said to be
overloaded
and the process is referred to as method overloading.
• Method overloading is one of the ways that Java supports polymorphism.
• Variable-Length Arguments
UNIT-I 88
UNIT-I
UNIT-I 90
The this Keyword:
‘this’ keyword can be used inside any method to refer to the current object.
class Rect { class Rect { class Rect {
int length,breadth; int length,breadth; int length,breadth;
void init(int a, int b){ void init(int length, void init(int length,
length=a; int breadth){
int breadth){ this.length=length;
breadth=b;
length=length;
} this.breadth=breadth;
breadth=breadth;
} }
} }
}
Factorial of 3 is 6
Factorial of 4 is 24
Factorial of 5 is 120
UNIT-I
Introducing Nested and Inner Classes:
It is possible to define a class within another class; such classes are known as
nested classes. The scope of a nested class is bounded by the scope of its
enclosing class. Thus, if class B is defined within class A, then B does not exist
independently of A. A nested class has access to the members, including private
members, of the class in which it is nested. However, the enclosing class does not
have access to the members of the nested class. A nested class that is declared
directly within its enclosing class scope is a member of its enclosing class. It is also
possible to declare a nested class that is local to a block.
UNIT-I
UNIT-I
Exploring the String Class:
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");
If you need to change a string, you can always create a new one that contains the
modifications. • Java defines peer classes of String, called StringBuffer and
StringBuilder, which allow strings to be altered, so all of the normal string
manipulations are still available in Java.
Strings can be constructed in a variety of ways. The easiest is to use a statement
like this:
UNIT-I
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( ).
boolean equals(secondStr)
int length( )
char charAt(index)
UNIT-I
UNIT-I