0% found this document useful (0 votes)
9 views

UNIT-I BASICS Java Programming

Uploaded by

22eg105q15
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

UNIT-I BASICS Java Programming

Uploaded by

22eg105q15
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 125

Java Programming

M. Hari Prasad
Asst. Prof.
Dept. of AI
Anurag University

UNIT-I 1
2 UNIT-I
Contents
Introduction this, static, final keyword
History of Java Garbage collection
Java buzzwords Nested and Inner Classes
Identifiers, Comments String handling.
Separators, Keywords
Data Types, Variables
Scope and life time of variables
Type conversion and casting
Arrays
Operators
Control statements
Classes and objects
Constructors
Methods
3 UNIT-I
4 UNIT-I
Programs
Computer programs, known as software, are instructions to the
computer.

Without programs, a computer is an empty machine.

Computers do not understand human languages, so we need to


use computer languages to communicate with them.

Programs are written using programming languages.

5 UNIT-I
Programming Languages

Machine Language :

Assembly Language :

High-Level Language :

6 UNIT-I
Programming Languages
Machine Language :
Machine language is a set of primitive instructions built into every
computer.
The instructions are in the form of binary code, so you have to enter
binary codes for various instructions.
The programs are highly difficult to read and modify.
For example:

1101101010011010

7 UNIT-I
Programming Languages
Assembly Language :
Assembly languages were developed to make programming easy.
Since the computer cannot understand assembly language, a
program called assembler is used to convert assembly language
programs into machine code. For example, to add two numbers, we
write an instruction in assembly code like this:
ADDF3 R1, R2, R3

8 UNIT-I
Programming Languages
High-Level Language :
The high-level languages are English-like and easy to learn and
program. For example, the following is a high-level language
statement that computes the area of a circle with radius 5:
area = 5 * 5 * 3.1415;

9 UNIT-I
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 this course)

10 UNIT-I
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.

11 UNIT-I
12 UNIT-I
Java’s History
• B led to C,
– C evolved into C++, and
•C++ set the stage for Java
• Much of the character of Java is inherited from
these two languages.
• From C, Java derives its syntax.
• Many of Java’s object-oriented features were
influenced by C++.
UNIT-I 13
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
14
Java’s History
• Java was conceived at Sun Microsystems, Inc. in 1991 by
James Gosling,
Patrick Naughton,
Chris Warth,
Ed Frank, and
Mike Sheridan.

• First name “Oak” in fall 1992 => renamed “Java” in 1995.


Bill Joy,
Arthur van Hoff,
Jonathan Payne,
Frank Yellin, and
Tim Lindholm

