0% found this document useful (0 votes)
18 views39 pages

Try With Resources

The document provides an overview of Object Oriented Programming with Java, focusing on features such as try-with-resources, annotations, the Java Module System, and the diamond operator. It explains the syntax and usage of try-with-resources for resource management, various categories of annotations, and the benefits of the Java Module System introduced in Java 9. Additionally, it discusses the diamond operator's role in simplifying generics in Java, particularly with anonymous inner classes in JDK 9.

Uploaded by

shrey16211
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)
18 views39 pages

Try With Resources

The document provides an overview of Object Oriented Programming with Java, focusing on features such as try-with-resources, annotations, the Java Module System, and the diamond operator. It explains the syntax and usage of try-with-resources for resource management, various categories of annotations, and the benefits of the Java Module System introduced in Java 9. Additionally, it discusses the diamond operator's role in simplifying generics in Java, particularly with anonymous inner classes in JDK 9.

Uploaded by

shrey16211
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
You are on page 1/ 39

Object Oriented Programming with Java

(BCS-403)

Prepared By
Sachin Kumar Sonker
Assistant Professor,UCER Naini,Allahabad
The try-with-resources
 Try-with-resources statement is a try statement that
declares one or more resources in it.
 Java introduced try-with-resource feature in Java 7.
 Resource:
A resource is an object that must be closed once
your program is done using it
example, a File resource or a Socket connection
resource.
 ensures that each resource is closed at the end of
the statement execution.
 Any object can be pass as a resource that implements
java.lang.AutoCloseable
The try-with-resources
 don’t need to add an extra finally block for just
passing the closing statements of the resources.

 Syntax: Try-with-resources

try(declare resources here) {


// use resources
}
catch(FileNotFoundException e) {
// exception handling
}
The try-with-resources
 Example: try-with-resources having a single
