[Go to site: main page, start]

0% found this document useful (0 votes)
12 views554 pages

Java Notes (SpringBoot Course)

This document provides an introduction to Java programming, covering its features, history, and comparisons with other languages like C and C++. It outlines the structure of Java programs, the Java Virtual Machine, and the different versions of Java, including Java SE, EE, and ME. Additionally, it discusses basic programming constructs, including variables, constants, and data types.

Uploaded by

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

Java Notes (SpringBoot Course)

This document provides an introduction to Java programming, covering its features, history, and comparisons with other languages like C and C++. It outlines the structure of Java programs, the Java Virtual Machine, and the different versions of Java, including Java SE, EE, and ME. Additionally, it discusses basic programming constructs, including variables, constants, and data types.

Uploaded by

ayushgoyal8755
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Java Technologies

Session 1:

Learning Objectives

By the end of this session, you must be able to

➢ Introduction to Java

➢ List and explain Java features

➢ Differentiate between C++ and Java

➢ Write a simple Java program

➢ HelloWorld
Introduction to Java
Programming Language Levels
• A programming language specifies the words and symbols that we
can use to write a program by following certain rules

• There are three programming language levels:


– Machine language
– Assembly language
– High-level language

• Each type of CPU has its own specific machine language

• The other levels were created to make it easier for a human being
to write programs
Programming Languages
● Machine language

o computer’s native language


o sequence of zeroes and ones (binary)
o different computers understand different sequences
o hard for humans to understand:
o 01010001...
Programming Languages
● Assembly language
o mnemonics for machine language
o low level: each instruction is minimal
o still hard for humans to understand:
▪ ADD, LOAD, JMP etc.,
Programming Languages
● High-level languages
o C, C++, Java, C#, Python, JavaScript, Ruby, Perl, etc.
o high level: each instruction is composed of many low-level
instructions
o closer to English and high school algebra
o easier to read and understand
o hypotenuse = [Link](leg1 * leg1 + leg2 * leg2);
Language Translators
• Machine language is the only language capable of directly instructing
the CPU
• Every non machine language program instruction must be translated
into machine language prior to execution
• Language Translators convert High-level code into machine
language

• Interpreters translate one program statement at a time, as the


program is running

• Compilers translate a complete program into machine language,


then the machine language program is executed as needed

• Because compiled programs run faster than programs that are


translated line by line by an interpreter, programmers usually
choose compilers to translate frequently run business programs
Java History
 Computer language innovation and development occurs for two
fundamental reasons:

1) To adapt to the changing environments and uses


2) To implement the refinements and improvements in the art of
programming

 The development of Java was driven by both in equal measures

 Many Java features are inherited from the earlier languages:

C → C++ → Java
Before Java: C
 Designed by Dennis Ritchie in 1972.

 Before C:

 BASIC, COBOL, FORTRAN, PASCAL

 C is structured, efficient, high-level language that could


replace assembly code when creating systems programs.

Before Java: C++


Designed by Bjarne Stroustrup in 1979.

OOP – a methodology that helps to organize complex programs


through the use of polymorphism and inheritance, encapsulation.

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


– Set top boxes
– Washing machines
– VCR’s
- Ovens, etc.

 Aim was to make these appliances more “intelligent”.


Java: History

 C++ is powerful, but also dangerous

 The power and popularity of C derived from the extensive use of pointers

 Incorrect use of pointers can cause memory leaks, leading the program to
crash

 Replacing pointers by references, and automating memory management was


the proposed solution
Java: History
 Hence, the team built a new programming language called Oak, which
avoided potentially dangerous constructs in C++, such as pointers,
pointer arithmetic, operator overloading etc.

 Introduced automatic memory management, freeing the


programmer to concentrate on other things.

 Architecture neutrality (Platform independence)

 Many different CPU’s are used as controllers in consumer electronic


devices (They may change as per the new trends in technology).

 So, the software and programming language had to be architecture


neutral.
Java: History
 It was soon realized that these design goals of consumer electronics
perfectly suited an ideal programming language for the Internet and
WWW, which should be:
❖ Object-oriented (& support GUI)
❖ Robust
❖ Architecture neutral

 Internet programming presented a BIG business opportunity. Much


bigger than programming for consumer electronics.

 Java was “re-targeted” for the Internet

 The team was expanded to include Bill Joy (developer of Unix), Arthur
van Hoff, Jonathan Payne, Frank Yellin, Tim Lindholm etc.

 In 1994, an early web browser called WebRunner was written in Oak.


WebRunner was later renamed HotJava.

 In 1995, Oak was renamed Java.


A common story is that the name Java relates to the place from where
the development team got its coffee. The name Java survived the
trade mark search.
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
The Java Buzzwords
 Simple – Java is designed to be easy for the professional
programmer to learn and use.

 Object-oriented: A clean, usable, pragmatic approach to objects

 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 and Portable: Java Virtual Machine provides a


platform independent environment for the execution of Java byte code
and can be ported to any machine.
The Java Buzzwords
Interpreted and High-performance: Java programs are compiled
into an intermediate representation – byte code:
a) Later interpreted by any JVM
b) Translated into the native machine code (JIT)

Distributed: Java handles TCP/IP protocols, accessing a resource


through its URL much like accessing a local file

Dynamic: Substantial amounts of run-time type information to verify


and resolve access to objects at run-time.

Secure: Programs are confined to the Java execution environment


and cannot access other parts of the computer.
The Java Platform
• A platform is the hardware and software environment in which a
program runs.
• The Java platform differs from most other platforms. It's a
software-only platform that runs on top of other, hardware-
based platforms.

• The Java platform has two components:


• The Java Virtual Machine (Java VM)
• The Java Application Programming Interface (Java API)
– The Java API is a large collection of ready-made software components
that provide many useful capabilities, such as graphical user interface
(GUI) widgets.
– The Java API is grouped into libraries (packages) of related
components which allow you to do various things.
Versions of Java
• Java Language vs. Java Platform
– Current version of the language is 18 (JDK 18 / Java SE 18)
– Three versions of the Java Platform, targeted at different uses

• Java Standard Edition (Java SE)


– To develop secure, portable, high-performance applications for
the widest range of computing platforms possible
• Java Enterprise Edition (Java EE)
– For business applications, web services, mission-critical systems
– Transaction processing, databases, distribution, replication
• Java Micro Edition (Java ME)
– Very small Java environment for smart cards, mobile phones, and
set-top boxes
– Subset of the standard Java libraries aimed at limited size and
processing power
The Java SE Platform
To develop and deploy Java applications on desktops and servers and embedded
environments..
Introduction – Java Virtual Machine

Java .class
.java file Compiler file

Java Virtual Machine (JVM)

Mac Microsoft UNIX


Java Virtual Machine - JVM
1. Every Java interpreter, whether it's a Java development tool or a Web
browser that can run Java applets, is an implementation of the Java VM
2. The Java VM can also be implemented in hardware
3. Java byte codes help make "write once, run anywhere" possible
4. We can compile Java program into byte codes on any platform that has a
Java compiler
5. The byte codes can then be run on any implementation of the Java VM
Object Oriented Languages - A Comparison

Feature C++ Ada Java


Encapsulation Yes Yes Yes
Inheritance Yes No Yes
Multiple Inheritance Yes No No
Polymorphism Yes Yes Yes
Binding (Early/Late) Both Early Late
Concurrency Poor Difficult Yes
Garbage Collection No No Yes
Class Libraries Yes Limited Yes

C++: OOL ADA: OBL JAVA: Almost Pure OOL


Java better than C++ ?
• No Typedef, #Defines or Preprocessor

• No Global Variables

• No goto statements

• No Pointers and Pointer arithmetic

• No Multiple Inheritance

• No Operator Overloading

• No copy constructors, destructors

• No Templates
Added or Improved over C++

• Interfaces

• Automatic Garbage collection

• Exceptions (More powerful than C++)

• Strings

• Packages

• Multi-threading

• instanceof
Types of Java Applications
• Different ways to write/run a Java codes are:

Application- A stand-alone program that can be invoked from


command line . A program that has a “main()” method

Applet- A program embedded in a web page , to be run when


the page is browsed .
A program that contains no “main” method

• Application - Java interpreter


• Applets - Java enabled web browser (Linked to HTML via
<APPLET> tag in .html file)
Java Program Structure

• The Java programming language:


– A program is made up of one or more classes
– A class contains data
– and One or more methods

• A Java application always contains a method called main()


Java Program Structure

// comments about the class

public class MyProgram


{
class header

class body

Comments can be added almost anywhere


}
Java Program Structure

// comments about the class

public class MyProgram


{
// Data members
// comments about the method
public static void main (String[] args)
{
method header
method body
}

}
Comments

• Comments in a program are also called inline documentation


• They should be included to explain the purpose of the program and describe
processing steps
• They do not affect how a program works
• Java comments can take two forms:

// this comment runs to the end of the line

/* this comment runs to the terminating


symbol, even across line breaks */

/** This kind of comment is a special‘javadoc’ style comment */


Java Program - Example
Java Program - Example
A Simple Java Application

– Define a class HelloWorld and store it into a file: [Link]

public class HelloWorld {


public static void main (String[] args) {
[Link](“Hello World”);
}
}

Compile the program: javac [Link]


Execute the program: java HelloWorld
Output: Hello World

Try Yourself : [Link]


A Simple Java Application
public class HelloWorld1{
public void display()
{
[Link](“Hello World”);
}
public static void main(String[] args)
{
HelloWorld1 hw = new HelloWorld1();
[Link]();
}
}

Compile the program: javac [Link]


Execute the program: java HelloWorld
Output: Hello World

Try Yourself: [Link]


Executing Applications

• On command line
java classname

Bytecode

Java Java Java


Interpreter Interpreter Interpreter
...
on Windows on Linux on Sun Solaris
Java Program - Example
Program is
Phase 1 Editor Disk created in
the editor and
stored
Compiler Disk on disk.
Phase 2
Compiler creates
Primary byte codes and stores
Memory them on disk.
Class Loader
Phase 3

Class loader puts


Disk bytecodes in memory.
..
..
..
Primary
Memory
Phase 4 Bytecode Verifier Bytecode verifier
confirms that all
bytecodes are valid
and do not violate
Java’s security
.. restrictions.
..
.. Interpreter reads
Primary
bytecodes and
Interpreter Memory
Phase 5 translates them into a
language that the
computer can
understand, possibly
storing data values as
.. the program executes.
.. JIT is used to improve
Lifecycle of Java Code .. the performance.
Compile: javac [Link]
Run: java A cdachyd
Next ………

➢Basic programming constructs of Java

➢Classes and Objects in Java

➢new operator

➢Constructors

➢ Overloading
Session 2:

Learning Objectives
By the end of this session, you must be able to

➢Explain basic programming constructs of Java

➢Arrays in Java

➢Explain Classes and Objects in Java

➢Use instance data and methods

➢Use new operator to create instances

➢Explain Constructors - Overloading

➢Explain Method overloading

➢Write programs on Parameter passing – object as


parameter
Java Programming - Basic Constructs
Char Set
16 – bit Unicode char set

Identifiers:

• Identifiers are the named words a programmer uses in a


program

• An identifier can be made up of letters, digits, the underscore


character (_), and the dollar sign ($)

• They cannot begin with a digit

• Java is case sensitive, therefore Total and total are


different identifiers
Reserved Words
• Often we use special identifiers called reserved words that
already have a predefined meaning in the language
• A reserved word cannot be used in any other way

abstract default if package this


assert do implements private throw
boolean double import protected throws
break else instanceof public transient
byte enum int return true
case extends interface short try
const false long static void
catch final native strictfp volatile
char finally new super while
class float null switch
continue for synchronized
Variables
 Programming languages 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.


Basic Variable Declaration
 Syntax:
datatype identifier [=value];
 Datatype must be
 A simple data type
 User defined datatype (Class type)
 Value is an optional initial value.

 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;
char ch = 'x';
Constants
• A constant is an identifier that is similar to a variable
except that it holds one value for its entire existence

• The compiler will issue an error if you try to change a


constant

• In Java, we use the final modifier to declare a


constant

Example: final int MIN_HEIGHT = 69;


Data Types - Primitive

 Java defines eight simple (primitive) 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 (16-bit Unicode)
8. boolean – logical values true and false
Introduction - Data Types

Data type Bytes Min Value Max Value Literal Values

byte 1 -27 27 – 1 123

short 2 -215 215 – 1 1234

int 4 -231 231 – 1 12345, 086, 0x675

long 8 -263 263 – 1 123456

float 4 - - 1.0

double 8 - - 123.86

char 2 0 216 – 1 ‘a’, ‘\n’

boolean - - - true, false


General rule:
Min value = 2(bits – 1)
Max value = 2(bits-1) – 1 48
(where 1 byte = 8 bits)
Data Types
 boolean result = true;
 char capitalC = 'C';
 byte b = 100;
 short s = 10000;
 int i = 100000;

 // The number 26, in decimal


 int decVal = 26;
 // The number 26, in hexadecimal
 int hexVal = 0x1a;
 // The number 26, in binary
 int binVal = 0b11010;

long creditCardNumber = 1234_5678_9012_3456L;


long socialSecurityNumber = 999_99_9999L;
float pi = 3.14_15F;
long bytes = 0b11010010_01101001_10010100_10010010;
Operators

 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
6) Unary Operators
7) Ternary operator
8) Special operators
Operators – Assignment Operators/Arithmetic Operators

• Assignment Operator
Operator Description Example

= Assignment int i = 10;


int j = i;

• Arithmetic Operators

Operator Description Example


+ Addition int i = 8 + 9; byte b = (byte) 5+4;
- Subtraction int i = 9 – 4;
* Multiplication int i = 8 * 6;
/ Division int i = 10 / 2;

% Remainder int i = 10 % 3;

Example:[Link]
51
Operators – Unary Operators/Equality Operators

• Unary Operators
Operator Description Example
+ Unary plus int i = +1;
- Unary minus int i = -1;
++ Increment int j = i++;
-- Decrement int j = i--;
! Logical Not boolean j = !true;

Example: [Link] Example: [Link]

• Equality Operators

Operator Description Example


== Equality If (i==1)
!= Non equality If (i != 4) 52
Operators – Relational Operators/Conditional Operators

• Relational Operators
Operator Description Example
> Greater than if ( x > 4)
< Less than if ( x < 4)
>= Greater than or equal to if ( x >= 4)
<= Less than or equal to if ( x <= 4)

• Conditional Operators

Operator Description Example


&& Conditional and If (a == 4 && b == 5)
|| Conditional or If (a == 4 || b == 5)

Example: [Link]

Example: [Link]
53
Operators – instanceof Operator/Bitwise Operators/shift operators

• instanceof Operator
Operator Description Example
instanceof Instance of If (john instanceof person)

• Bitwise Operators
Operator Description Example
& Bitwise and 001 & 111 = 1
| Bitwise or 001 | 110 = 111
^ Bitwise ex-or 001 ^ 110 = 111
~ Reverse ~0 = 1

Example: [Link]

• Shift Operators
Operator Description Example
>> Right shift 4 >> 1 = 0100 >> 1 = 0010 = 2
<< Left Shift 4 << 1 = 0100 << 1 = 1000 = 8
54
>>> Unsigned Right shift 4 >>> 1 =0100 >>> 1 =0010 = 2
Operators – Points Know
• Increment & Decrement Operators:
– can’t apply increment & decrement operators for constants ex: int x=++4;
– can’t apply increment & decrement operators for final variable ex: final int x=4; x++;
– Can apply increment & decrement operators for any primitive type except boolean