UNIT-I 15
Motivation
1. Platform-independent (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. Code
that would run on a variety of CPUs under
differing environments.
2. World Wide Web

UNIT-I 16
Motivation
Java,
• is a programmer’s language
• is cohesive and logically consistent.
• gives the programmer, full control.

UNIT-I 17
JDK Versions
Version
Java SE Version Release Date
Number
JDK 1.0 (Oak) 1 Jan-96
JDK 1.1 1.1 Feb-97
J2SE 1.2 (Playground) 1.2 Dec-98
J2SE 1.3 (Kestrel) 1.3 May-00
J2SE 1.4 (Merlin) 1.4 Feb-02
J2SE 5.0 (Tiger) 1.5 Sep-04
Java SE 6 (Mustang) 1.6 Dec-06
Java SE 7 (Dolphin) 1.7 Jul-11
Java SE 8 1.8 Mar-14
Java SE 9 9 September, 21st 2017
Java SE 10 10 March, 20th 2018
Java SE 11 11 September, 25th 2018
Java SE 12 12 March, 19th 2019
Java SE 13 13 September, 17th 2019
Java SE 14 14 March, 17th 2020
Java SE 15 15 September, 15th 2020
Java SE 16 16 March, 16th 2021

Java SE 17 17
Expected on Sept. 2021

18 UNIT-I
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.

19 UNIT-I
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.

20 UNIT-I
Java is Compiled and Interpreted

Hardware and
Programmer
Operating System

Source Code Byte Code


Text Interprete
Compiler
Editor r
.java file .class file
Notepad, javac java
editplus, appletviewer
Edit etc netscape

21 UNIT-I
Java Translation and Execution
Java source code

Java compiler

Java bytecode

Java
Java interpreter Java interpreter Java interpreter
interpreter
for Windows for Mac for Razr v2
for Linux

22 UNIT-I
22
23 UNIT-I
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

24 UNIT-I
Characteristics of Java
• Java Is Simple Because Java inherits the
• Java Is Object-Oriented C/C++ syntax and many of the
• Java Is Distributed object-oriented features of
C++, learning Java will be
• Java Is Interpreted easier.
• Java Is Robust
• Java Is Secure
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic

25 UNIT-I
Characteristics of Java
• Java Is Simple Java is inherently object-oriented.
• Java Is Object-Oriented Although many object-oriented languages
began strictly as procedural languages,
• Java Is Distributed Java was designed from the start to be
• Java Is Interpreted object-oriented. Object-oriented
programming (OOP) is a popular
• Java Is Robust programming approach that is replacing
• Java Is Secure traditional procedural programming
techniques.
• Java Is Architecture-Neutral
• Java Is Portable One of the central issues in software
development is how to reuse code.
• Java's Performance Object-oriented programming provides
• Java Is Multithreaded great flexibility, modularity, clarity, and
reusability through encapsulation,
• Java Is Dynamic inheritance, and polymorphism.

26 UNIT-I
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented Distributed computing involves
several computers working
• Java Is Distributed together on a network. Java is
• Java Is Interpreted designed to make distributed
computing easy.
• Java Is Robust Java also supports Remote Method
• Java Is Secure Invocation(RMI)

• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic

27 UNIT-I
Characteristics of Java
• Java Is Simple Java enables the creation of
cross-platform programs by compiling
• Java Is Object-Oriented into an intermediate representation
• Java Is Distributed called Java bytecode. This code can be
executed on any system that
• Java Is Interpreted implements the Java Virtual Machine
• Java Is Robust
• Java Is Secure
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic

28 UNIT-I
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented
Java compilers can detect many problems
• Java Is Distributed that would first show up at execution time
• Java Is Interpreted in other languages.

• Java Is Robust Java has eliminated certain types of


• Java Is Secure error-prone programming constructs
found in other languages.
• Java Is Architecture-Neutral
• Java Is Portable Java has a runtime exception-handling
feature to provide programming support
• Java's Performance for robustness.
• Java Is Multithreaded
• Java Is Dynamic

29 UNIT-I
Characteristics of Java
• Java Is Simple By using a Java-compatible web
browser, we can safely download Java
• Java Is Object-Oriented applets without fear of viral infection or
• Java Is Distributed malicious intent.

• Java Is Interpreted Java achieves this protection by


confining a Java program to the Java
• Java Is Robust execution environment and not
• Java Is Secure allowing it access to other parts of the
computer.
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic

30 UNIT-I
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented
• Java Is Distributed
Write once, run anywhere
• Java Is Interpreted With a Java Virtual Machine (JVM), you
• Java Is Robust can write one program that will run on
any platform.
• Java Is Secure
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic

31 UNIT-I
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented
• Java Is Distributed
Because Java is architecture neutral, Java
• Java Is Interpreted programs are portable.
• Java Is Robust They can be run on any platform without
being recompiled.
• Java Is Secure
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic

32 UNIT-I
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented
• Java Is Distributed The Just-in-time compilers allow the
• Java Is Interpreted platform-independent Java programs to be
executed with nearly the same run-time
• Java Is Robust performance as conventional compiled
• Java Is Secure programs
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic

33 UNIT-I
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented
Multithread programming is smoothly
• Java Is Distributed integrated in Java, which allows you to write
• Java Is Interpreted programs that do many things
simultaneously. Whereas in other languages
• Java Is Robust you have to call procedures specific to the
• Java Is Secure operating system to enable multithreading.

• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic

34 UNIT-I
Characteristics of Java
• Java Is Simple
• Java Is Object-Oriented
• Java Is Distributed Java programs carry with them substantial
amounts of run-time type information that is
• Java Is Interpreted used to verify and resolve accesses to objects at
• Java Is Robust run time. This makes it possible to dynamically
link code in a safe and expedient manner.
• Java Is Secure
• Java Is Architecture-Neutral
• Java Is Portable
• Java's Performance
• Java Is Multithreaded
• Java Is Dynamic

35 UNIT-I
OOP Principles
Encapsulation:

Inheritance:

Polymorphism:

36 UNIT-I
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 will
Inheritance: be shared by a set of objects.
The data defined by the class are referred to as
member variables or instance variables.
Polymorphism: The code that operates on that data is referred to as
member methods or just methods.

37 UNIT-I
OOP Principles
Encapsulation:

Inheritance: Inheritance is the process by which one object acquires


the properties of another object.

Polymorphism:

38 UNIT-I
OOP Principles
Encapsulation:

Inheritance:

Polymorphism: Polymorphism is a feature that allows one interface


to be used for a general class of actions.
The specific action is determined by the exact
nature of the situation.

39 UNIT-I
40 UNIT-I
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.
41 UNIT-I
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.

42 UNIT-I
Comments
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.

43 UNIT-I
Separators
() Method definition and invocation, defining precedence in
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.

44 UNIT-I
Keywords
Keywords are reserved words recognized by Java that cannot
be used as identifiers.
Java defines 50 keywords as follows:

enum

45 UNIT-I
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

46 UNIT-I
Integers:

Name Width Range

long 64 -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

int 32 -2,147,483,648 to 2,147,483,647

short 16 -32,768 to 32,767

byte 8 -128 to 127

47 UNIT-I
Floating-Point Types:

Name Width Range

double 64 4.9e-324 to 1.8e+308

float 32 1.4e-045 to 3.4e+038

48 UNIT-I
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.

49 UNIT-I
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.

50 UNIT-I
Literals
Integer Literals:
► Integer literals can be represented using any of the three
bases decimal, octal and hexadecimal.
► 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). The range of hexadecimal digits is 0
to 9 and A to F (a to f) for 10 to 15.
Ex: 0x12, 0X45, 0X1B

