Java Notes (SpringBoot Course)
Java Notes (SpringBoot Course)
Session 1:
Learning Objectives
➢ Introduction to Java
➢ 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
• The other levels were created to make it easier for a human being
to write programs
Programming Languages
● Machine language
C → C++ → Java
Before Java: C
Designed by Dennis Ritchie in 1972.
Before C:
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
The team was expanded to include Bill Joy (developer of Unix), Arthur
van Hoff, Jonathan Payne, Frank Yellin, Tim Lindholm etc.
❖ 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.
Java .class
.java file Compiler file
• No Global Variables
• No goto statements
• No Multiple Inheritance
• No Operator Overloading
• No Templates
Added or Improved over C++
• Interfaces
• Strings
• Packages
• Multi-threading
• instanceof
Types of Java Applications
• Different ways to write/run a Java codes are:
class body
}
Comments
• On command line
java classname
Bytecode
➢new operator
➢Constructors
➢ Overloading
Session 2:
Learning Objectives
By the end of this session, you must be able to
➢Arrays in Java
Identifiers:
float 4 - - 1.0
double 8 - - 123.86
• Assignment Operator
Operator Description Example
• Arithmetic Operators
% 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;
• Equality 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
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 %
• 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
If – then:
if (isMoving){
// the "then" clause: decrease current speed
currentSpeed--;
}
Flow Control – if-else
Syntax Example
* 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 }//
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
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.
• 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
variable_name=new <type>[N];
primes=new int[10];
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
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
• Two-Dimensional 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} };
//Three arrays
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
● Programming languages
o Examples: C, C++, Java,etc.,
Polymorphism
What is an Object?
• 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
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
1) Manual – in C/C++
2) Automatic – in Java
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
➢ Garbage Collection
this keyword
• this is a reference variable that refers to the current object
• Call to this() must be always first
Usage:
– 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);
}
}
[Link]
The Java Platform – JDK / Java SE
Java Development Kit
• The following figure shows a block diagram of the JVM that includes its
major subsystems and memory areas.
• 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
• For each type it loads, the JVM must store the following
information in the method area:
• 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
• 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
• allocate memory;
• assign fields their default values;
• run the constructor;
• a reference is returned.
How Java Reclaims Objects Memory
– Easier programming
– Reference counting
– Mark-and-sweep
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
• 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
– 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.
• 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
Inheritance
Session 4:
Learning Objectives
➢ Describe Inheritance
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 Components
• Information Hiding
The Costs of Inheritance
• Execution Speed
• Program Size
• Message-Passing Overhead
[Link]
1. Final variable can not be changed
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?
• It increases encapsulation
class OuterClass {
...
class InnerClass {
...
}
}
– Such as
– [Link] and
– ClassName$[Link]
[Link]
[Link]
Local Class
• A class that is
created inside a
method
[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 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
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
➢Describe Interfaces
• We can declare a class as abstract, even if the class does not have any abstract
methods
• 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.
• 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:
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");
}
}
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 {
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]();
}
}
package cdac;
Public class R {
public void fun(){
[Link](" Hello, i am from cdac package");
}
// javac -d . [Link]
// java cdac.R
Example 3 :[Link]
package [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
}
}
• 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
• 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
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
• 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
native no no yes no no no no 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:
➢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.
Exception Handling
Session 6:
Learning Objectives
295
What is Exception Handling?
296
division by zero
class DivisionByZeroHandled
{
int c;
29-Mar-22
297
Handling Exceptions - Java
Format:
try
{
// Code that may cause an error/exception to occur
}
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);
}
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
}
class Integer
{
public Integer (int value);
public Integer (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 =
try }
{
num = [Link] (s);
}
:
catch (NumberFormatException e)
{
:
}
305
Handling Exceptions: Tracing The Example
[Link] (String s)
{
NumberFormatException e =
try }
{
num = [Link] (s);
}
:
catch (NumberFormatException e)
{
:
}
306
Handling Exceptions: Tracing The Example
[Link] (String s)
{
main ()
try }
{
num = [Link] (s);
}
:
catch (NumberFormatException e)
{
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"
}
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
• 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
arr[i-1] = arr[i-1] / 0;
29-Mar-22
318
Common Unchecked Exceptions: ArrayIndexOutOfBoundsException
29-Mar-22
319
Common Unchecked Exceptions: ArithmeticExceptions
arr[i-1] = arr[i-1] / 0;
ArithmeticException
(Division by zero)
29-Mar-22
320
Keywords – Exception Handling in Java
[Link]
[Link]
[Link]
[Link]
[Link] ()
{
try
2) Exception thrown here
{
}
[Link]();
}
catch
{
}
[Link] ()
{
try
2) Code runs okay here
{
}
[Link]();
}
catch
{
}
finally
{
} 332
[Link]
throw
[Link]
Example -throw Statements
Output:
Caught inside demoproc.
Recaught: [Link]: demo
[Link]
[Link]
throws
Output:
Inside throwOne. [Link]
Caught [Link]: demo
[Link]
User Defined Exception
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;
if(amt>amount){
throw new NilBalanceException("Insufficient Funds to
withdraw!!");
}
}
}
Try with
resources
Note: 1.7 onwards…. try with resources is possible without catch or finally
try with resources
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
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);
Learning Objectives
➢ Explain Java IO
➢ Describe Streams
➢ Byte / Character
➢ Text /Character
Overview of I/O Streams
Program I ‘ M A S T R I N G \n Device
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:
• 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:
• These streams are typically used to read and write binary data such as
images and sounds.
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
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);
}
class Table{
}
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..."); }
} }
Learning Objectives
➢ 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 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()
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
✓ 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.
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
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)
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
4. SortedSet (Interface):
5. NavigableSet (Interface):
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):
✓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:
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
import [Link].*;
// [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) {
}
Vector Demo
import [Link].*;
[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 {
Iterator i=[Link]();
while([Link]()){
[Link]([Link]());
}
}
}
TreeSet Demo
import [Link].*;
public class TreeSetDemo {
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].*;
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);
import [Link].*;
import [Link].*;
public class IdentityHashMapDemo {
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.
•Not synchronized.
1)Type-safety :
Holds only a single type of objects in generics. It doesn’t allow to store other typed objects
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.
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
Iterator<String> itr=[Link]();
while([Link]()){
[Link]([Link]());
}
}
}
Generics
Example of Java Generics using Map
import [Link].*;
class TestGenerics2{
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.
❑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);
}
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);
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.
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].*;
//Deserialization
FileInputStream fis=new FileInputStream("[Link]");
ObjectInputStream ois=new ObjectInputStream(fis);
Person p2=(Person)[Link]();
➢ 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
• 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! ";
}
o/p:
tid private
tstr private
Reflection API
Accessing Private Data
import [Link];
import [Link];
Field str=[Link]("tstr");
[Link](true);
String whatsintstr=(String)[Link](tc);
[Link]("Information hiding in tstr is:"+whatsintstr);
}
}
➢ 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"})
➢ @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].*;
[Link]();
[Link]();
}
}
[Link]
import [Link].*;
import [Link].*;
[Link]();
[Link]();
}
}
Client – Server, two-way communication
[Link]
import [Link].*;
import [Link].*;
String str=(String)[Link]();
[Link]("Server Says="+str);
[Link]();
[Link]();
}
}
[Link]
import [Link].*;
import [Link].*;
[Link]();
[Link]();
}
}