• Arithmetic Operators:
– There is no way to represent infinity in case of integral arithmetic (int, byte, short, long). Hence if infinity
is result , we always get ArithmeticException: / by zero ex: [Link](10/0);
– In case of floating point arithmetic, there is always a way to represent infinity. Float and Double classes
contain the following constants:
– Positive_Infinity and Negative_Infinity Ex: [Link](10/0.0); [Link](-10/0.0);
– In integral arithmetic, there is no way to represent undefined results. Ex: 0/0=undefined , So leads to
ArithmeticException
– In floating arithmetic, undefined results are NaN (Not a Number) Ex: [Link](0/0.0); // NaN
– The only operators which cause ArithmeticException are / and %

• Relational Operators (<, >, <=, >=) :


– Can apply relational operators for every primitive data type except boolean
– Can’t be applied to reference types
Operators
• Equality Operators ( ==, != ) :
– can apply equality operators for every primitive type including boolean types
– Can apply even for object references also

• instanceof Operator:
– By using instanceof operator, whether the given object is of particular type or not.
– Example: Thread t=new Thread();
[Link](t instanceof Thread); // true
[Link](t instanceof Object); // true
[Link](t instanceof Runnable); // true

• Bitwise Operators:
– & (AND) , | (OR) , ^ (XOR) , ~ (Negation), ! (NOT)
– ~ (tilde) can’t be applied to boolean types
– ! (NOT) can’t be applied to integral types

• new Operator :
– Used create objects
– No delete operator as objects destroyed automatically – Garbage Collection
Operator Precedence
Selection Statements

 Java selection statements allow us to control the flow of program’s


execution based upon conditions known only during run-time.

 Java provides the following selection statements:


1) if-then
2) if - then - else
3) switch

If – then:

if (isMoving){
// the "then" clause: decrease current speed
currentSpeed--;
}
Flow Control – if-else

Syntax Example

if (<condition-1>) { int a = 10;


// logic for true condition-1 goes here if (a < 10 ) {
} else if (<condition-2>) { [Link](“Less than 10”);
// logic for true condition-2 goes here } else if (a > 10) {
} else { [Link](“Greater than 10”);
// if no condition is met, control comes here } else {
} [Link](“Equal to 10”);
}
Result: Equal to 10s

* if(true)
[Link](“Hello”);
** if(true)
int x=10; //
[Link](“Hello”) ;
*** if(true) {
int x=10;
}
**** if(true);

Example: [Link]
Flow Control – switch

Syntax Example
* byte b=10;
switch(b){
switch (<value>) { int a = 10;
}
case <a>: switch (a) {
** char ch=‘a’;
// stmt-1 case 1:
switch(ch){
break; [Link](“1”);
}
case <b>: break;
//stmt-2 case 10:
*** long l=10l;
break; [Link](“10”);
switch(l){
default: break;
} //
//stmt-3 default:
[Link](“None”); **** boolean b=true;
} } switch(b){
Result: 10 }//

***** String color=“blue”;


switch(color){
}

Example: [Link] Example: [Link]


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) do - while
2) while
3) for
Flow Control – do-while / while

• do-while Example: [Link]


Syntax Example
do { int i = 0;
// stmt-1 do {
} while (<condition>); [Link](“In do”);
i++;
} while ( i < 10);
Result: Prints “In do” 10 times

• while Example: [Link]


Syntax Example
while (<condition>) { int i = 0;
//stmt while ( i < 10 ) {
} [Link](“In while”);
i++;
}
Result: “In while” 10 times
Flow Control – for loop

• for Example: [Link]


Syntax Example

for( initialize; condition; expression) for (int i = 0; i < 10; i++)


{ {
// stmt [Link](“In for”);
} }

Result: Prints “In for” 10 times

class ForEachDemo // for each style


{
public static void main(String[] args) {
int arr[]={10,20,30,40,50};
for (int i: arr)
{
[Link]("Count="+i);
}
}}
Iteration Statements
*while(true)
* while(true){ * int a=10, b=20;
[Link](“Hello”);
[Link](“Hello”); while(a<b){
} [Link](“Hello”);
*while(true);
[Link](“Hi”); //urc }
[Link](“Hi”);
*while(true)
*while(false){
int x=10; //
[Link](“Hello”); //urc * final int a=10, b=20;
} while(a<b){
*while(true){
[Link](“Hi”); [Link](“Hello”);
int x=10;
} }
[Link](“Hi”); // urc

for(int i=0; true; i++) for(int i=0; false; i++) for(int i=0; ; i++)
for(; ;); //true { { {
[Link](“Hello”); [Link](“Hello”); [Link](“Hello”);
} } }
[Link](“HI”); //urc [Link](“HI”); //urc [Link](“HI”);
//urc
Jump Statements

 Java jump statements enable transfer of control to other parts of


program.

 Java provides three jump statements:


1) break
2) continue
3) return

 In addition, Java supports exception handling that can also alter


the control flow of a program.
break Statement

• The break statement has two forms:


•labeled and unlabeled

• We saw the unlabeled form in the previous discussion of


the switch statement.

• We can also use an unlabeled break to terminate a for,


while, or do-while loop

Example:[Link]
continue Statement

• The continue statement skips the current iteration of a for, while , or do-
while loop.

• The unlabeled form skips to the end of the innermost loop's body and
evaluates the Boolean expression that controls the loop

Example:[Link]

return Statement
• The return statement exits from the current method, and control flow returns
to where the method was invoked.

• The return statement has two forms:


• one that returns a value
• one that doesn't return.
• To return a value, simply put the value after the return keyword.
return ++count;

• When a method is declared void, use the form of return that doesn't return a
value.
return;
Coding Guidelines
Arrays in JAVA
Declaring an Array Variable

• Syntax and Examples


– <type> [] variable_name;
– int [] prime;
– int prime[];

• Both syntaxes are equivalent


• No memory allocation at this point
Defining an Array

• Define an array as follows:

variable_name=new <type>[N];
primes=new int[10];

• Declaring and defining in the same statement:


int[] primes=new int[10];

• In JAVA, int is of 4 bytes, total space=4*10=40 bytes


Graphical Representation
Index

0 1 2 3 4 5 6 7 8 9
2 1 11 -9 2 1 11 90 101 2

value
What happens if …

• We define
int[] prime=new long[20];
[Link]: incompatible types
found: long[]
required: int[]
int[] primes = new long[20];
^
• The right hand side defines an array, and thus
the array variable should refer to the same type
of array
What happens if …

• We define
int prime[100];
[Link]: ']' expected

• The C++ style is not permitted in JAVA


syntax
Default Initialization

• When array is created, array elements are


initialized
– Numeric values (int, double, etc.) to 0
– Boolean values to false
– Char values to ‘\u0000’
– Class types to null
Accessing Array Elements

• Index of an array is defined as


– Positive int, byte or short values
– Expression that results into these types
• Any other types used for index will give error
– long, double, etc.
– Incase expression results in long, then type cast to int
• Indexing starts from 0 and ends at N-1
primes[2]=0;
int k = primes[2];

Validating Indexes

• JAVA checks whether the index values are


valid at runtime
– If index is negative or greater than the size
of the array then an
IndexOutOfBoundException will be thrown
– Program will normally be terminated unless
handled in the try {} catch {}
What happens if …

long[] primes = new long[20];


primes[25]=33;
….
Runtime Error:
Exception in thread “main”
[Link]: 25
at [Link]([Link])
Initializing Arrays

• Initialize and specify size of array while declaring


an array variable
int[] primes={2,3,5,7,11,13,17}; //7 elements
• You can initialize array with an existing array
int[] even={2,4,6,8,10};
int[] value=even;
– One array but two array variables!
– Both array variables refer to the same array
– Array can be accessed through either variable name
Graphical Representation

even
0 1 2 3 4
2 4 6 8 10

value

[Link]
Array Length
• Refer to array length using length
– A data member of array object
– array_variable_name.length
– for(int k=0; k<[Link];k++)
….
• Sample Code:
long[] primes = new long[20];
[Link]([Link]);
• Output: 20

• If number of elements in the array are changed, JAVA


will automatically change the length attribute!
Sample Program
class MinAlgorithm
{
public static void main ( String[] args )
{
int[] array = { -20, 19, 1, 5, -1, 27, 19, 5 } ;
int min=array[0]; // initialize the current minimum

for ( int index=0; index < [Link]; index++ )

if ( array[ index ] < min )


min = array[ index ] ;

[Link]("The minimum of this array is: " + min );


}
}
Arrays of Arrays

• Two-Dimensional arrays

float[][] temperature=new float[10][365];

– 10 arrays each having 365 elements


– First index: specifies array (row)
– Second Index: specifies element in that array
(column)
– In JAVA float is 4 bytes, total Size=4*10*365=14,600
bytes
Initializing Array of Arrays

int[][] array2D = {
{99, 42,74, 83,100},
{90, 91, 72, 88, 95},
{88, 61, 74, 89, 96},
{61, 89, 82, 98, 93},
{93, 73, 75, 78, 99},
{50, 65, 92, 87, 94},
{43, 98, 78, 56, 99} };

//7 arrays with 5 elements each


Arrays of Arrays of Varying Length

• All arrays do not have to be of the same


length
float[][] samples;
samples=new float[6][];//defines # of arrays
samples[2]=new float[6];
samples[5]=new float[101];
• Not required to define all arrays
Initializing Varying Size Arrays
int[][] uneven = {{ 1, 9, 4 }, { 0, 2}, { 0, 1, 2, 3, 4 } };

//Three arrays

//First array has 3 elements


//Second array has 2 elements
//Third array has 5 elements
Array of Arrays Length
long[][] primes = new long[20][];
primes[2] = new long[30];
[Link]([Link]); //Number of arrays
[Link](primes[2].length);//Number of elements
in the second array

OUTPUT:
20
30
Sample Program
class unevenExample3
{
public static void main( String[] arg )
{ // declare and construct a 2D array
int[][] uneven = { { 1, 9, 4 }, { 0, 2}, { 0, 1, 2, 3, 4 }
};
// print out the array
for ( int row=0; row < [Link]; row++ ) //changes
row
{
[Link]("Row " + row + ": ");
for ( int col=0; col < uneven[row].length; col++ )
//changes column
[Link]( uneven[row][col] + " ");
[Link]();
}
}
}
Row 0: 1 9 4
Row 1: 0 2
Row 2: 0 1 2 3 4
Multidimensional Arrays

• A farmer has 10 farms of beans each in 5 countries,


and each farm has 30 fields!
• Three-dimensional array
long[][][] beans=new long[5][10][30];
//beans[country][farm][fields]
Varying length in Multidimensional Arrays

• Same features apply to multi-dimensional arrays as


those of 2 dimensional arrays
long beans=new long[3][][];//3 countries
beans[0]=new long[4][];//First country has 4 farms
beans[0][3]=new long[10];
// Fourth farm in first country has 10 fields
Coding Guidelines
What’s a Program?
● Model of Complex system

o model: simplified representation of salient features of


something, either tangible or abstract

o system: collection of collaborating components

● Programming Paradigm or Approach

o A programming paradigm is a style or “way” of programming

o Example: OOP, POP, Declarative, functional, etc.,


What’s a Program?

● Sequences of instructions expressed in specific


programming language
o syntax: grammatical rules for forming instructions
o semantics: meaning/interpretation of instruction

● Programming languages
o Examples: C, C++, Java,etc.,
Polymorphism
What is an Object?

 Real world entities or things which have:


1) State
2) Behavior
3) Identity

Example: your dog, your car etc.,

 State – name, color, breed of a dog


 Behavior – sitting, barking, waging tail, running
 Identity – your dog

 A software object is a bundle of variables (state) and methods


(operations).
What is a Class?
 Class is basis for the Java language.

 Each concept we wish to describe in Java must be included in a class.

 A class is a template for objects

 A class is a blueprint / prototype 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 defined in the class.

 A class defines a new data type, whose values are objects

 An object is an instance of a class


The Class hierarchy

• In Java , classes are arranged in a hierarchy

• The root, or topmost class is Object

• Every class but Object has at least one super class

• A class may have subclasses

• Each class inherits all the fields and methods of its super
classes
Class Definition
 A class consists of :
• Name,
• Several variable declarations (class/instance variables)
• Several method declarations

• A Class also consists constructors and blocks

 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) { … }
}
Declaring and creating objects

• Declare a reference
Example: Person p;
String s;

• Creating an instance/object
Person p = new Person(); s
String s = new String (“India”);

India
• The new keyword is used to allocate
memory at run-time
Example Program

[Link]
What happens in the memory?
Anonymous object
Object Destruction

 A program accumulates memory through its execution.


 Two mechanisms to free memory that is no longer needed by the
program:

1) Manual – in C/C++
2) Automatic – 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.


Constructor

 A constructor used to initialize the state of an object.


 It is invoked at the time of object creation
 It constructs the values (data) for the object
 Features:
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 is the class

 When the class has no constructor, the default constructor


automatically supplied the compiler.
Default Constructor
Parameterized Constructor
Constructor Overloading
Constructor – Copying values
Constructors vs. Methods
Method Overloading
• A class with multiple methods by the same name but different parameters
• Implements polymorphism in java (static)
• Three ways:
• Number of arguments
• Types of arguments
• Order and Type of argument
Method Overloading
Method overloading is not possible by changing return
types.

Is Overloading the main() method possible ?


Overloading main() method

public class Simple /*Whenever your class is public and contains main()
method, file name must be same as your class name.*/
{
public static void main(String[] args)
{
[Link]("Hello World!");
main(10); // main() call
}
public static void main(int a) // main() method overloading
{
[Link](a);
}
}

[Link]
Method Overloading
Method Overloading
Parameter Passing
Only pass-by value or call by value is available in Java. There is no call by
reference. Primitive data types and objects can be passed as values

[Link]
Parameter Passing

[Link]
Session 3:

Learning Objectives

➢ Explain this facility

➢ Describe static member, method and block

➢ JDK and its usage

➢ Garbage Collection
this keyword
• this is a reference variable that refers to the current object
• Call to this() must be always first

Usage:

1. Used to refer current class instance variable

2. this() is used to invoke current class constructor

3. Used to invoke current class method

4. Can be passed as an argument to the method

5. Used as argument in constructor call

6. Used to return current class instance


[Link]
this() is used to invoke current class constructor
Advantage of this()
[Link]
Proving “this”
The static keyword
• Java methods and variables can be declared static
• These will exist independent of any object
This means that a Class’s