51 UNIT-I
Integer Literals:

► Integer literals create a int value which is a 32-bit integer


value and can be assigned even to byte and short if it is
in the range.

► Integer literals can also be used for long, however we can


specify long literals explicitly by appending an upper or
lower case L to integer literal.

Ex: 1234L,0x52dfL

52 UNIT-I
Floating-Point Literals:

► Floating-point numbers represent decimal values with a


fractional component. They can be expressed in either
standard or scientific notation.
Standard notation: 2.34, 3.14159
Scientific notation: 6.022E23, 314159e-5

► Floating-point literals in Java default to double precision.


► To specify a float literal, append an F or f to the constant.
Ex:- 24.89f, 10076.45F
► double literal can also be specified explicitly by appending a
D or d.
Ex:- 24.89, 24.89d, 12.0056D

53 UNIT-I
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.

54 UNIT-I
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.

55 UNIT-I
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

56 UNIT-I
Variables
Declaring a Variable:
In Java, all variables must be declared before they can be used.

type identifier [ =value][, identifier [=value] …];

57 UNIT-I
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.

58 UNIT-I
59 UNIT-I
Type Conversion and Casting
Java supports both automatic type conversion and casting.
Java’s Automatic Conversions:
When one type of data is assigned to another type of variable, an
automatic type conversion will take place if the following two
conditions are met:
• The two types are compatible.
• The destination type is larger than the source type.
When these two conditions are met, a widening conversion takes
place.
Ex:- int to long, byte to int, float to double …

60 UNIT-I
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.

Ex:- int i=257; b=(byte)i;


byte b; i=(int)d;
double d=456.132;

61 UNIT-I
Automatic Type Promotion in Expressions:
Java automatically promotes each byte or short operand to int
when evaluating an expression.
Ex:- byte a=5, b=10;
a=a*b; //error
int c=a*b;
a=(byte)(a*b);
In addition to the above, Java automatic type promotion rules are:
1. If one of the operands is double, the whole expression is
promoted to double.
2. Otherwise, if one of the operands is float, the whole expression is
promoted to float.
3. Otherwise, if one of the operands is long, the whole expression is
promoted to long.

62 UNIT-I
63 UNIT-I
Arrays
An array is a group of like-typed variables that are referred to by a
common name.

One-Dimensional Arrays

Multidimensional Arrays

64 UNIT-I
One-Dimensional Arrays:

The general form of a one-dimensional array declaration is:


type array-var[ ];
type[ ] array-var;
To allocate memory to an array new operator is used.
array-var=new type[size];

Ex:- int nums[ ]; int[ ] vals;


nums= new int[10]; vals=new int[20];

Array initializer will not use new operator.


Ex:- int days[ ]={ 1,2,3,4,5,6,7 };