resource
import java.io.*;
class TWR {
// Main driver method
public static void main(String[] args)
{
// Try block to check for exceptions
try (FileOutputStream fos= new
FileOutputStream(“firsttextfile.txt"))
{
String text= "Hello World. This is my java program";
byte arr[] = text.getBytes();
fos.write(arr);
}
The try-with-resources
// Catch block to handle exceptions
catch (Exception e) {
System.out.println(e);
}
System.out.println ("Resource are closed
and message has been written
into the firsttextfile.txt");
}
}
Output: Resource are closed and message has been
written into the firsttextfile.txt
System.out.println(

Example 2: try-with-resources having multiple


}
"File content copied to another one.");

resources
import java.io.*;

class TWR {
public static void main(String[] args)
{
try (FileOutputStream fos = new
FileOutputStream("outputfile.txt");
BufferedReader br = new
BufferedReader(newFileReader(“firsttextfile.txt"))) {
String text;
while ((text = br.readLine()) != null) {
byte arr[] = text.getBytes();
fos.write(arr);
}
catch (Exception e) {
System.out.println(e);
}
System.out.println( "Resource are closed and
message has been written into the firsttextfile.txt");
}
}

Output: File content copied to another one.


Resource are closed and message has been written into the
firsttextfile.txt
Type Annotations
 Annotations: Annotation is a tag that represents
the metadata i.e. attached with class, interface,
methods or fields to indicate some additional
information which can be used by java compiler
and JVM.
 Annotations start with ‘@’.
 Annotations are not pure comments as they can
change the way a program is treated by the
compiler.
 Annotations do not change the action of a
compiled program.
Categories of Annotations

There are broadly 5 categories of annotations as listed:


 Marker Annotations
 Single value Annotations
 Full Annotations
 Type Annotations
 Repeating Annotations
Category 1: Marker Annotations

 The only purpose is to mark a declaration. These


annotations contain no members and do not consist of any
data. Thus, its presence as an annotation is sufficient.
Since the marker interface contains no members, simply
determining whether it is present or absent is
sufficient. @Override is an example of Marker
Annotation.
Example
 @TestAnnotation()
Category 2: Single value Annotations

 These annotations contain only one member and allow a


shorthand form of specifying the value of the member. We
only need to specify the value for that member when the
annotation is applied and don’t need to specify the name
of the member. However, in order to use this shorthand,
the name of the member must be a value.

Example
 @TestAnnotation(“testing”);
Category 3: Full Annotations

 These annotations consist of multiple data


members, names, values, pairs.

Example
 @TestAnnotation(owner=”Rahul”, value=”Class
Geeks”)
Category 4: Type Annotations

 These annotations can be applied to any place where a


type is being used. For example, we can annotate the
return type of a method. These are declared annotated
with @Target annotation.
Type Annotations
 Java 8 has included a new feature type
annotations
 early Java versions, you can apply annotations
only to declarations.
 After releasing of Java SE 8 , annotations can be
applied to any type use
 means that annotations can be used anywhere
you use a type.
 Java created type annotations to support
improved analysis of Java programs. It supports
way of ensuring stronger type checking.
Type Annotations
 Example:
import java.lang.annotation.ElementType;
import java.lang.annotation.Target;

// Using target annotation to annotate a


type
@Target(ElementType.TYPE_USE)

// Declaring a simple type annotation


@interface TypeAnnoDemo{}
public class Test {
public static void main(String[] args) {

// Annotating the type of a string


@TypeAnnoDemo String string = "I am
annotated with a type annotation";
System.out.println(string);
abc();
}
// Annotating return type of a function
static @TypeAnnoDemo int abc() {

System.out.println("This function's return


type is annotated");
return 0;
}
}

Output:
I am annotated with a type annotation
This function's return type is annotated
Category 5: Repeating Annotations

 These are the annotations that can be applied to a single


item more than once. For an annotation to be repeatable
it must be annotated with the @Repeatable annotation,
which is defined in the java.lang.annotation package. Its
value field specifies the container type for the
repeatable annotation. The container is specified as an
annotation whose value field is an array of the
repeatable annotation type. Hence, to create a
repeatable annotation, firstly the container annotation is
created, and then the annotation type is specified as an
argument to the @Repeatable annotation.
Repeating Annotations
 Java allows you to repeating annotations in your
source code.
 helpful when you want to reuse annotation for the
same class.
 defined in the java.lang.annotation package.
 can repeat an annotation anywhere that you would
use a standard annotation.
 For compatibility reasons, repeating annotations
are stored in a container annotation that is
automatically generated by the Java compiler.
 two declarations are required in your code.

1. Declare a repeatable annotation type


2. Declare the containing annotation type
Declaring a repeatable annotation type
 Declaring of repeatable annotation type must be
marked with the @Repeatable meta-annotation.
 Example:
@Repeatable(Games.class)
@interfaceGame{
String name();
String day();
}
 value of the @Repeatable meta-annotation, in
parentheses, is the type of the container
annotation that the Java compiler generates to
store repeating annotations.
2)Declare the containing annotation
type
 Containing annotation type must have a value
element with an array type.
 component type of the array type must be the
repeatable annotation type
 Example:
@interfaceGames{
Game[] value();
}
Note - Compiler will throw a compile-time error, if
you apply the same annotation to a declaration
without first declaring it as repeatable.
Java Repeating Annotations Example
// Importing required packages for repeating
annotation
import java.lang.annotation.Repeatable;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
// Declaring repeatable annotation type
@Repeatable(Games.class)
@interfaceGame{
String name();
String day();
}
// Declaring container for repeatable annotation type
@Retention(RetentionPolicy.RUNTIME)
@interfaceGames{
Game[] value();
}
// Repeating annotation
@Game(name = "Cricket", day = "Sunday")
@Game(name = "Hockey", day = "Friday")
@Game(name = "Football", day = "Saturday")
public class RepeatingAnnotationsExample {
public static void main(String[] args) {
// Getting annotation by type into an array
Game[] game = RepeatingAnnotationsExample.class.
getAnnotationsByType(Game.class);
for (Gamegame2 : game) { // Iterating values
System.out.println(game2.name()+" on "+
game2.day());
}
}
}
OUTPUT:
Cricket on Sunday
Hockey on Friday
Football on Saturday
Java Module System
 Java Platform Module System is a new feature
which is introduced in Java 9.
 Java added this feature to collect Java
packages and code into a single unit
called module.
 By the help of the Java module, we can specify
which of the packages of the module should be
visible to other Java modules.
 In earlier versions of Java, there was no
concept of module to create modular Java
applications, that why size of application
increased and difficult to move around.
 Java 9 restructured JDK into set of modules so
that we can use only required module for our
project.
 Java also allows us to create our own modules
so that we can develop module based
application.
 Module is a collection of Java programs or
softwares. To describe a module, a Java
file module-info.java is required.
Java Module System
 module-info.java also known as module
descriptor and defines the following:
 Module name
 What does it export
 What does it require
Creating Java module
 Creating Java module required the following steps.
 Create a directory structure
 Create a module declarator
 Java source code
Create a Directory Structure
Create a file module-info.java, inside this file,
declare a module by using module identifier and
provide module name same as the directory name
that contains it.

module com.Javatut{
}
.
 Leave module body empty, if it does not has
any module dependency. Save this file
inside src/com.javatut with module-
info.java name.
 Java Source Code
 Now, create a Java file to compile and execute
module. In our example, we have a Hello.java file
that contains the following code.
class Hello{
public static void main(String[] args){
System.out.println("Hello from the Java module");
}
}

 Save this file


inside src/com.javatut/com/javatut/ with Hello.java nam
e.
Compile Java Module
 To compile the module use the following command.
 javac -d mods --module-source-path src/ --
module com.javatut
To Run Module
 To run the compiled module, use the following
command.
 java--module-path mods/ --module
com.javatut/com.javatut.Hello

 Output:
 Hello from the Java module
Diamond Operator
What is a diamond operator?
 Diamond operator was introduced as a new feature
in java SE 7. The purpose of diamond operator is to
avoid redundant code by leaving the generic type
in the right side of the expression.
 main purpose of the diamond operator is to
simplify the use of generics when creating an
object.
 avoids unchecked warnings in a program and makes
the program more readable.
Diamond Operator
 diamond operator could not be used with
Anonymous inner classes in JDK 7.
 In JDK 9, it can be used with the anonymous
class as well to simplify code and improves
readability.
 Example:
 List<String> c = new ArrayList<>();
Problem with the diamond operator while
working with Anonymous Inner classes
 Java 7 allowed us to use diamond operator in normal
classes but it didn’t allow us to use them in
anonymous inner classes. Lets take an example:

abstract class MyClass<T>{


abstract T add(T num, T num2);
}
public class JavaExample {
public static void main(String[] args) {
MyClass<Integer> obj = new MyClass<>() {
Output:

$javac JavaExample.java
JavaExample.java:7: error: cannot infer type
arguments for MyClass
MyClass obj = new MyClass<>() {
reason: cannot use '<>' with anonymous inner classe
where T is a type-variable:
T extends Object declared in class MyClass
 Java developer extended the feature of the
diamond operator in JDK 9 by allowing the
diamond operator to be used with anonymous
inner classes too.
 If we run the above code with JDK 9, then
code will run fine and we will generate the
below output.
Output:
201

You might also like