– static methods can be called even if no objects of that class have been created and
– static data is “shared” by all instances (i.e., one value per class instead of one per instance

• Static
– means “global”--all objects refer to the same storage.
– applies to variables or methods
• usage:
– with variable of a class
– with a method of a class
Usage of Static Method
Static Block
public class SSS {
static{
[Link]("Parent is:");
[Link](0);
}
}

javac –deprecated [Link]

[Link]
The Java Platform – JDK / Java SE
Java Development Kit

• javac - The Java Compiler


• java - The Java Interpreter
• appletviewer -Tool to run the applets

• javap - to print the Java byte codes


• javadoc - documentation generator
• javah - creates C header files
JVM
JVM
JVM
JVM
• JVM is a component of the Java system that interprets and executes
the instructions in our class files.

• The following figure shows a block diagram of the JVM that includes its
major subsystems and memory areas.

Figure 1: Memory configuration by the JVM.


JVM

• Each instance of the JVM has one method area, one heap, and
one or more stacks - one for each thread

• When JVM loads a class file, it puts its information in the method
area

• As the program runs, all objects instantiated are stored in the


heap

• The stack area is used to store activation records as a


program runs
JVM
JVM
Types of Class Loaders

Bootstrap Class Loader:


• Bootstrap class loader loads java's core classes like [Link],
[Link] etc.
• These are classes that are part of java runtime environment.
• Bootstrap class loader is native implementation and so they may
differ across different JVMs.

Extensions Class Loader:


• JAVA_HOME/jre/lib/ext contains jar packages that are extensions of
standard core java classes.
• Extensions class loader loads classes from this ext folder

• System Class Loader:


Java classes that are available in the java classpath are loaded
using System class loader.
The Class Loader Subsystem
• The class loader performs three main functions of JVM, namely:
loading, linking and initialization
• The linking process consists of three sub-tasks, namely, verification,
preparation, and resolution

Figure 3: Class loading process.


JVM
Class Loading Process

• Loading means reading the class file for a type, parsing it


to get its information, and storing the information in the
method area.

• For each type it loads, the JVM must store the following
information in the method area:

– The fully qualified name of the type


– The fully qualified name of the type's direct super class or if the type is an interface, a list of
its direct super interfaces .
– Whether the type is a class or an interface
– The type's modifiers ( public, abstract, final, etc)
– Constant pool for the type: constants and symbolic references.
– Field info : name, type and modifiers of variables
– Method info: name, return type, number & types of parameters, modifiers, byte codes, size of
stack frame and exception table.
Class Loading Process (Cont’d)
• The end of the loading process is the creation of an instance of
[Link] for the loaded type.
• The purpose is to give access to some of the information captured in
the method area for the type, to the programmer.
• Some of the methods of the class [Link] are:

public String getName()


public Class getSupClass()
public boolean isInterface()
public Class[] getInterfaces()
public Method[] getMethods()
public Field[] getFields()
public Constructor[] getConstructors()

• Note that for any loaded type T, only one instance of [Link]
is created even if T is used several times in an application.
• To use the above methods, we need to first call the getClass()
method on any instance of T to get the reference to the Class
instance for T.
[Link]
Verification During Linking Process
• The next process handled by the class loader is Linking.
• This involves three sub-processes:
Verification, Preparation and Resolution

• Verification is the process of ensuring structurally correct


the binary representation of a class. The JVM has to make
sure that a file it is asked to load was generated by a valid
compiler and it is well formed
• Example of some of the things that are checked at
verification are:
– Every method is provided with a structurally correct signature
– Every instruction obeys the type discipline of the Java language
– Every branch instruction branches to the start not middle of another instruction
Preparation
• In this phase, the JVM allocates memory for the class (i.e
static) variables and sets them to default initial values.
• Note that class variables are not initialized to their proper initial
values until the initialization phase - no java code is executed
until initialization.
• The default values for the various types are shown below:
Resolution
• Resolution is the process of replacing symbolic names for types, fields
and methods used by a loaded type with their actual references.
• Symbolic references are resolved into a direct references by searching
through the method area to locate the referenced entity.
• For the class below, at the loading phase, the class loader would have
loaded the classes: TestClassClass, String, System and Object.

public class TestClassClass{


public static void main(String[] args){
String name = new String(“ABC”);
Class nameClassInfo = [Link]();
[Link]("Parent is: “ + [Link]());
}
}

• The names of these classes would have been stored in the constant pool for
TestClassClass.
• In this phase, the names are replaced with their actual references.
Class Initialization
• This is the process of setting class variables to their proper initial
values - initial values desired by the programmer.
class Example1 {
static double rate = 3.5;
static int size = 3*(int)([Link]()*5);
...
}
• Initialization of a class consists of two steps:
– Initializing its direct super class (if any and if not already initialized)
– Executing its own initialization statements
• The above imply that, the first class that gets initialized is Object.
• Note that static final variables are not treated as class variables but
as constants and are assigned their values at compilation.

class Example2 {
static final int angle = 35;
static final int length = angle * 2;
...
}
JVM
JVM
JVM
JVM
Garbage Collection
How Objects are Created in Java

• An object is created in Java by invoking the new()


operator.
• Calling the new() operator, the JVM will do the
following:

• allocate memory;
• assign fields their default values;
• run the constructor;
• a reference is returned.
How Java Reclaims Objects Memory

• Java does not provide the programmer any means to


destroy objects explicitly

• The advantages are

– No dangling reference problem in Java

– Easier programming

– No memory leak problem


What is Garbage?

Garbage: unreferenced objects Ram Object

Student ram= new Student(); ram


Student shyam= new Student();
ram=shyam;
shyam

Now Ram Object becomes a garbage,


It is unreferenced Object
Shyam Object
What is Garbage Collection?
• What is Garbage Collection?
– Finding garbage and reclaiming memory allocated to it.

• Why Garbage Collection?


– the heap space occupied by an un-referenced object can be
recycled and made available for subsequent new objects

• When is the Garbage Collection process invoked?


– When the total memory allocated to a Java program exceeds
some threshold.

• Is a running program affected by garbage collection?


– Yes, the program suspended during garbage collection.
Advantages of Garbage Collection

• GC eliminates the need for the programmer to deallocate


memory blocks explicitly

• Garbage collection helps ensure program integrity.

• Garbage collection can also dramatically simplify programs.


Disadvantages of Garbage Collection

• Garbage collection adds an overhead that can affect program


performance.

• GC requires extra memory.

• Programmers have less control over the scheduling of CPU


time.
[Link]
Garbage Collector

public class GCDemo {

public void finalize(){


[Link]("garabage collector invoked!!");
}

public static void main(String[] args) {


GCDemo[] gc=new GCDemo[10];
for(int i=0;i<10;i++){
gc[i]=new GCDemo();
}
gc=null;
[Link]();
}
}
Common Garbage Collection Schemes
• Three main approaches of garbage collection:

– Reference counting

– Mark-and-sweep

– Stop-and-copy garbage collection.


Reference Counting Garbage Collection

• Main Idea: Add a reference count field for every


object.

• This field is updated when the number of references


to an object changes.
p
57
Example
refCount = 2
Object p= new Integer(57); q
Object q = p;
Reference Counting (cont'd)
• The update of reference field when we have a reference assignment ( i.e
p=q) can be implemented as follows

Example:
Object p = new Integer(57);
Object q= new Integer(99);
p=q

p
57

refCount = 0
q

99

refCount = 2
Reference Counting (cont'd)
• Reference counting will fail whenever the data
structure contains a cycle of references and the cycle
is not reachable from a global or local reference

head ListElements ListElements ListElements

next next next

refCount = 1 refCount = 1 refCount = 1


Reference Counting (cont'd)
• Advantages
– Conceptually simple: Garbage is easily identified
– It is easy to implement.
– Immediate reclamation of storage
– Objects are not moved in memory during garbage
collection.

• Disadvantages
– Reference counting does not detect garbage with cyclic
references.
– The overhead of incrementing and decrementing the
reference count each time.
– Extra space: A count field is needed in each object.
– It may increase heap fragmentation.
Mark-and-Sweep Garbage Collection

• The mark-and-sweep algorithm is divided into two phases:


– Mark phase: the garbage collector traverses the graph of
references from the root nodes and marks each heap object it
encounters. Each object has an extra bit: the mark bit – initially
the mark bit is 0. It is set to 1 for the reachable objects in the
mark phase.

– Sweep phase: the GC scans the heap looking for objects with
mark bit 0 – these objects have not been visited in the mark
phase – they are garbage. Any such object is added to the free
list of objects that can be reallocated. The objects with a mark bit
1 have their mark bit reset to 0.
Mark and Sweep (cont'd)

• Advantages
– It is able to reclaim garbage that contains cyclic references.
– There is no overhead in storing and manipulating reference
count fields.
– Objects are not moved during GC – no need to update the
references to objects.
• Disadvantages
– It may increase heap fragmentation.
– It does work proportional to the size of the entire heap.
– The program must be halted while garbage collection is
being performed.
Stop-and-Copy Garbage Collection
• The heap is divided into two regions: Active and Inactive.

• Objects are allocated from the active region only.

• When all the space in the active region has been exhausted,
program execution is stopped and the heap is traversed. Live
objects are copied to the other region as they are encountered
by the traversal. The role of the two regions is reversed, i.e.,
swap (active, inactive). …
Stop-and-Copy Garbage Collection (cont'd)
• A graphical depiction of a garbage-collected heap that uses a
stop and copy algorithm. This figure shows nine snapshots of
the heap over time:
Stop-and-Copy Garbage Collection (cont'd)

• Advantages
– Only one pass through the data is required.
– It de-fragments the heap.
– It does work proportional to the amount of live objects and
not to the memory size.
– It is able to reclaim garbage that contains cyclic references.
– There is no overhead in storing and manipulating reference
count fields.
Stop-and-Copy Garbage Collection (cont'd)

• Disadvantages
– Twice as much memory is needed for a given amount of
heap space.
– Objects are moved in memory during garbage collection
(i.e., references need to be updated)
– The program must be halted while garbage collection is
being performed.
getBytes

Class “Object” : getClass() getBytes


getBytes
Output: getBytes
FQN of getChars
class:[Link] getChars
import [Link]; equals indexOfSupplementary
import [Link]; toString intern
hashCode isEmpty
join
compareTo join
public class ObjectTest { compareTo lastIndexOf
public static void main(String[] args) { indexOf lastIndexOf
indexOf lastIndexOf
int count=0; indexOf lastIndexOf
Object o=new String("CDAC Hyderabad"); indexOf lastIndexOf
lastIndexOf
Class c=[Link](); indexOf lastIndexOfSupplementary
indexOf length
[Link]("FQN of class:"+[Link]()); valueOf matches
Method[] m=[Link](); //reflection valueOf nonSyncContentEquals
valueOf offsetByCodePoints
Field[] f=[Link](); // reflection regionMatches
valueOf
for(Method m1:m){ regionMatches
valueOf replace
count++; valueOf replace
valueOf replaceAll
[Link]([Link]()); valueOf replaceFirst
} valueOf split
charAt split
[Link]("No of methods:"+count); startsWith
checkBounds startsWith
[Link]("................"); codePointAt subSequence
for(Field f1:f){ codePointBefore substring
codePointCount substring
count++; toCharArray
compareToIgnoreCase
[Link]([Link]()); concat toLowerCase
toLowerCase
} contains toUpperCase
contentEquals toUpperCase
} contentEquals trim
} copyValueOf No of methods:77
copyValueOf ................
endsWith value
hash
equalsIgnoreCase serialVersionUID
format serialPersistentFields
format CASE_INSENSITIVE_ORDER
Coming session

Inheritance
Session 4:

Learning Objectives

By the end of this session, you must be able to

➢ Describe Inheritance

➢ Use Super Keyword

➢ Explain Nested Classes


Inheritance
Inheritance

• INHERITANCE is One of the pillars of object-orientation

• A new class is derived from an existing class:


1) Existing class is called super-class
2) Derived class is called sub-class

• A sub-class is a specialized version of its super-class:


1) has all non-private members of its super-class
2) may provide its own implementation of super-class
methods

• Objects of a sub-class are a special kind of objects of a


super-class
Class Hierarchy

• A child class of one parent can be the


parent of another child, forming class
hierarchies
Animal
• At the top of the hierarchy there’s a default
class called Object
Reptile Bird Mammal

Snake Lizard Parrot Horse Bat


extends Key Word

• It is a keyword used to inherit a class from


another class
class One class Two extends One
• Allows to extend from only one class
{ {
int a=5; int b=10;
} }

One baseobj=new One(); // base class object.


Two subobj=new Two(); // child class object

super class object baseobj can be used to refer its sub class objects.

For example,
Baseobj=subobj // now its pointing to sub class
Example : Inheritance

[Link]
Overriding
Allows a sub class or child class to provide a specific
implementation of a method that is already provided by one of
its super classes or parent classes.

[Link]
The Benefits of Inheritance

• Software Reusability (among projects)

• Increased Reliability (resulting from reuse and sharing of well-tested


code)

• Code Sharing (within a project)

• Consistency of Interface (among related objects)

• Software Components

• Rapid Prototyping (quickly assemble from pre-existing components)

• Polymorphism and Frameworks (high-level reusable components)

• Information Hiding
The Costs of Inheritance

• Execution Speed

• Program Size

• Message-Passing Overhead

• Program Complexity (in overuse of


inheritance)
1 . Referring immediate parent class instance variable

[Link]
1. Final variable can not be changed

2. Final method can not be overridden

3. Final class can not be inherited


Class “Object”

• In Java, all classes use inheritance.

• If no parent class is specified explicitly, the base class Object is


implicitly inherited.

• All classes defined in Java, are children of Object class, which


provides minimal functionality guaranteed common to all objects.
Class Object
Methods defined in Object class are;
[Link](Object obj) Determine whether the argument object is the same as the
receiver
[Link]() Returns the class of the receiver, an object of type Class
[Link]() Returns a hash value for this object. Should be overridden when the
equals method is changed
[Link]() Converts object into a string value. This method is also often overridden
[Link]() Called by the garbage collector on an object when garbage collector
determines that there are no more references to the object
[Link]() Creates and returns a copy of this object.
[Link]()
[Link](long timeout)
[Link](long timeout, int nanos)
10. notify()
11. notifyAll()
Class “Object” : getClass()
getBytes
getBytes
getBytes
Output: getBytes
FQN of getChars
class:[Link] getChars
import [Link]; equals indexOfSupplementary
import [Link]; toString intern
hashCode isEmpty
join
compareTo join
public class ObjectTest { compareTo lastIndexOf
public static void main(String[] args) { indexOf lastIndexOf
indexOf lastIndexOf
int count=0; indexOf lastIndexOf
Object o=new String("CDAC Hyderabad"); indexOf lastIndexOf
lastIndexOf
Class c=[Link](); indexOf lastIndexOfSupplementary
indexOf length
[Link]("FQN of class:"+[Link]()); valueOf matches
Method[] m=[Link](); //reflection valueOf nonSyncContentEquals
valueOf offsetByCodePoints
Field[] f=[Link](); // reflection regionMatches
valueOf
for(Method m1:m){ regionMatches
valueOf replace
count++; valueOf replace
valueOf replaceAll
[Link]([Link]()); valueOf replaceFirst
} valueOf split
charAt split
[Link]("No of methods:"+count); startsWith
checkBounds startsWith
[Link]("................"); codePointAt subSequence
for(Field f1:f){ codePointBefore substring
codePointCount substring
count++; toCharArray
compareToIgnoreCase
[Link]([Link]()); concat toLowerCase
toLowerCase
} contains toUpperCase
contentEquals toUpperCase
} contentEquals trim
} copyValueOf No of methods:77
copyValueOf ................
endsWith value
hash
equalsIgnoreCase serialVersionUID
format serialPersistentFields
format CASE_INSENSITIVE_ORDER
Nested Classes
Nested Classes

• The Java programming language allows you to define a class within


another class.
Such a class is called a nested class
• Nested classes introduced in jdk1.1

class OuterClass {
...
class NestedClass {
...
}
}
Nested Classes - Terminology
• Nested classes are divided into two categories:
– static
Nested classes that are declared static are simply
called static nested classes
– non-static
Non-static nested classes are called inner classes

class OuterClass {
...
static class StaticNestedClass {
...
}
class InnerClass {
...
}
}
What is Nested Class?

• A nested class is a member of its enclosing class

• Non-static nested classes (inner classes) have access to other


members of the enclosing class, even if they are declared private

• Static nested classes do not have access to other members of the


enclosing class except static members

• As a member of the OuterClass, a nested class can be


declared private, public, protected, or static
Why Use Nested Classes?

• There are several compelling reasons for using nested


classes, among them are :

• It is a way of logically grouping classes that are only used in one


place

• It increases encapsulation

• Nested classes can lead to more readable and maintainable code


(less code)
Types of nested classes
 Static nested classes
 Non-local named only
 Inner classes
 Local
 Anonymous or named
 Non-local
 Named only
Inner Classes

• As with instance methods and variables, an inner


class is associated with an instance of its enclosing
class and has direct access to that object's methods and
fields

• Also, because an inner class is associated with an


instance, it cannot define any static members itself

• Objects that are instances of an inner class


exist within an instance of the outer class.
Inner Classes …

class OuterClass {
...
class InnerClass {
...
}
}

• An instance of InnerClass can


exist only within an instance
of OuterClass and has direct
access to the methods and An Instance of InnerClass Exists Within an
fields of its enclosing instance Instance of OuterClass
Inner class

• To instantiate an inner class, you must first instantiate


the outer class.
• Then, create the inner object within the outer object
with this syntax:

[Link] innerObject = [Link]


InnerClass();
The .class File for an Inner Class

• Compiling any class in Java produces a .class file


named [Link]

• Compiling a class with one (or more) inner classes


causes both (or more) classes to be compiled, and
produces two (or more) .class files

– Such as
– [Link] and
– ClassName$[Link]
[Link]
[Link]
Local Class

• A class that is
created inside a
method

• Local class can not


have static
members.

• Final static fields


are allowed

• Can not have


accessibility
modifiers.

[Link]
Anonymous Class
• Combines the process of definition and instantiation into a single step

• Syntax:
new <Super Class Name>(<optional arg list>)
{
<member declartion>
};

Anonymous Class can be created by:

1. Class (May be abstract class)


2. Interface
Anonymous Inner
Class
@FunctionalInterface @FunctionalInterface
interface B{ interface B{
void show(); void show();
}
}
public class A {
public static void main(String[] args){ public class A {
B b=new B(){ public static void main(String[] args){
public void show(){ B b=()->[Link]("Anonymous
[Link]("Anonymous Implementation"); // lambda expression
Implementation"); [Link]();
} }
};
}
[Link]();
}
}

// Anonymous Implementation

[Link]
[Link]
Static Nested Classes
• As with class methods and variables, a static nested class is
associated with its outer class

• And like static class methods, a static nested class cannot refer
directly to instance variables or methods defined in its enclosing
class
– it can use them only through an object reference

• A static nested class interacts with the instance members of its


outer class (and other classes) just like any other top-level class

class Cover{
static class InnerCover{
void go(){
[Link]("I am the first Static Inner
Class");
}
}
}
[Link]
[Link]
Questions?

Thank You,
Sadhu Sreenivas
Next…

➢Abstract Class

➢Interfaces

➢Packages

➢Access Modifiers

➢Wrapper Classes
Session 5:

Learning Objectives

By the end of this session, you must be able to

➢Explain Abstract Class

➢Describe Interfaces

➢Create and Use Packages

➢Explain Wrapper Classes


[Link]
abstract class - features

• If a class contains at least one abstract method should be declared as abstract

• We can declare a class as abstract, even if the class does not have any abstract
methods

• Abstract class can not be instantiated but can be referred

• If a class is extending from an abstract class, the extending class should provide the
body (implementation) for all the abstract methods of super class

• If the extended class fails to provide body for at least one abstract method, should
be declared abstract
Example
Example
Example
Interfaces
• An interface is a reference type, similar to a class, that can contain only constants,
method signatures, and nested types.

• There are no method bodies.

• Interfaces cannot be instantiated—they can only be implemented by classes


or extended by other interfaces.

• A method declaration within an interface is followed by a semicolon, but no braces.

• All methods declared in an interface are implicitly public.

• An interface can contain constant declarations in addition to method declarations.

• All constant values defined in an interface are implicitly public static final.
Uses of Interfaces
[Link]
[Link]
Interfaces: Java 9 feature
In Java 9 and later versions, an interface can have six kinds of things:

1. constant variables Example:


2. abstract methods interface B{
3. default methods void show();
4. static methods default void print(){ // default methods
5. private methods [Link](“Hello");
6. private static methods }
}

public class A implements B {


public void show(){
[Link](“Hi");
}
public static void main(String[] args){
A a=new A();
[Link]();
[Link]();
}
}
Interfaces: Java 9 feature
In Java 9 and later versions, an interface can have six kinds of things:

interface BB{
1. constant variables void show();
2. abstract methods default void print(){ // default methods
3. default methods disp();
4. static methods [Link]("hello");
5. private methods }
6. private static methods private void disp(){ //private static or static
[Link]("Private");
}
}

public class AA implements BB {


public void show(){
[Link]("hi");
}
public static void main(String[] args){
AA a=new AA();
[Link]();
[Link]();
}
}
Run time Polymorphism
[Link]
Interface vs Abstract Class

Abstract Classes Interfaces


1. Contain one or more abstract 1. Contain only method
methods, can contain no declarations and public static
abstract methods also i.e. only final constants
concrete methods & can have
instance variables. 2. Keyword “interface”

2. Keyword “abstract” 3. Only have public members

3. Contain private ,protected and 4. A class implementing an


public members. interface must implement all of
the methods defined in the
4. A class extending an abstract interface
class need not implement any of
the methods defined in the
abstract class
Packages
A package is a grouping of related types (class,
interface) providing access protection and name
space management.
Java Package
Creating and Using Packages

Defining a package :
package package-name;

Importing a package :
import [Link];
or
import packagename.*;

Naming convention :
double y = [Link](x); //fully qualified name
Packages – explicit and implicit import
import [Link].*; // implicit import
import [Link].*;
public class Test {

public static void main(String[] args) {


Date d=new Date(); // ambiguous ref
[Link](d);
}
}

import [Link]; // explicit import


import [Link].*; // implicit import
public class Test {

public static void main(String[] args) {


Date d=new Date();
[Link](d);
}
}
static import
public class Test {
public static void main(String[] args) {
[Link]([Link](123, 321)); //321
[Link]([Link](784));//28
[Link]([Link]()); //random
[Link]([Link](8, 3));//512
}
}

import static [Link].*; // static import


public class Test {
public static void main(String[] args) {
[Link](max(123, 321));
[Link](sqrt(784));
[Link](random());
[Link](pow(8, 3));
}
}
[Link]
Example 1 : [Link]

package hyd;
public class Sample{
public void msg () {
[Link]("Hello i am from hyd package!");
}
public static void main(String args[])
{
Sample s=new Sample();
[Link]();
}
}

//compile // javac -d . [Link]


// run // java [Link]
Example 2 : [Link]

package cdac;

import hyd.*; // importing package

Public class R {
public void fun(){
[Link](" Hello, i am from cdac package");
}

public static void main(String[] args)


{
Sample s1=new Sample();
[Link]();
R r1=new R();
[Link]();
}
}

// javac -d . [Link]
// java cdac.R
Example 3 :[Link]

package [Link];

public class DAC {


public void method () {
[Link]("Hello, i am from sub package!");
}
public static void main(String args[]){
DAC dac=new DAC();
[Link]();
}
}

//compile // javac -d . [Link]


// run // java [Link]
Example 4 : [Link]

package acts;
import cdac.*;
import [Link];
class SR{
public void function(){
[Link](" Hello i am from acts package!");
}
public static void main(String[] args) {
R r=new R(); // from cdac package
[Link]();
Sample s=new Sample(); // from hyd package
[Link]();
SR sr=new SR(); // from current package-acts
[Link]();
[Link] d=new [Link]();
[Link](); // from sub package
}
}

Note: All classes must be public


Access Modifiers
Modifiers
There are 12 modifiers in Java :

• public
• private Visibility modifiers
• protected
• (default)

• static
• abstract
• final
• strictfp
• native
• synchronized
• transient
• volatile
Modifiers
• The only applicable modifiers for top level classes in Java are:
public, default, final, abstract and strictfp

• For the inner classes, the following are allowed:


public, default, final, abstract, strictfp, private, protected and static

• final – modifier applicable for classes, methods and variables

• abstract - modifier applicable for classes, methods but not variables

• final class can not have abstract methods where as abstract class can contain final
methods

• public class A {
final int x;
} // varaible x is not initialized

• public class A {
final static int x;
} // varaible x is not initialized
Modifiers
strictfp: strict floating point – IEEE 754 standard
strictfp modifier applicable for classes and methods but not variables

*The only applicable modifier for local variables is final

public class A {
public void test(){
final int x;
[Link]("Hello");
}
}
// Hello

public class A {
public void test(){
final int x;
[Link](x);
}
}
// variable x might not have been initialized
Modifiers

• static modifier – applicable for variables and methods but not for classes (but inner
classes can be declared static)

• native modifier – applicable for methods but not for variables and classes

• synchronized modifier – applicable for methods and blocks but not for classes and
variables

• transient modifier - applicable for only variables.

• volatile modifier – applicable for only variables


Modifiers

• The only applicable modifier for local variables is final

• The modifiers which are applicable for only variables but not for classes and
methods : volatile and transient

• The modifiers which are applicable for only methods but not for classes and
variables : synchronized and native

• The modifiers which are applicable for top level classes, methods and
variables : public, default and final

• The modifiers which are applicable for inner classes but not for outer classes
are: private, protected and static

• final, strictfp and synchronized can be used with main()


• Ex: public static final strictfp synchronized void main(String…args)
modifiers table

modifier Outer Inner method variable block interface enum constructor


class class

public yes yes yes yes no yes yes yes

(default) yes yes yes yes no yes yes yes

private no yes yes yes no no no yes

protected no yes yes yes no no no yes

final yes yes yes yes no no no no

abstract yes yes yes no no yes no no

static no yes yes yes yes no no no

synchronized no no yes no yes no no no

native no no yes no no no no no

strictfp yes yes yes no no yes yes no

transient no no no yes no no no no

volatile no no no yes no no no no
Enumeration : enum Keyword
➢ Enumeration is a list of named constants and these Java enumerations define a class
type.
➢ An enum type is a special data type that enables for a variable to be a set of predefined
constants
➢ The variable must be equal to one of the values that have been predefined for it.
➢ Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and
the days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY,
SATURDAY)
➢ Enumeration is used using the keyword enum
➢ Each item in enum is implicitly declared as public static final members
Enumeration : enum Keyword
In the Java programming language, you define an enum type by using the enum keyword.
For example, you would specify a days-of-the-week enum type as:

public enum Day {


SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY
}

➢You should use enum types any time you need to represent a fixed set of constants. That includes
natural enum types such as the planets in our solar system and data sets where you know all possible
values at compile time

➢Java programming language enum types are much more powerful than their counterparts in other
languages.
➢The enum declaration defines a class (called an enum type). The enum class body can include
methods and other fields.
➢The compiler automatically adds some special methods when it creates an enum. For example, they
have a static values method that returns an array containing all of the values of the enum in the order
they are declared. This method is commonly used in combination with the for-each construct to iterate
over the values of an enum type.

➢For example, this code from the Planet class example below iterates over all the planets in the solar
system.

for (Planet p : [Link]()) {


[Link]("Your weight on……);
}
enum : Example
enum Days {
MON, TUE,WED,THU,FRI,SAT,SUN; public static void main(String[] args) {
}
EnumTest first=new EnumTest([Link]);
public class EnumTest { [Link]();
Days day; EnumTest third=new EnumTest([Link]);
public EnumTest(Days day) { [Link]();
[Link] = day; EnumTest fifth=new EnumTest([Link]);
} [Link]();
public void daysOfWeek() { EnumTest sixth=new EnumTest([Link]);
switch (day) { [Link]();
case MON: EnumTest seven=new EnumTest([Link]);
[Link]("Mondays are bad."); [Link]();
break;
case FRI: Days d[]=[Link]();
[Link]("Fridays are better."); for (Days d1:d)
break; [Link](d1);
case SAT: }
case SUN: }
[Link]("Weekends are best.");
break; /* Mondays are bad.
default: Midweek days are so-so.
[Link]("Midweek days are so-so."); Fridays are better.
break; Weekends are best.
} Weekends are best
} MON…..
*/
Next ….

Exception Handling
Session 6:

Learning Objectives

➢ Describe Exception Handling Mechanism in Java


Exception Handling
Exception Handling

Kinds of Errors Source of Errors


Input Errors
•Compile time errors Device Errors
•Run time errors Physical Limitations
Code Errors

What should be done when an error occurred?

• Notify the user if an error occurs


• Save all work
• Allow users to exit from the program smoothly

295
What is Exception Handling?

• An exception signifies an illegal, invalid or unexpected


issue during program execution.

• An exception is an event that occurs during the execution


of a program that disrupts the normal flow of instructions.

• Since exceptions are almost always assumed to be


anticipated, you need to provide appropriate exception
handling.

Approaches for dealing with error conditions


• Using Conditional statements and return values
• Use Java’s exception handling mechanism

296
division by zero

class DivisionByZeroHandled
{
int c;

public int compute(int a, int b)


{
if(b==0) return 0;
else
c=a/b;
return c;
}
}

29-Mar-22
297
Handling Exceptions - Java

Format:

try
{
// Code that may cause an error/exception to occur
}

catch (ExceptionType identifier)


{
// Code to handle the exception
}

29-Mar-22
298
Handling Exceptions: DivisionByZero

class DivisionByZeroHandled
{
public static void main(String[] args)
{
int a=5, b=0, c=0;
try
{
c=a/b;
}catch(Exception e){
[Link](e);
}
[Link](“Handled Exception");
}
}

29-Mar-22
299
Handling Exceptions: Result Of Calling readLine ()

try
{
[Link]("Type an integer: ");
BufferedReader br=new BufferedReader(new InputStreamReader([Link]));
String s =[Link](); The exception
[Link]("You typed in..." + s); can occur here
int num = [Link] (s);
[Link]("Converted to an integer..." + num);
}

Note: Checked Exception 300


Handling Exceptions: Result Of Calling ParseInt ()

try
{
[Link]("Type an integer: ");
BufferedReader br=new BufferedReader(new InputStreamReader([Link]));
String s =[Link]();
[Link]("You typed in..." + s);
num = [Link] (s); The second exception
[Link]("Converted to an integer..." + num); can occur here
}

Note: Unchecked Exception 301


Where The Exceptions Occur In Class Integer?

class Integer
{
public Integer (int value);
public Integer (String s) throws NumberFormatException;

public static int parseInt (String s) throws


NumberFormatException;

29-Mar-22
302
Handling Exceptions: Tracing The Example

[Link] (String s)
{
:

main () :

try }

{
num = [Link](s);
}
:
catch (NumberFormatException e)
{
:
}
303
Handling Exceptions: Tracing The Example

[Link] (String s)
{
Oops!
main () The user didn’t enter an integer
try }

{
num = [Link] (s);
}
:
catch (NumberFormatException e)
{
:
}29-Mar-22
304
Handling Exceptions: Tracing The Example

[Link] (String s)
{
NumberFormatException e =

main () new NumberFormatException ();

try }

{
num = [Link] (s);
}
:
catch (NumberFormatException e)
{
:
}
305
Handling Exceptions: Tracing The Example

[Link] (String s)
{
NumberFormatException e =

main () new NumberFormatException ();

try }

{
num = [Link] (s);
}
:
catch (NumberFormatException e)
{
:
}
306
Handling Exceptions: Tracing The Example

[Link] (String s)
{

main ()
try }

{
num = [Link] (s);
}
:
catch (NumberFormatException e)
{

Exception must be dealt with here


}
307
Handling Exceptions: Catching The Exception

catch (NumberFormatException e)
{
[Link](e);
}

29-Mar-22
308
Catching The Exception: Error Messages

catch (NumberFormatException e)
{
[Link]([Link]());
[Link](e);
[Link]();
}

29-Mar-22
309
Catching The Exception: Error Messages

catch (NumberFormatException e)
{ For input string: ”cdac"
[Link]([Link]());
[Link](e);
[Link]();
}
[Link]
} For input string: “cdac"
}

[Link]: For input string: “cdac"


at
[Link]([Link])
at [Link]([Link])
at [Link]([Link])
at [Link]([Link])
310
Java Exception class hierarchy

ClassNotFoundException

CloneNotSupportedException
Exception
IOException
ArithmeticException
AWTException
NullPointerException
RuntimeException
Object Throwable IndexOutOfBoundsException

NoSuchElementException
LinkageError

VirtualMachoneError
Error
AWTError
Checked

Unchecked
Checked Exceptions
• Must be handled if the potential for an error exists
– must use a try-catch block

• Deal with problems that occur in a specific place


– When a particular method invoked enclose it within a try-
catch block

• Example:
– SQLException, IOException

29-Mar-22 314
Checked Exceptions
Characteristics Of Unchecked Exceptions

• The compiler doesn’t require you to handle them if they are thrown.
– No try-catch block required by the compiler

• They can occur at any time in the program (not just for a specific
method)

• Examples:
– NullPointerException,IndexOutOfBoundsException,
ArithmeticException…

29-Mar-22
316
Run Time Exceptions (Unchecked)
Common Unchecked Exceptions: NullPointerException

int [] arr = null;


arr[0] = 1;
NullPointerException

arr = new int [4];


int i;
for (i = 0; i <= 4; i++)
arr[i] = i;

arr[i-1] = arr[i-1] / 0;

29-Mar-22
318
Common Unchecked Exceptions: ArrayIndexOutOfBoundsException

int [] arr = null;


arr[0] = 1;

arr = new int [4];


int i;
for (i = 0; i <= 4; i++)
ArrayIndexOutOfBoundsException
arr[i] = i;
(when i = 4)
arr[i-1] = arr[i-1] / 0;

29-Mar-22
319
Common Unchecked Exceptions: ArithmeticExceptions

int [] arr = null;


arr[0] = 1;

arr = new int [4];


int i;
for (i = 0; i <= 4; i++)
arr[i] = i;

arr[i-1] = arr[i-1] / 0;

ArithmeticException
(Division by zero)

29-Mar-22
320
Keywords – Exception Handling in Java
[Link]
[Link]
[Link]
[Link]

1.7 onwards… multi catch is also provided! Use | symbol


[Link]
The Finally Clause

• An additional part of Java’s exception handling model (try-catch-


finally).

• Used to enclose statements that must always be executed whether


or not an exception occurs.

✓ finally block will be executed whether or not an exception is thrown.

✓ Each try clause requires at least one catch or finally clause.


The Finally Clause: Exception Thrown

[Link] ()
{
try
2) Exception thrown here
{
}
[Link]();
}

catch
{
}

finally 4) A the end of the catch


block control transfers
{ to the finally clause
} 331
The Finally Clause: No Exception Thrown

[Link] ()
{
try
2) Code runs okay here
{
}
[Link]();
}

catch
{
}

finally
{
} 332
[Link]
throw

✓ It is possible for your program to throw an exception explicitly


throw ThrowableInstance

✓ Here, ThrowableInstance must be an object of type


Throwable or a subclass Throwable

✓ There are two ways to obtain a Throwable objects:


✓ Using a parameter into a catch clause
✓ Creating one with the new operator
throw

[Link]
Example -throw Statements

Output:
Caught inside demoproc.
Recaught: [Link]: demo
[Link]
[Link]
throws

✓ If a method is capable of causing an exception that it does not


handle, it must specify this behavior so that callers of the
method can guard themselves against that exception
✓ type method-name parameter-list) throws exception-list
{
// body of method
}
✓ It is not applicable for Error or RuntimeException, or any
of their subclasses
Example: incorrect program
Example: corrected version

Output:
Inside throwOne. [Link]
Caught [Link]: demo
[Link]
User Defined Exception

✓ Define a subclass of the Exception class.


✓ The new subclass inherits all the methods of Exception and
can override them.
class MyException extends Exception{
private int a;
MyException(int i) {
a = i;
}
public String toString (){
return “MyException [” + a + “ ]”;
}
Example contd..

class test{
static void compute (int a) throws Myexception{
if(a>10) throw new MyException(a);
[Link](“Normal Exit”);
}
public static void main(String args[]){
try{
compute(1);
compute(20);
}catch(MyException e){ [Link](“Caught “ +e);
}
}

[Link] [Link]
class MyException extends Exception {
public MyException (String errorMessage) {
super (errorMessage);
} public class ExceptionEx
} {
public static void main(String args[]) {
class MyMarks{ try {
private int marks=0;

public void setMarks(int mark) throws MyException { MyMarks mm=new MyMarks();


if(mark>0){
[Link]=marks; [Link](-1);
}
else{ int i=[Link]();
throw new MyException("Invalid Marks");
} [Link](i);
}
}
public int getMarks(){ catch(MyException e)
return marks; {[Link](e);}
} }
} }
public class NilBalanceException extends Exception{ public class ExceptionTest {

public NilBalanceException(String errMsg) { public static void main(String[] args) {


super(errMsg);
Bank b=new Bank();
}
try {
} [Link](20000);
}
class Bank{ catch(Exception e){
double amount=10000; [Link](e);}
}
}
void withdraw(double amt) throws NilBalanceException {

if(amt>amount){
throw new NilBalanceException("Insufficient Funds to
withdraw!!");

}
}
}
Try with
resources

Example1: Example 2: try with resources

try(BR br=new BR(new BR([Link]))){


BR br=null;
[Link]();
try{ }
BR br=ner BR(); catch(IOException e){
[Link]();// and rest of the code Handling code
} }
catch(Exception e){
Handling code // finally not required
}
finally{
if(br!=null)
try(r1;r2;r3){
[Link]()
}
// resources should be AutoCloseable resources
}

Note: 1.7 onwards…. try with resources is possible without catch or finally
try with resources

public class TryDemo {


public static void main(String[] args) {
try(BufferedReader br=new BufferedReader(new InputStreamReader([Link]))){
String name= [Link]();
[Link]("Hi "+name);
}catch(IOException e){
[Link](e);
}
}
}

public class TryDemo {


public static void main(String[] args) throws IOException {
try(BufferedReader br=new BufferedReader(new InputStreamReader([Link]))){
String name= [Link]();
[Link]("Hi "+name);
}
}
}

// works well without catch


Next ….

Arrays
String Handling
[Link]
[Link]
Session 7:

Learning Objectives

➢ Arrays in Java

➢ String Handling

➢ [Link]

➢ [Link]
String Handling
29-Mar-22
356
29-Mar-22
357
29-Mar-22
358
29-Mar-22
359
[Link]

29-Mar-22
360
29-Mar-22
361
29-Mar-22
362
29-Mar-22
363
29-Mar-22
364
29-Mar-22
365
29-Mar-22
366
29-Mar-22
367
29-Mar-22
368
29-Mar-22
369
29-Mar-22
370
29-Mar-22 [Link]
371
29-Mar-22
372
29-Mar-22
373
29-Mar-22
374
29-Mar-22
375
29-Mar-22
376
29-Mar-22
377
29-Mar-22
378
29-Mar-22
379
29-Mar-22
380
29-Mar-22
381
29-Mar-22
382
29-Mar-22
383
29-Mar-22
384
Object class

29-Mar-22 385
29-Mar-22 386
29-Mar-22 387
[Link] package

29-Mar-22
388
[Link] package

29-Mar-22 389
[Link]
• The [Link] class is the superclass of classes BigDecimal,
BigInteger, Byte, Double, Float, Integer, Long, and Short
• The Subclasses of Number must provide methods to convert the represented
numeric value to byte, double, float, int, long, and short

Declaration for [Link] class:

public abstract class Number extends Object implements Serializable

Constructor:
➢ Number() -This is the Single Constructor

Methods:
➢ byte byteValue() -This method returns the value of the specified number as a byte
➢ abstract double doubleValue() -This method returns the value of the specified number as
a double
➢ abstract float floatValue() - This method returns the value of the specified number as a
float
➢ abstract int intValue() - This method returns the value of the specified number as a int
➢ abstract long longValue() - This method returns the value of the specified number as a
long.
29-Mar-22 390
➢ short shortValue() - This method returns the value of the specified number as a short
[Link]
• The [Link] class contains methods for performing basic numeric operations such
as the elementary exponential, logarithm, square root, and trigonometric functions.
• Declaration for [Link] class:
public final class Math extends Object
• Fields: static double E and static double PI
Methods:
static double abs(double a) - This method returns the absolute value of a double value
static double acos(double a) - This method returns the arc cosine of a value
static double ceil(double a) - Returns the smallest double value that is >= to the argument
static double cos(double a) - This method returns the trigonometric cosine of an angle
static double exp(double a) - Returns Euler's number e raised to the power of a double value
static double floor(double a) Returns the largest double value that is <= to the argument
static double log(double a) - Returns the natural logarithm (base e) of a double value
static double max(double a, double b) - Returns the greater of two double values
static double min(double a, double b) - Returns the smaller of two double values
static double pow(double a, double b) - Returns the value of the first argument raised to the power of the
second argument.
static double random() - Returns a double value with a positive sign, greater than or equal to 0.0 and less
than 1.0.
static long round(double a) - This method returns the closest long to the argument
static double sqrt(double a) - Returns the correctly rounded positive square root of a double value.

391
29-Mar-22
[Link]
The [Link] class contains several useful class fields and methods.
It cannot be instantiated.
Facilities provided by System:
•standard output
•error output streams
•standard input and access to externally defined properties and environment variables.
•A utility method for quickly copying a portion of an array.
•a means of loading files and libraries
Fields:
•static PrintStream err -- This is the "standard" error output stream
•static InputStream in -- This is the "standard" input stream
•static PrintStream out -- This is the "standard" output stream
Methods:
static void arraycopy(Object src, int srcPos, Object dest, int destPos, int length) -
It copies an array from the specified source array, beginning at the specified position, to the
specified position of the destination array
static Console console() -
Returns the unique Console object associated with the current Java virtual machine, if any
static void gc() - This method runs the garbage collector
static Properties getProperties() - Determines the current system properties
static Console console() - Returns the unique Console object associated with the current Java
virtual machine, if any.

29-Mar-22 392
[Link] package

29-Mar-22
393
[Link] package – working with Date and Scanner
• The [Link] class represents a specific instant in time, with millisecond
precision
• The [Link] class is a simple text scanner which can parse primitive
types and strings using regular expression

Example:

import [Link].*;
public class DateDemo {
public static void main(String[] args) {
Date d=new Date();
[Link](d);

Scanner sc=new Scanner([Link]);


[Link]("Enetr Your Name:");
String name=[Link]();
[Link](name);
}
}
29-Mar-22
394
Session 8:

Learning Objectives

➢ Explain Java IO

➢ Describe Streams

➢ Byte / Character
➢ Text /Character
Overview of I/O Streams

To bring in information, a program opens a stream on an


information source (a file, memory, a socket) and reads the
information sequentially, as shown in the following figure.
Overview of I/O STREAMS
Similarly, a program can send information to an external
destination by opening a stream to a destination and writing
the information out sequentially, as shown in the following
figure.
Overview of I/O streams

• The [Link] package contains a collection of stream classes that


support algorithms for reading and writing.
• To use these classes, a program needs to import the [Link]
package.
• The stream classes are divided into two class hierarchies, based
on the data type (either characters or bytes) on which they operate
i.e Character Stream and Byte Stream

• Java has predefined byte streams:


– [Link]
– [Link]
– [Link]
I/O Streams
• JAVA distinguishes between 2 types of streams:
• Text – streams, containing ‘characters‘

Program I ‘ M A S T R I N G \n Device

•Binary Streams, containing 8 – bit information

Program 01101001 11101101 00000000 Device


Streams
• Streams in JAVA are Objects, of course!
Having
• 2 types of streams (text / binary) and
• 2 directions (input / output)

• Results in 4 base-classes dealing with I/O:

1. Reader: text-input
2. Writer: text-output
3. InputStream: byte-input
4. OutputStream: byte-output
InputStream Streams

OutputStream
binary

Reader

Writer
text
Character Streams

• Reader and Writer are the abstract super classes for character
streams in [Link]
• Reader provides the API and partial implementation for
readers ( streams that read 16-bit characters )
• Writer provides the API and partial implementation for writers
(streams that write 16-bit characters).
Character Streams
• The following figure shows the class hierarchies
for the Reader and Writer classes.
Writer Class:
Character Streams
• The following figure shows the class hierarchies
for the Reader and Writer classes.

Reader class:
Writing Textfiles
• Class: FileWriter
• Frequently used methods:
Writing Textfiles
• Using FileWriter
• It is not very convenient
• is not efficient (every character is written in a single step,
invoking a huge overhead)
• Better: wrap FileWriter with processing streams
• BufferedWriter
• PrintWriter
Example
• Writing a textfile:

– Create a stream object and


associate it with a disk-file
– Give the stream object
the desired functionality
– write data to the stream
– close the stream.
Wrapping Textfiles
• BufferedWriter:
• Buffers output of FileWriter, i.e. multiple
characters are processed together, enhancing
efficiency

• PrintWriter
• provides methods for convenient handling, e.g.
println()
• ( remark: the [Link]() – method is a method of the PrintWriter-
instance [Link] ! )
Wrapping a Writer
• A typical code segment for opening a convenient,
efficient textfile:

• FileWriter out = new FileWriter("[Link]");


• BufferedWriter b = new BufferedWriter(out);
• PrintWriter p = new PrintWriter(b);
Or
• with anonymous (‘unnamed‘) objects:
• PrintWriter p = new PrintWriter(new BufferedWriter(
new FileWriter("[Link]")));
Reading Textfiles
• Class: FileReader
• Frequently used Methods:

(The other methods are used for


positioning)
Wrapping a Reader
• Using FileReader is not very efficient.
• Better wrap it with BufferedReader:

• BufferedReader br =new BufferedReader(


• new FileReader(“name“));

• Remark: BufferedReader contains the method readLine(), which


is convenient for reading textfiles
EOF Detection
• Detecting the end of a file (EOF):
• Usually amount of data to be read is not known
• Reading methods return ‘impossible‘ value if end of file is
reached
• Example:
– [Link] returns -1
– [Link]() returns ‘null‘
• Typical code for EOF detection:
• while ((c = [Link]() != -1){ // read and
check c
...do something with c
}
Example
import [Link].*;
public class IOTest1 import [Link].*;
{ public class BReader {
public static void main(String[] args)
{ public static void main(String[] args) throws
try{ IOException {
BufferedReader myInput = new BufferedReader(new BufferedReader br=new BufferedReader(new
FileReader("[Link]"));
FileReader("[Link]"));
BufferedWriter myOutput = new BufferedWriter(new
String line=[Link]();
FileWriter("[Link]")); while(line!=null){
int c; [Link](line);
while((c=[Link]()) != -1) line=[Link]();
[Link](c); }
[Link](); [Link]();
[Link](); }
}catch(IOException e){} }
}
}
Byte Streams
• To read and write 8-bit bytes, programs should use the byte streams,
descendents of InputStream and OutputStream .

• InputStream and OutputStream provide the API and partial implementation


for input streams (streams that read 8-bit bytes) and output streams (streams
that write 8-bit bytes).

• These streams are typically used to read and write binary data such as
images and sounds.

• Two of the byte stream classes, ObjectInputStream and


ObjectOutputStream, are used for object serialization.
import [Link].*; The scanner class
import [Link];
import [Link];
public class scanIn {
public static void main(String[] args) {
String first, last;
int ssn;
try{
Scanner sc = new Scanner(new File("[Link]"));
while ([Link]()) {
first = [Link]();
last = [Link]();
ssn = [Link]();
[Link]("First: " + first + "\nLast: " + last + "\nSSN: " + ssn);
}
}catch (FileNotFoundException e){
[Link](e);
} //end catch
} //end main
} // end class
DataInputStream
/*Example using DataInputStream.*/
import [Link];
public class InputOutput
{
public static void main(String[] as)
{
try
{
DataInputStream dis = new DataInputStream([Link]);
[Link]("Enter First Number");
int a =[Link]([Link]());
[Link]("Enter Second Number");
int b = [Link]([Link]());
int sum = a+b;
[Link]("Sum is "+sum);
}
catch (Exception e)
{ [Link](); }
}
}
Output:
Enter First Number
2
Enter Second Number
4
Sum is 6
Next….

Multithreading
Session 9:

Learning Objectives

➢ Explain Multithreading
Multithreading
Threads
• Threads are lightweight processes as the overhead of switching between
threads is less
• The can be easily spawned
• The Java Virtual Machine spawns a thread when your program is run
called the Main Thread

Why do we need threads?


• To enhance parallel processing
• To increase response to the user
• To utilize the idle time of the CPU
• Prioritize your work depending on priority
Thread States
Example

class MyThread extends Thread{

public void run(){ // job of thread


for (int i=0;i<10;i++)
[Link]("Child Thread!!");
}
public static void main(String[] args){
MyThread t=new MyThread(); // Thread instantiation
[Link](); // starting a thread

for(int i=0;i<10;i++)
[Link]("Main Thread!!");
}
}
Example
class MyRunnable implements Runnable{
public void run(){ // job of thread
for (int i=0;i<10;i++)
[Link]("Child Thread!!");
}
public static void main(String[ ] args){
MyRunnable r= new MyRunnable(); // MyRunnable instantiation
Thread t=new Thread(r); // thread instantiation
[Link](); // starting a thread

for(int i=0;i<10;i++)
[Link]("Main Thread!!");
}
}
Sleeping a thread - sleep() method
•used to sleep a thread for specific time
Problem ---run() directly
The current Thread() method:
Daemon Thread
Understanding the problem without Synchronization

class Table{
void printTable(int n){ //method not synchronized class Use{
for(int i=1;i<=5;i++){
[Link](n*i);
public static void main(String args[]){
try{ Table obj = new Table();//only one object
[Link](400); MyThread1 t1=new MyThread1(obj);
}catch(Exception e){[Link](e);} MyThread2 t2=new MyThread2(obj);
} [Link]();
} [Link]();
}
}
class MyThread1 extends Thread{ }
Table t;
Output:
MyThread1(Table t){
this.t=t; 5
}
public void run(){ 100
[Link](5);
} 10
200
}
class MyThread2 extends Thread{ ….
Table t;
MyThread2(Table t){ …
this.t=t;
}
public void run(){
[Link](100);
}
} USE --- synchronized void printTable()
Example 2: synchronization
public class Greeting {
public class MyThread extends Thread{
public synchronized void wish(String name){
Greeting g;
for(int i=0;i<10;i++){
String name;
[Link]("Good Morning:");
try{
public MyThread(Greeting g, String name) {
[Link](5000);
this.g=g;
}catch(InterruptedException e){}
[Link]=name;
[Link](name);
}
}
@Override
}
public void run(){
}
[Link](name);
}

public class SynchronizedDemo { }

public static void main(String[] args) {


Output:
Good Morning:DAC
Greeting g=new Greeting(); Good Morning:DAC
MyThread t1=new MyThread(g,"DAC"); Good Morning:DAC
Good Morning:DAC
MyThread t2=new MyThread(g, "DSSD"); Good Morning:DAC
Good Morning:DAC
[Link](); Good Morning:DAC
[Link](); Good Morning:DAC
Good Morning:DAC
} Good Morning:DAC
Good Morning:DSSD
} Good Morning:DSSD
Good Morning:DSSD
Good Morning:DSSD
Good Morning:DSSD
Good Morning:DSSD
Good Morning:DSSD
Good Morning:DSSD
Good Morning:DSSD
Good Morning:DSSD
Example 3: synchronization
public class Display {
public synchronized void dispn(){ public class Mythread1 extends Thread{
for(int i=1;i<=10;i++){ Display d;
[Link](i);
try{ public Mythread1(Display d) {
[Link](3000); this.d = d;
}catch(InterruptedException e){} }
} public void run(){
} [Link]();
}
public synchronized void dispc(){ }
for(int i=65;i<75;i++){
class Mythread2 extends Thread{
[Link]((char)i);
Display d;
try{
[Link](3000);
public Mythread2(Display d) {
}catch(InterruptedException e){} this.d = d;
} }
} public void run(){ Output:
} [Link](); 1
2
} 3
} 4
5
6
7
8
public class SyncDemo { 9
public static void main(String[] args) { 10
A
Display d=new Display(); B
C
D
Mythread1 t1=new Mythread1(d); E
F
Mythread2 t2=new Mythread2(d); G
H
[Link](); I
J
[Link]();
}
}
Program of synchronized block

class Table{

void printTable(int n){


synchronized(this){ //synchronized block
for(int i=1;i<=5;i++){
[Link](n*i);
try{
[Link](400);
}catch(Exception e){[Link](e);}
}
}
}//end of the method

}
Example : Inter thread communication

class Customer{
int amount=10000; class Test{
synchronized void withdraw (int amount){ public static void main(String args[]){
[Link]("going to withdraw..."); Customer c=new Customer();
new Thread(){
if([Link]<amount){ public void run(){[Link](15000);}
[Link]("Less balance; waiting for deposit..."); }.start();
try{wait();}catch(Exception e){} new Thread(){
} public void run(){[Link](10000);}
[Link]-=amount; }.start();
[Link]("withdraw completed..."); }
} }

synchronized void deposit(int amount){ Output:


[Link]("going to deposit..."); going to withdraw…
[Link]+=amount; Less balance; waiting for deposit…
[Link]("deposit completed... "); going to deposit…
deposit completed...
notify(); withdraw completed...
}
}
Example : Deadlock

public class A { public class B {


public synchronized void m2(A a){
public synchronized void m1(B b){ [Link]("Thread 2 starts execution of
[Link]("Thread 1 starts execution of m1() ");
m1() "); try{
try{ [Link](5000);
[Link](5000); }catch(InterruptedException ie){}
}catch(InterruptedException ie){}
[Link]();
[Link](); }
} public synchronized void dead(){
public synchronized void dead(){ [Link]("Inside B, dead()");
[Link]("Inside A, dead()"); }
} }
}

public class Deadlock extends Thread { Output: (deadlock)


A a=new A();
B b=new B();
Thread 1 starts execution of m1()
public void fun(){ Thread 2 starts execution of m1()
[Link]();
a.m1(b); //main thread >>>>>>>>>>>>>>><<<<<<<<<<<<<<<<<<<<
} If not synchronized…no deadlock (no locks)
public void run(){
b.m2(a); // child thread
}
public static void main(String[] args) {
Deadlock d=new Deadlock();
[Link]();
}
}
Session 10:

Learning Objectives

By the end of this session, you must be able to

➢ Collection Framework
Collection Framework
Introduction:
An array is an indexed collection of fixed number of homogeneous data elements
Limitations of Array Objects :
[Link] are fixed in size
[Link] can hold only homogeneous data elements
Example:
Student[] s=new Student(1000);
s[0]=new Student();
s[1]=new Student();
s[2]=new Customer(); // CE – Incompatible types
But this problem can be resolved by using Object type arrays.
Example:
Object[] a= new Object[1000];
a[0]=new Student();
a[1]=new Customer();
3. Arrays concept not built based on some underlying data structures
Collection Framework
Advantages of Collections over Arrays:
[Link] are grow able in nature – may increase or decrease – as per requirement
[Link] can hold both homogeneous & heterogeneous objects
[Link] collection class is implemented based on some data structures. Readymade method support is
available for every requirement

Note:
•Arrays can be used to hold both primitives & objects
•Collections can be used to hold only objects but not for primitives

Collection:
A group of individual objects as a single entity is called “Collection”
Collection Framework
Collection framework:
A collections framework is a unified architecture for representing and manipulating collections
All collections frameworks contain the following:
Interfaces: These are abstract data types that represent collections. Interfaces allow collections to be
manipulated independently
Implementations (Classes): These are the concrete implementations of the collection interfaces. In
essence, they are reusable data structures.
Algorithms (methods): These are the methods that perform useful computations, such as searching
and sorting, on objects that implement collection interfaces. The algorithms are said to be olymorphic

The Java Collections Framework provides the following benefits:

❖ Reduces programming effort


❖ Increases program speed and quality
❖ Allows interoperability among unrelated APIs
❖ Fosters software reuse, etc.,
9 – Key Interfaces of Collection Framework
1. Collection (Interface):
In general, Collection interface is considered as root interface of Collection Framework
Collection interface defines the most common methods which can be applicable for any collection object.

The Collection interface contains methods that perform basic operations, such as:
int size()
boolean isEmpty()
boolean contains(Object element)
boolean add(E element)
boolean remove(Object element)
iterator<E> iterator()

Collection Interface Bulk Operations


Bulk operations perform an operation on an entire Collection. The following are the bulk operations:

containsAll( ) : returns true if the target Collection contains all of the elements in the specified Collection.
addAll( ) : adds all of the elements in the specified Collection to the target Collection.
removeAll( ) : removes from the target Collection all of its elements that are also contained in the specified Collection.
retainAll( ) : it retains only those elements in the target Collection that are also contained in the specified Collection.
clear( ) : removes all elements from the Collection.
9 – Key Interfaces of Collection Framework
9 – Key Interfaces of Collection Framework
2. List (Interface):
✓ It is a child interface of Collection
✓ A List is an ordered Collection (sometimes called a sequence). Lists may contain duplicate elements.
✓ Used to represent a group of individual objects where insertion order is preserved & duplicates are allowed

*Vector & Stack are legacy classes


In addition to the operations inherited from Collection, the List interface includes operations for the following:
✓ Positional access : manipulates elements based on their numerical position in the list.
This includes methods such as get(), set(), add(), addAll(), and remove()

✓ Search : searches for a specified object in the list and returns its numerical position.
Search methods include indexOf() and lastIndexOf()

✓ Iteration : extends Iterator semantics to take advantage of the list's sequential nature. The listIterator methods
provide this behavior- hasPrevious(), next() and previous(), hasNext(), etc

✓ Range-view : The subList() method performs arbitrary range operations on the list.
Ex: [Link](fromIndex, toIndex).clear(); // removes those ranged values
9 – Key Interfaces of Collection Framework
Most polymorphic algorithms in the Collections class apply specifically to List .

sort(list l) :sorts a List using a merge sort algorithm, which provides a fast, stable sort.

shuffle ( ) : randomly permutes the elements in a List.

reverse ( ): reverses the order of the elements in a List.

rotate ( ): rotates all the elements in a List by a specified distance.

swap ( ): swaps the elements at specified positions in a List.

replaceAll ( ): replaces all occurrences of one specified value with another.

fill( ): overwrites every element in a List with the specified value.

copy ( ): copies the source List into the destination List.

binarySearch( ): searches for an element in an ordered List using the binary search algorithm.

indexOfSubList( ): returns the index of the first sublist of one List that is equal to another.

lastIndexOfSubList( ): returns the index of the last sublist of one List that is equal to another.
9 – Key Interfaces of Collection Framework
3. Set (Interface):
✓ It is a child interface of Collection
✓ A Set is a Collection that cannot contain duplicate elements
✓ Used to represent a group of individual objects where insertion order is
not preserved & duplicates are not allowed
✓ The Set interface contains only methods inherited from Collection and
adds the restriction that duplicate elements are prohibited

There are three general-purpose Set implementations:


HashSet, TreeSet, and LinkedHashSet.

HashSet :
✓ stores its elements in a hash table, is the best-performing implementation;
however it makes no guarantees concerning the order of iteration.
TreeSet :
✓ stores its elements in a red-black tree, orders its elements based on their
values; it is substantially slower than HashSet.
LinkedHashSet:
✓ implemented as a hash table with a linked list running through it, orders
its elements based on the order in which they were inserted into the set
(insertion-order).
✓ LinkedHashSet spares its clients from the unspecified, generally chaotic
ordering provided by HashSet at a cost that is only slightly higher.
9 – Key Interfaces of Collection Framework
Basic Operations on Set:
size() method returns the number of elements in the Set (its cardinality)

isEmpty() method returns whether the set is empty or not

add() method adds the specified element to the Set if it is not already present and returns a boolean
indicating whether the element was added

remove() method removes the specified element from the Set if it is present and returns a boolean
indicating whether the element was present

iterator() method returns an Iterator over the Set

4. SortedSet (Interface):

✓ It is a child interface of Set


✓ Used to represent a group of individual objects according to some sorting order

5. NavigableSet (Interface):

✓ It is a child interface of SortedSet


✓ Defines several methods for navigation purpose
9 – Key Interfaces of Collection Framework
6. Queue (Interface):
✓ It is a child interface of Collection
✓ Used to represent a group of individual objects prior to processing
✓ A Queue is a collection for holding elements prior to processing.
✓ Besides basic Collection operations, queues provide additional
insertion, removal, and inspection operations.

The Queue interface follows:

✓ public interface Queue<E> extends Collection<E> {


E element(); // return head
boolean offer(E e); // add
E peek(); // return head
E poll(); //remove
E remove(); // remove
}

Queue Interface Structure


Type of Operation Throws exception Returns special value
Insert add(e) offer(e)
Remove remove() poll()
Examine element() peek()
9 – Key Interfaces of Collection Framework
Deque (Interface):

✓ Usually pronounced as deck, a deque is a double-ended-queue.


✓ A double-ended-queue is a linear collection of elements that supports the insertion and removal of elements at
both end points.
✓ The Deque interface, defines methods to access the elements at both ends of the Deque instance.
✓ Methods are provided to insert, remove, and examine the elements.

Deque Methods
First Element (Beginning of the Last Element (End of the Deque
Type of Operation
Deque instance) instance)

addFirst(e) addLast(e)
Insert
offerFirst(e) offerLast(e)

removeFirst() removeLast()
Remove
pollFirst() pollLast()

getFirst() getLast()
Examine
peekFirst() peekLast()

❖ All the above interfaces (Collection, List, Set, SortedSet, NavigableSet, Queue) used to represent a group of
individual objects only.

❖ To represent group of objects as key-value pairs , then Map interface has to be used
9 – Key Interfaces of Collection Framework
7. Map (Interface):

✓A Map is an object that maps keys to values.


✓ A map cannot contain duplicate keys: Each key can map to at most one value.
✓Map is used to represent a group of individual objects as key-value pairs (Ex: id - name)
✓Both key and value are objects only
✓Duplicate keys are not allowed, but values can be duplicated

✓The Map interface includes methods for basic operations: put(), get(), remove(), containsKey(),
containsValue(), size(), and empty()

✓Bulk operations: (putAll() and clear(), and collection views (such as keySet(), entrySet(), and
values()).

Collection Views
The Collection view methods allow a Map to be viewed as a Collection in these three ways:

keySet — the Set of keys contained in the Map.


values — The Collection of values contained in the Map. This Collection is not a Set, because
multiple keys can map to the same value.
entrySet — the Set of key-value pairs contained in the Map. The Map interface provides a small
nested interface called [Link], the type of the elements in this Set.
9 – Key Interfaces of Collection Framework
7. Map (Interface):

❖Map is not child interface of Collection


❖Hashtable, Properties and Dictionary are the legacy classes

8. SortedMap (Interface):
✓It’s a child interface of Map
✓Used to represent a group of individual objects as key-value pairs according to some sorting order
✓Sorting should be done only based on keys but not on values

9. NavigableMap (Interface):
✓It’s a child interface of SortedMap
✓Defines several methods for navigation purpose
Collection Framework - Summary
Collection Framework : and more..

Utility Classes:
1. Arrays - applies for arrays
2. Collections - A List ‘l’ may be sorted as follows:
Collections. Sort(l);

Cursors (Iterators):
[Link] - for legacy classes
[Link] - Universal iterator
[Link] – list types

Interfaces (for Sorting):


1. Comparable – default order – natural sorting prder
2. Comparator - any other order
Array List Demo

import [Link]; ArrayList al1=new ArrayList();


[Link]("vasu");
import [Link].*; [Link]("sreenivas");
[Link](al);
public class ALDemo { [Link](1,"Sadhu");
public static void main(String[] args) { [Link](0,“cdac");
ArrayList al=new ArrayList(); [Link](al1);
int[] a={5,7,9,2,3,1}; [Link](al);
[Link](a);
for(int i:a) Iterator itr=[Link]();
[Link](i); while([Link]()){
[Link]([Link]());
[Link]("sreenivas"); }
[Link](10);
[Link](101); }
[Link](3.14); }
[Link]('s');
[Link](true);
Array List Demo

import [Link].*;

public class ALDemo1 {


public static void main(String[]
args) {

ArrayList al=new ArrayList();


[Link]("Sadhu");
[Link]("Sreenivas");
[Link]("35");
[Link]("8.5");
[Link]("Hyderabad");
[Link]("500089");
[Link]("true");
[Link](al);

// [Link](al);
[Link](al);

Iterator itr=[Link]();
while([Link]())
[Link]([Link]());

}
}
Linked List Demo

// [Link](al);
import [Link]; [Link](al);
import [Link]; ListIterator itr=[Link]();
import [Link]; while([Link]())
import [Link]; {
[Link]([Link]());
public class LLDemo1 {
}
public static void main(String[] args) { [Link]([Link]());
}
LinkedList al=new LinkedList(); }
[Link]("Sadhu");
[Link]("Sreenivas");
[Link]("35");
[Link]("8.5");
[Link]("Hyderabad");
[Link]("500089");
[Link]("true");
[Link]("Mr");
[Link]("false");
[Link](al);
Stack Demo

import [Link].*;
public class StackDemo {
public static void main(String[] args) {

Stack s=new Stack();


[Link](10);
[Link](20);
[Link](30);
[Link](40);
[Link](50);
[Link](s);
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
}

}
Vector Demo

import [Link].*;

public class VectorDemo {

public static void main(String[] args) {

Vector v=new Vector();


[Link]([Link]());
[Link]("Sadhu");
[Link]("Sreeni");
[Link]("Hyderabad");
[Link](v);

[Link](0);
[Link](v);
Enumeration e=[Link]();
while([Link]())

[Link]([Link]());

Iterator itr=[Link]();
while([Link]())
[Link]([Link]());
}
}
HashSet Demo

import [Link];

import [Link].*;
public class HashSetDemo {

public static void main(String[] args) {

LinkedHashSet h=new LinkedHashSet();


[Link]("TS");
[Link]("AP");
[Link]("UP");
[Link]("TS"); // false
[Link](123);
[Link](321);
[Link](null);
[Link](h);

Iterator i=[Link]();
while([Link]()){
[Link]([Link]());
}

}
}
TreeSet Demo

import [Link].*;
public class TreeSetDemo {

public static void main(String[] args) {

TreeSet t=new TreeSet();


[Link](10);
[Link](9);
[Link](11);
[Link](5);
[Link](15);
//[Link](null); not possible
// [Link]("ABC");
[Link](t);
[Link]([Link]());
[Link]([Link]());
[Link]([Link](11));
[Link]([Link](10));

Iterator itr=[Link]();
while([Link]())
[Link]([Link]());
}
}
PriorityQueue Demo

import [Link].*;
public class PriorityQueueDemo {
public static void main(String[] args) {

PriorityQueue pq=new
PriorityQueue();
[Link](10);
[Link](20);
[Link](500);
[Link](5);
[Link](50);
[Link](200);
[Link](1000);
[Link](pq);
[Link]();
[Link]();
[Link]();
[Link]([Link]());
[Link](pq);
}
}
ListIterator Demo
import [Link].*;
import [Link].*;

public class ListIteratorDemo {

public static void main(String[] args) {


LinkedList l=new LinkedList();
[Link]("sachin");
[Link]("saurabh");
[Link]("yuvi");
[Link]("dhoni");
[Link]("zaheer");
[Link](l);

ListIterator litr=[Link]();
while([Link]()){
String s=(String)[Link]();
if([Link]("zaheer"))
[Link]();
if([Link]("sachin"))
[Link]("Virat");

}
[Link](l);
}
HashMap Demo

//Set s=[Link]();
import [Link].*; //[Link](s);

public class HashMapDemo { Collection s1=[Link]();


public static void main(String[] args) { [Link](s1);
HashMap m=new HashMap(); Collection c=[Link]();
[Link]("sadhu",5400); [Link](c);
[Link]("simi",5400);
[Link]("sharan",6600); Set s2=[Link]();
[Link]("pramod",7600); Iterator itr=[Link]();
[Link](m); while([Link]()){
[Link]("nag",5400); [Link] m1=([Link])[Link]();
[Link]("bsrk",5400); [Link]([Link]()+"__"+[Link]());
[Link](m); }
}
}
TreeMap Demo

import [Link].*;

public class TreeMapDemo {


public static void main(String[] args) {

TreeMap m=new TreeMap(new MyComparator());


[Link](105,"asdf");
[Link](101, "pqr");
[Link](102, "abc");
[Link](103, "xyz");
[Link](104, "mno");
[Link](m);
}
}
class MyComparator implements Comparator{
public int compare(Object o1, Object o2){
String s1=[Link]();
String s2=[Link]();
return [Link](s1);
}
}
IdentityHashMap Demo

import [Link].*;
public class IdentityHashMapDemo {

public static void main(String[] args) {

IdentityHashMap m=new IdentityHashMap();


Integer i1=new Integer(10);
Integer i2=new Integer(10);
[Link](i1,"sadhu");
[Link](i2,"sreeni");
[Link](m);
}
}
Summary of Interfaces
➢The core collection interfaces are the foundation of the Java Collections Framework.

The Java Collections Framework hierarchy consists of two distinct interface trees:

➢The first tree starts with the Collection interface, which provides for the basic
functionality used by all collections, such as add and remove methods.
➢Its sub interfaces — Set, List, and Queue — provide for more specialized collections.
➢The Set interface does not allow duplicate elements. This can be useful for storing
collections such as a deck of cards or student records. The Set interface has a subinterface,
SortedSet, that provides for ordering of elements in the set.
➢The List interface provides for an ordered collection, for situations in which you need
precise control over where each element is inserted. You can retrieve elements from a List
by their exact position.
➢The Queue interface enables additional insertion, extraction, and inspection operations.
Elements in a Queue are typically ordered in on a FIFO basis.
➢The Deque interface enables insertion, deletion, and inspection operations at both the ends.
Elements in a Deque can be used in both LIFO and FIFO.

The second tree starts with the Map interface, which maps keys and values similar to a
Hashtable.
Map's subinterface, SortedMap, maintains its key-value pairs in ascending order or in an
order specified by a Comparator.

These interfaces allow collections to be manipulated independently of the details of their


representation.
Commonly used methods of Collection interface
ArrayList class:

Hierarchy of ArrayList class:


•Uses a dynamic array for storing
the [Link] extends AbstractList
class and implements List interface.

•Can contain duplicate elements.

•Maintains insertion order.

•Not synchronized.

•Random access because array


works at the index basis.

•Manipulation slow because a lot of


shifting needs to be occured.
Example of addAll(Collection c) method:
Example of removeAll() method:
Example of retainAll() method:
Generics
Java Generics programming is introduced in J2SE 5 to deal with type-safety of objects

Earlier to Generics, used to store any type of objects in collection.

Now, in generics, java programmer is forced to store specific type of objects

Advantage of Java Generics:

1)Type-safety :
Holds only a single type of objects in generics. It doesn’t allow to store other typed objects

2)Type casting is not required:


There is no need to typecast the object

3)Compile-Time Checking:
It is checked at compile time but not occur at runtime. The good programming strategy
says it is far better to handle the problem at compile time than runtime.
Generics
Earlier to Generics, type cast is used.

List list = new ArrayList();


[Link]("hello");
String s = (String) [Link](0);//typecasting

After Generics, don't need to typecast the object.

List<String> list = new ArrayList<String>();


[Link]("hello");
String s = [Link](0);

Compile Time Checking:

List<String> list = new ArrayList<String>();


[Link]("hello");
[Link](32);//Compile Time Error
Generics
Example of Generics in Java

We have just seen ArrayList class, also can use any collection class such as LinkedList,
HashSet, TreeSet, HashMap, Comparator etc.

import [Link].*;

class TestGenerics1{
public static void main(String args[]){
ArrayList<String> list=new ArrayList<String>();
[Link](“ABC");
[Link](“XYZ");
//[Link](32);//compile time error

String s=[Link](1);//type casting is not required


[Link]("element is: "+s);

Iterator<String> itr=[Link]();
while([Link]()){
[Link]([Link]());
}
}
}
Generics
Example of Java Generics using Map

import [Link].*;
class TestGenerics2{

public static void main(String args[]){

Map<Integer,String> map=new HashMap<Integer,String>();


[Link](1,“ABC");
[Link](4,“XYZ");
[Link](2,“PQR");

//Now use [Link] for Set and Iterator


Set<[Link]<Integer,String>> set=[Link]();

Iterator<[Link]<Integer,String>> itr=[Link]();
while([Link]()){
[Link] e=[Link]();//no need to typecast
[Link]([Link]()+" "+[Link]());
}

}
}
Generics
Generic class
A class that can refer to any type is known as generic class.
Here, we are using T type parameter to create the generic class of specific type.
Creating generic class:

class MyGen<T>{
T obj;
void add(T obj){
[Link]=obj;
}
T get(){
return obj;
}
}

The T type indicates that it can refer to any type (like String, Integer, Employee etc.). The type you
specify for the class, will be used to store and retrieve the data.

class TestGenerics3{
public static void main(String args[]){
MyGen<Integer> m=new MyGen<Integer>();
[Link](2);
//[Link](“ABC");//Compile time error
[Link]([Link]());
}
}
Generic Class - Example

class MyGen<T>{
T obj;
void add(T obj){
[Link]=obj;
}
T get(){
return obj;
}
}
public class GenericDemo {
public static void main(String[] args) {
MyGen<Integer> m1=new MyGen();
[Link](99);
[Link]([Link]());
// [Link]("AXBC");
MyGen<String> m2=new MyGen();
[Link]("Hello");
[Link]([Link]());
}

}
Generics
Type Parameters
The type parameters naming conventions are important to learn generics thoroughly.
The commonly type parameters are as follows:
T - Type
E - Element
K - Key
N - Number
V - Value
Generic Method
Like generic class, we can create generic method that can accept any type of argument. E to denote the
element.

public class TestGenerics4{


public static < E > void printArray(E[] elements) {
for (E element : elements){
[Link](element );
}
[Link]();
}
public static void main( String args[] ) {
Integer[] intArray = { 10, 20, 30, 40, 50 };
Character[] charArray = { ‘A', ‘B', ‘C', ‘D', ‘E',‘F',‘G',‘H',‘I',‘J' };

[Link]( "Printing Integer Array" );


printArray( intArray );

[Link]( "Printing Character Array" );


printArray( charArray );
}
}
Generics - wildcard
import [Link].*;
public class GenericWildCard {
public static void main(String[] args) {
List<Integer> ints = new ArrayList<>();
[Link](3); [Link](5); [Link](10);
double sum = sum(ints); // Incompatible types List<Integer> can not be converted to List<Number>
[Link]("Sum of ints="+sum);
}

public static double sum(List<Number> list){


double sum = 0;
for(Number n : list){
sum += [Link]();
}
return sum;
}
}

❑Now the problem with above implementation is that it won’t work with List of Integers or Doubles because
we know that List<Integer> and List<Double> are not related, this is when upper bounded wildcard is helpful.
❑ We use generics wildcard with extends keyword and the upper bound class or interface that will allow us to
pass argument of upper bound or it’s subclasses types.
Generics - wildcard
import [Link].*;
public class GenericWildCard {
public static void main(String[] args) {
List<Integer> ints = new ArrayList<>();
[Link](3); [Link](5); [Link](10);
double sum = sum(ints);
[Link]("Sum of ints="+sum);
}

public static double sum(List<? extends Number> list){


double sum = 0;
for(Number n : list){
sum += [Link]();
}
return sum;
}
}
Generics - Wildcard
The ? (question mark) symbol represents wildcard element. It means any type. If we write <? extends
Number>, it means any child class of Number e.g. Integer, Float, Double etc. Now, we can call the method
of Number class through any child class object.

import [Link].*; class GenericTest {


//creating a method that accepts only child class of Shape
abstract class Shape{
abstract void draw(); public static void drawShapes(List<? extends Shape> lists){
} for(Shape s:lists){
[Link]();//calling method of Shape class by child class instance
class Rectangle extends Shape{ }
void draw(){ }
[Link]("drawing rectangle"); public static void main(String args[]){
} List<Rectangle> list1=new ArrayList<Rectangle>();
} [Link](new Rectangle());

class Circle extends Shape{ List<Circle> list2=new ArrayList<Circle>();


void draw(){ [Link](new Circle());
[Link]("drawing circle"); [Link](new Circle());
}
} drawShapes(list1);
drawShapes(list2);
}
}
// drawing a rectangle!
//drawing a circle!
//drawing a circle!
Java Generics Unbounded Wildcard

Sometimes we have a situation where we want our generic method to be working with all
types, in this case unbounded wildcard can be used. Its same as using <? extends Object>.

import [Link].*;
public class GenericWildCard {
public static void main(String[] args) {
List<Integer> l1 = new ArrayList<>();
[Link](3); [Link](5); [Link](10);
printData(l1);

List<String> l2=new ArrayList<>();


[Link]("ABC");
[Link]("XYZ");
printData(l2);
}

public static void printData(List<?> list){


for(Object obj : list){
[Link](obj + " ");
}
}
}
Java Generics Lower bounded Wildcard

Suppose we want to add Integers to a list of integers in a method, we can keep the
argument type as List<Integer> but it will be tied up with Integers whereas List<Number>
and List<Object> can also hold integers, so we can use lower bound wildcard to achieve
this.

We use generics wildcard (?) with super keyword and lower bound class to achieve this.

We can pass lower bound or any super type of lower bound as an argument in this case,
java compiler allows to add lower bound object types to the list.

public static void addIntegers(List<? super Integer> list){


[Link](new Integer(50));
}
Serialization
Serialization in java is a mechanism of writing the state of an object into a byte
stream.

The reverse operation of serialization is called deserialization.

It is mainly used to pass/share object's state on the network (known as


marshalling).

Java transient keyword is used in serialization. If you define any data member
as transient, it will not be serialized.
Serialization
import [Link].*;
class Person implements Serializable //marker interface{
transient int age=30;
String name="ABC";
}
class SerializeTest{
static public void main(String[] args) throws Exception{
Person p1=new Person();
//serialization
FileOutputStream fos=new FileOutputStream("[Link]");
ObjectOutputStream oos=new ObjectOutputStream(fos);
[Link](p1);

//Deserialization
FileInputStream fis=new FileInputStream("[Link]");
ObjectInputStream ois=new ObjectInputStream(fis);
Person p2=(Person)[Link]();
[Link]([Link]+" "+[Link]+" "+[Link]+" "+[Link]);
}
} //output: 30 ABC 0 ABC transient means – value will not be serialized
Serialization
import [Link].*;

class Person implements Serializable{


transient static int age=30;
String name="ABC";
}
class SerializeTest{
static public void main(String[] args) throws Exception{
Person p1=new Person();
//serialization
FileOutputStream fos=new FileOutputStream("[Link]");
ObjectOutputStream oos=new ObjectOutputStream(fos);
[Link](p1);
//Deserialization
FileInputStream fis=new FileInputStream("[Link]");
ObjectInputStream ois=new ObjectInputStream(fis);
Person p2=(Person)[Link]();
[Link]([Link]+" "+[Link]+" "+[Link]+" "+[Link]);
}
} //30 ABC 30 ABC
Serialization
import [Link].*;

class Person implements Serializable{


transient static int age=30;
String name="ABC";
}
class SerializeTest{
static public void main(String[] args) throws Exception{
Person p1=new Person();
//serialization
FileOutputStream fos=new FileOutputStream("[Link]");
ObjectOutputStream oos=new ObjectOutputStream(fos);
[Link](p1);
//Deserialization
FileInputStream fis=new FileInputStream("[Link]");
ObjectInputStream ois=new ObjectInputStream(fis);
Person p2=(Person)[Link]();
[Link]([Link]+" "+[Link]+" "+[Link]+" "+[Link]);
}
} //30 ABC 30 ABC
Serialization
import [Link].*;
class Person implements Serializable{
transient final int age=30;
transient String name="ABC";
}
class SerializeTest{
static public void main(String[] args) throws Exception{
Person p1=new Person();
//serialization
FileOutputStream fos=new FileOutputStream("[Link]");
ObjectOutputStream oos=new ObjectOutputStream(fos);
[Link](p1);

//Deserialization
FileInputStream fis=new FileInputStream("[Link]");
ObjectInputStream ois=new ObjectInputStream(fis);
Person p2=(Person)[Link]();

[Link]([Link]+" "+[Link]+" "+[Link]+" "+[Link]);


}
} // output: 30 ABC 30 null
Reflection API
➢ Reflection is commonly used by programs which require the ability to examine or modify the
runtime behavior of applications running in the Java virtual machine

➢ The ability of a computer program to examine and modify the structure and behavior of program at
run time

➢ This is a relatively advanced feature and should be used only by developers who have a strong
grasp of the fundamentals of the language

➢ With that caveat in mind, reflection is a powerful technique and can enable applications to perform
operations which would otherwise be impossible

Reflection API is used to


o Inspect class and method modifiers
- private, public, final and abstract
o Inspect constructors, methods and their parameters
o Get and Set private data
o Invoke public / private methods

➢ [Link].* - need to be imported for reflection API


Reflection API

• Every object is either a reference or primitive type


• Reference types all inherit from [Link]
• Classes, enums, arrays, and interfaces are all reference types.
• Examples of reference types include [Link], [Link],
[Link], [Link]
• There is a fixed set of primitive types: boolean, byte, short, int, long, char, float, and
double.

• For every type of object, the Java Virtual Machine instantiates an immutable
instance of [Link] which provides methods to examine the runtime
properties of the object including its members and type information.

• Class also provides the ability to create new classes and objects.
• Most importantly, it is the entry point for all of the Reflection APIs.
Reflection API
Simple example to read methods and their parameter types

import [Link];
public class ReflectionDemo {
public static void main(String[] args) {
Class c="foo".getClass();
[Link]([Link]());
Method[] strMethods=[Link]();
for(Method m:strMethods) {
[Link]("Look at method:"+[Link]());
Class<?> parameterType[]=[Link]();
for(int i=0;i<[Link];i++)
[Link]("Parameter "+(i+1)+" parameter type :"+parameterType[i].getName());
}
}
}
getBytes
Class “Object” : getClass() getBytes
getBytes
Output: getBytes
FQN of getChars
class:[Link] getChars
import [Link]; equals indexOfSupplementary
import [Link]; toString intern
hashCode isEmpty
join
compareTo join
public class ObjectTest { compareTo lastIndexOf
public static void main(String[] args) { indexOf lastIndexOf
indexOf lastIndexOf
int count=0; indexOf lastIndexOf
Object o=new String("CDAC Hyderabad"); indexOf lastIndexOf
lastIndexOf
Class c=[Link](); indexOf lastIndexOfSupplementary
indexOf length
[Link]("FQN of class:"+[Link]()); valueOf matches
Method[] m=[Link](); //reflection valueOf nonSyncContentEquals
valueOf offsetByCodePoints
Field[] f=[Link](); // reflection regionMatches
valueOf
for(Method m1:m){ regionMatches
valueOf replace
count++; valueOf replace
valueOf replaceAll
[Link]([Link]()); valueOf replaceFirst
} valueOf split
charAt split
[Link]("No of methods:"+count); startsWith
checkBounds startsWith
[Link]("................"); codePointAt subSequence
for(Field f1:f){ codePointBefore substring
codePointCount substring
count++; toCharArray
compareToIgnoreCase
[Link]([Link]()); concat toLowerCase
toLowerCase
} contains toUpperCase
contentEquals toUpperCase
} contentEquals trim
} copyValueOf No of methods:77
copyValueOf ................
endsWith value
hash
equalsIgnoreCase serialVersionUID
format serialPersistentFields
format CASE_INSENSITIVE_ORDER
Reflection API
Private Data
public final class TestClass {
private int tid=55;
private String tstr="This is confidential! ";

public int getId(){


return tid;
}
private String getStr(String str){
return str;
}

public static void main(String[] args) {


TestClass tc=new TestClass();
Class c1=[Link]();
Field[] fields=[Link]();
for(Field f:fields)
[Link]([Link]()+" "+[Link]([Link]()));
}

}
o/p:
tid private
tstr private
Reflection API
Accessing Private Data
import [Link];
import [Link];

public final class TestClass {


private int tid=55;
private String tstr="This is confidential! ";
public int getId(){
return tid;
}
private String getStr(String str){
return str;
}
public static void main(String[] args) throws Exception{
TestClass tc=new TestClass();
Class c1=[Link]();
Field[] fields=[Link]();
for(Field f:fields)
[Link]([Link]()+" "+[Link]([Link]()));

Field str=[Link]("tstr");
[Link](true);
String whatsintstr=(String)[Link](tc);
[Link]("Information hiding in tstr is:"+whatsintstr);
}
}

* Private methods too can be invoked in the same way!!


Annotations
➢ Annotations, a form of metadata, provide data about a program that is not part of the
program itself.
➢ Annotations have no direct effect on the operation of the code they annotate.
➢ Annotations have a number of uses :
✓ Information for the compiler — Annotations can be used by the compiler to detect errors or suppress warnings.
✓ Compile-time and deployment-time processing — Software tools can process annotation information to
generate code, XML files, and so forth.
✓ Runtime processing — Some annotations are available to be examined at runtime.

➢ In its simplest form, an annotation looks like : @Entity


➢ The at sign character (@) indicates to the compiler that what follows is an annotation.

Predefined Annotation Types


➢ A set of annotation types are predefined in the Java SE API.
➢ Some annotation types are used by the Java compiler, and some apply to other
annotations.
➢ The predefined annotation types defined in [Link] are
➢ @Deprecated
➢ @Override
➢ @SuppressWarnings.
Annotations
➢ @Deprecated annotation indicates that the marked element is deprecated and should
no longer be used.
➢ The compiler generates a warning whenever a program uses a method, class, or field
with the @Deprecated annotation
➢ Example:
@Deprecated static void deprecatedMethod() {
//code goes here…
}
➢ @Override annotation informs the compiler that the element is meant to override an
element declared in a superclass.
➢ Example:
@Override int overriddenMethod() {
}
➢ While it is not required to use this annotation when overriding a method, it helps to
prevent errors.
➢ If a method marked with @Override fails to correctly override a method in one of its
super classes, the compiler generates an error.
Annotations
➢ @SuppressWarnings annotation tells the compiler to suppress specific warnings that it would
otherwise generate.
➢ In the following example, a deprecated method is used, and the compiler usually generates a warning.
In this case, however, the annotation causes the warning to be suppressed.
// use a deprecated method and tell
// compiler not to generate a warning
@SuppressWarnings("deprecation") void useDeprecatedMethod() {
// deprecation warning
// - suppressed [Link](); }

➢ Every compiler warning belongs to a category. The Java Language Specification lists two categories:
deprecation and unchecked.
➢ The unchecked warning can occur when interfacing with legacy code written before the advent
of generics.
➢ To suppress multiple categories of warnings, use the following syntax:
@SuppressWarnings({"unchecked", "deprecation"})

➢ @FunctionalInterface annotation, introduced in Java SE 8, indicates that the type declaration is


intended to be a functional interface, as defined by the Java Language Specification

➢ @SafeVarargs annotation, when applied to a method or constructor, asserts that the code does not
perform potentially unsafe operations on its varargs parameter
➢ When this annotation type is used, unchecked warnings relating to varargs usage are suppressed.
Annotations
Annotations That Apply to Other Annotations:
➢Annotations that apply to other annotations are called meta-annotations. There are several meta-annotation types defined
in [Link].
➢@Retention annotation specifies how the marked annotation is stored:
✓ [Link] – The marked annotation is retained only in the source level and is ignored by the compiler.
✓ [Link] – The marked annotation is retained by the compiler at compile time, but is ignored by the Java Virtual Machine
(JVM).
✓ [Link] – The marked annotation is retained by the JVM so it can be used by the runtime environment.

➢@Documented annotation indicates that whenever the specified annotation is used those elements should be
documented using the Javadoc tool. (By default, annotations are not included in Javadoc.)

➢@Target annotation marks another annotation to restrict what kind of Java elements the annotation can be applied to.
A target annotation specifies one of the following element types as its value:
– ElementType.ANNOTATION_TYPE can be applied to an annotation type.
– [Link] can be applied to a constructor.
– [Link] can be applied to a field or property.
– ElementType.LOCAL_VARIABLE can be applied to a local variable.
– [Link] can be applied to a method-level annotation.
– [Link] can be applied to a package declaration.
– [Link] can be applied to the parameters of a method.
– [Link] can be applied to any element of a class.

➢@Inherited annotation indicates that the annotation type can be inherited from the super class. When the user queries the
annotation type and the class has no annotation for this type, the class' superclass is queried for the annotation type. This
annotation applies only to class declarations.

➢@Repeatable annotation, introduced in Java SE 8, indicates that the marked annotation can be applied more than once to
the same declaration or type use.
Network Programming
Basic client – server program

[Link]
import [Link].*;
import [Link].*;

public class MyClient {

public static void main(String[] args) throws IOException{


Socket sock=new Socket("localhost",6666);

//ObjectOutputStream out=new ObjectOutputStream([Link]());


//[Link]("Hello Server");

PrintWriter out=new PrintWriter([Link]());


[Link](“Hello Server");
[Link]();

[Link]();
[Link]();
}
}
[Link]

import [Link].*;
import [Link].*;

public class MyServer{


public static void main(String[] args) throws IOException{
ServerSocket sos=new ServerSocket(6666);
[Link]("Listening on port....6666!");
Socket sock=[Link]();
[Link]("Client Connected!");

//ObjectInputStream ois=new ObjectInputStream([Link]());


//String str=(String)[Link]();

BufferedReader br=new BufferedReader(new InputStreamReader([Link]()));


String str=(String)[Link]();
[Link]("Client Says="+str);

[Link]();
[Link]();

}
}
Client – Server, two-way communication

[Link]
import [Link].*;
import [Link].*;

public class MyClient {

public static void main(String[] args) throws IOException{


Socket sock=new Socket("localhost",6666);
//ObjectOutputStream out=new ObjectOutputStream([Link]());
//[Link]("Hello Server");

PrintWriter out=new PrintWriter([Link]());


[Link]("Are you getting my message...?");
[Link]();

BufferedReader br=new BufferedReader(new InputStreamReader([Link]()));

String str=(String)[Link]();
[Link]("Server Says="+str);
[Link]();
[Link]();
}
}
[Link]
import [Link].*;
import [Link].*;

public class MyServer{


public static void main(String[] args) throws IOException{
ServerSocket sos=new ServerSocket(6666);
[Link]("Listening on port....6666!");
Socket sock=[Link]();
[Link]("Client Connected!");

//ObjectInputStream ois=new ObjectInputStream([Link]());


//String str=(String)[Link]();

BufferedReader br=new BufferedReader(new InputStreamReader([Link]()));


String str=(String)[Link]();
[Link]("Client Says="+str);

PrintWriter out=new PrintWriter([Link]());


[Link]("Yes...I am !");
[Link]();

[Link]();
[Link]();

}
}

You might also like