65 UNIT-I
Multidimensional Arrays:
Multidimensional arrays are arrays of arrays.
Ex:- int twoDim1[ ][ ]=new int[4][5];

int twoDim2[ ][ ]=new int[4][ ];


twoDim2[0]=new int[1];
twoDim2[1]=new int[2];
twoDim2[2]=new int[3];
twoDim2[3]=new int[4];

66 UNIT-I
67 UNIT-I
Operators

Arithmetic Operators

Bitwise Operators

Relational Operators

Boolean Logical Operators

68 UNIT-I
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

69 UNIT-I
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
70 UNIT-I
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

71 UNIT-I
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

72 UNIT-I
Operator Precedence:
() [] .
High ++ -- ~ !
* / %
+ -
>> >>> <<
> >= < <=
== !=
&
^
|
&&
||
?:
Low = Op=

73 UNIT-I
74 UNIT-I
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.

75 UNIT-I
Selection statements:

if
if-else
Nested ifs
The if-else-if ladder
switch
Nested switch Statements.

76 UNIT-I
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

Collection is of any type of collection or array.

int nums[ ]={10,20,30,40,50};


int sum=0;
for(int x : nums) sum+=x;

77 UNIT-I
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 by a colon.
78 UNIT-I
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.

79 UNIT-I
80 UNIT-I
Class Fundamentals
• A class defines a new data type.

• Once defined can be used to create objects of that type.

• A class is a template for an object.

• An object is an instance of a class.

81 UNIT-I
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
}
}
82 UNIT-I
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.

83 UNIT-I
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( );

Ex:- Box mybox; null


class Box
mybox
{
double width;
double height; mybox=new Box( ); width
double depth;
} height
mybox
depth
84 UNIT-I
Assigning Object Reference Variables:
Box b1=new Box();
Box b2;
b2=b1;
After these above statements both b1 b2 refer to the same object.
In the first statement object b1 is created and memory is allocated to it.
After the 3rd statement b2 refers to the same object as b1 refer to.
Any changes made to object through b2 will affect to b1.

width
b1
height Box object
depth
null
b2
85 UNIT-I
86 UNIT-I
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);
} }
87 UNIT-I
88 UNIT-I
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

89 UNIT-I
Variable-Length Arguments(Varargs):

A method that takes a variable number of arguments is called a variable-arity


method (or) a varargs method.

A variable length argument is specified by three periods (…).


Ex:- void add(int … v)

A method can have normal parameters along with a variable-length parameter. The
variable-length parameter must be the last parameter declared by the method.
Ex:- void display(int a, int … p)
void test(boolean a, boolean b, double c, char … d)

There must be only one variable-length parameter

90 UNIT-I
Overloading Varargs Methods:

Varargs methods can be overloaded in two ways:

1) The types of vararg parameter can differ.

2) To add a normal parameter.

91 UNIT-I
Varargs and Ambiguity:
void display(int ... a) void display(int a, int ... v)
{ {
System.out.print("Parameters:"); System.out.print("Parameters:"+a);
for(int x:a) for(int x:v)
System.out.print(" "+x); System.out.print(" "+x);
System.out.println(); System.out.println();
} }
void display(char ... ch) void display(int ... w)
{ {
System.out.print("Parameters:"); System.out.print("Parameters2:");
for(char x:ch)
for(int x:w)
System.out.print(" "+x);
System.out.print(" "+x);
System.out.println();
} System.out.println();
}

s1.display( );
s1.display(10);

92 UNIT-I
93 UNIT-I
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){
breadth=b; length=length; this.length=length;
} breadth=breadth; this.breadth=breadth;
} } }
} }

Rect r1=new Rect( ); Rect r1=new Rect( ); Rect r1=new Rect( );


r1.init(10,20); r1.init(10,20); r1.init(10,20);

94 UNIT-I
static keyword:
Normally, a class member must be accessed only with an object of its class.

It is possible to create a member that can be accessed before any objects of


its class are created and without reference to an object.

To create such a member, precede its declaration with the keyword static.

Such members can be accessed with the class name by the dot operator.
class Sample {
static int a=10; int c=Sample.a+Sample.b;
static int b; Sample.methodOne(5,6);
static void methodOne(int p, int q) {
System.out.println(“p=“+p+”q=“+q);
}
}
95 UNIT-I
static variables:

Instance variables declared as static are essentially global variables.

When objects of a class are declared, no copy of a static variable is made.

All instances of the class share the same static variable.

To initialize static variables, declare a static block which get executed exactly
once, when the class is first loaded.

96 UNIT-I
static methods:

Methods declared as static have several restrictions:

• They can only call other static methods.

• They must only access static data.

• They cannot refer to this and super in any way.

97 UNIT-I
final keyword:
final can be applied for variables, methods and classes.

final variable contents cannot be modified.

final variable must be initialized when it is declared.

Variables declared as final do not occupy memory on a per-instance basis.


A final variable is a constant.

Ex:- final int FILE_NEW=1;


final int FILE_OPEN=2;

98 UNIT-I
99 UNIT-I
Garbage Collection:
In java, objects are dynamically allocated by using the new operator.
Such objects are automatically destroyed and their memory is released when
no references to the objects exists.
The technique that accomplishes this is called garbage collection.
Sometimes an object will need to perform some action when it is destroyed.
Java provides a mechanism called finalization using which we can define
specific actions that will occur when an object is just about to be reclaimed
by the garbage collector.
To add a finalizer to a class, simply define the finalize() method, which the
Java runtime calls this method whenever it is about to recycle an object.

protected void finalize( ) {


// finalization code
}
100 UNIT-I
101 UNIT-I
Nested and Inner Classes:
A class can be defined within another classes. Such classes are known as
nested classes.
The scope of a nested class is bounded by the scope of its enclosing class.
A nested class has access to the members, including private members, of
the class in which it is nested.
The enclosing class does not have access to the members of the nested class.

class A {
// members
class B {
//class B members
}
// members
}
102 UNIT-I
Nested and Inner Classes:

There are two types of nested classes:


► static nested classes
► non-static nested classes.

103 UNIT-I
static Nested Classes:
A static nested class is one which has the static modifier applied.
It must access the members of its enclosing class through an object.

class A {
// members
static class B {
//class B members
}
// members
}

104 UNIT-I
Non-static Nested Classes:
A non-static nested class is also known as inner class.
It has access to all the variables and methods of its outer class.

class A {
// members
class B {
//class B members
}
// members
}

105 UNIT-I
106 UNIT-I
Strings in Java:
A string is a sequence of characters.

Java implements strings as objects of type String class.

When a String object is created, a string is created that cannot be changed.

We can still perform all types of string operations, but each time an existing
string is altered a new String object is created that contains the modifications.

Java provide two classes to create modifiable strings.


They are StringBuffer and StringBuilder.

The classes String, StringBuffer and StringBuilder are defined in java.lang package.
All are final.

107 UNIT-I
Constructors of String class:
String( )
String(char chars[ ])
String(char chars[ ], int startIndex, int numChars)
String(String strObj)
String(byte asciiChars[ ])
String(byte asciiChars[ ],int startIndex,int numChars)
String(StringBuffer strBufObj)
String(int codePoints[ ],int startIndex, int numChars) Added in J2SE 5
String(StringBuilder strBuildObj) Added in J2SE 5

108 UNIT-I
String Literals:

String s = ”abcdefghij”;

String Length:

int length( )

109 UNIT-I
String Concatenation:
The + operator concatenates two strings, producing a String object as the result.

Example1:
String age = “9”;
String s = “He is “ + age + “ years old. “;
System.out.println( s );
The O/P here is “He is 9 years old.”

Example2:
int age = 9;
String s = “He is “ + age + “ years old. “;
System.out.println( s );

The O/P here is also “He is 9 years old.”

110 UNIT-I
String Concatenation:
Example3:
String s = “abcdefghij “ + 20 + 30;
System.out.println( s );
The O/P here is “abcdefghij 2030”

This is because the compiler automatically converts an operand to its string


equivalent whenever the other operand of the + operator is an instance of
String.

Example4:
String s = “abcdefghij “ + (20 + 30);
System.out.println( s );
The O/P here is “abcdefghij 50”

111 UNIT-I
String Conversion and toString( ):
Java converts data into its string representation during concatenation by
calling one of the overloaded versions of the string conversion method
valueOf( ) defined by String class.
valueOf( ) is overloaded for all simple types and for type Object.
static String valueOf(int num)

static String valueOf(byte num)

static String valueOf(double num)

static String valueOf(long num)

static String valueOf(char chars[ ])

static String valueOf(Object ob)

static String valueOf(char chars[ ],int startIndex, int numChars)


112 UNIT-I
String Conversion and toString( ):
For objects, valueOf( ) calls the toString( ) method on the object.

Every class implements toString( ) because it is defined by Object.

The default implementation of toString( ) is sufficient.

We can override toString( ) and provide our own string representations for
objects.

The syntax is:


String toString( )

113 UNIT-I
Example:

class Rect{ class String1


int length,breadth; {
Rect(int x,int y) { public static void main(String args[])
length=x; {
breadth=y; Rect r1=new Rect(10,20);
} String s1=“Rect:”+r1;
} System.out.println(s1);
class Cube { Cube b1=new Cube(10,20,30);
String s2=“Cube:”+b1;
int length,width,height;
System.out.println(s2);
Cube(int x,int y,int z) {
}
length=x;
}
width=y;
height=z; O/P :
} Rect:Rect@82ba41
public String toString( ) { Cube:Hai I am instance of Cube class
return "Hai I am instance of Cube class";
}
}
114 UNIT-I
Character Extraction:

String object cannot be indexed as if they were a character array.


Many of the String methods employ an index into the string for their operation
beginning at zero.

char charAt(int where)


void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)
byte[ ] getBytes( )
char[ ] toCharArray( )

115 UNIT-I
String Comparision:

boolean equals(String str)


boolean equalsIgnoreCase(String str)

boolean regionMatches(int startIndex,String str2, int str2StartIndex,


int numChars)
boolean regionMatches(boolean ignoreCase, int startIndex,String str2,
int str2StartIndex, int numChars)
boolean startsWith(String str)
boolean endsWith(String str)
int compareTo(String str) <0 if invoking string<str
>0 if invoking string>str
0 if two strings are equal

116 UNIT-I
Searching Strings:
int indexOf(int ch) for first occurrence
int lastIndexOf(int ch) for last occurrence
int indexOf(String str)
int lastIndexOf(String str)
int indexOf(int ch, int startIndex)
int lastIndexOf(int ch, int startIndex)
int indexOf(String str, int startIndex)
int lastIndexOf(String str, int startIndex)

startIndex specifies the index at which point the search begins.

117 UNIT-I
Modifying a String:
String substring(int startIndex)
String substring(int startIndex, int endIndex)

String concat(String str)


String replace(char original, char replacement)
String replace(CharSequence original, CharSequence replacement)
Added in J2SE 5

String trim( )

118 UNIT-I
Changing the Case of Characters within a String:

String toLowerCase( )

String toUpperCase( )

119 UNIT-I
Some other String Methods:
int codePointAt(int i) Added by J2SE 5
int codePointBefore(int i) “
int codePointCount(int start,int end) “
boolean contains(CharSequence str) “
boolean contentEquals(CharSequence str) “
boolean contentEquals(StringBuffer str)
static String format(String fmtstr,Object … args) “
static String format(Locale loc, String fmtstr, Object … args) “
boolean matches(String regExp)
int offsetByCodePoints(int start, int num) “
String replaceFirst(String regExp,String newStr)
String replaceAll(String regExp,String newStr)
String[ ] split(String regExp)
String[ ] split(String regExp, int max)
CharSequence subSequence(int startIndex, int stopIndex)
120 UNIT-I
121 UNIT-I
StringBuffer Constructors:

StringBuffer( ) 16 characters
StringBuffer(int size)
StringBuffer(String str) str+16 characters
StringBuffer(CharSequence chars)

122 UNIT-I
Methods:
int length( ) string length
int capacity( ) total allocated capacity
void ensureCapacity(int capacity) preallocate
void setLength(int len)
char charAt(int where)
void setChatAt(int where, char ch)
void getChars(int sourceStart,int sourceEnd,char target[ ],int
targetStart)

Ensures that the capacity of the buffer is at least equal to the specified minimum.
The new capacity is the larger of:
a. The minimumCapacity argument.
b. Twice the old capacity, plus 2.

123 UNIT-I
Methods:
StringBuffer append(String str)
StringBuffer append(int num)
StringBuffer append(Object obj)

StringBuffer insert(int index, String str)


StringBuffer insert(int index, char ch)
StringBuffer insert(int index, Object obj)

StringBuffer reverse( )

StringBuffer delete(int startIndex, int endIndex)


StringBuffer deleteCharAt(int loc)

StringBuffer replace(int startIndex,int endIndex,String str)

String substring(int startIndex)


String substring(int startIndex, int endIndex)

124 UNIT-I
THANK YOU

UNIT-I 125

You might also like