A3-Java Unit 3

You might also like

Download as pdf
Download as pdf
You are on page 1of 19
OBJECT ORIENTED PROGRAMMING WITH JAVA HANDWRITTEN OS Packages, Import and Static Import Naming Convention For Packages Exception Handling: The Idea behind Exception, Exceptions & Errors, Types of Exception, Control Flow in Exceptions, JVM Reaction to Exceptions, Use of try, catch, finally, throw, throws in Exception Handling, In-built and User Defined Exceptions, Checked and Un-Checked Exceptions. Input /Output Basics: Byte Streams and Character Streams, Reading and Writing File in Java. Multithreading: Thread, Thread Life Cycle, Creating Threads, Thread Priorities, Synchronizing Threads, inter-thread Communication. ja New Features: Functional Interfaces, Lambda Expression, Method References, Stream API, Default Methods, Static Method, Base64 Encode and Decode, Forfach Method, Try-with- resources, Type Annotations, Repeating Annotations, Java Module System, Diamond Syntax with - tbody? list: : ) Arrow-token: It is used to link arguments-list and body of expression. Body: |t_contains expressions and statements for lambda expression. Lambda Expression - Example Let‘s understand Lambda Expression with the following code: Engineering Express ___|] @Functionalinterface //Itis optional ____]] interface Drawable{ =e) public void draw(); __|}]} —___| public class LambdaExpressionExample2 { Seat public static void main(String[] args) { —— int width=10; =i) Jiwith lambda Drawable d2=()->{ aE! System.out printin("Drawing "+width); al hk —— d2.draw(); Oiiput i Drawing 10 } | Method Referenc | Java provides a new feature called method reference in Java 8. __| Method _ reference is used to__ refer method —of functional |interface. . fonm of . - . WOME, choi method, you can replace your lambda expression with method reference. T if r Reference to an instance method. lw Reference to a constructor. Engineering Express Reference toa static method == ‘ou_can_refer to static method defined in the class. Following is the _| syntax and example which describe the process of referring static method in Java. Syntax : ContainingClass::staticMethodName Example: interface Sayable{ void say(); } public class MethodReference { public static void saySomething(){ System.out.printin("Hello, this is static method."); } public static void main(String] args) { // Referring static method Sayable sayable = MethodReference::saySomethi ng; // Calling interface method sayable.say(); } Output } Hello, this is static method. Reference to a static method i Iso. I following example, we are describing the process of referring the instance method, Syntax ; containingObject::instanceMethodName Example - Engineering Express interface Sayable{ Output void say(); Hello, this is non- static method. } Hello, this is non- static method, public class InstanceMethodReference { public void saySomething(){ System.out.printin("Hello, this is non-static method."); } public static void main(String[] args) { 11 Creating object InstanceMethodReference methodReference = new InstanceMethodRefer ence(); 1 Referring non-static method using reference Sayable sayable = methodReference::saySomething; 1] Calling interface method sayable.say(); 1 Referring non-static method using anonymous object Sayable sayable2 = new InstanceMethodReference()::saySomething; // You can use anonymous object also 1 Calling interface method sayable2.say(); Reference to a Constructor ou cae ee ee ae we are | ____|| referring constructor with the help of functional interface. | Syntax - ClassName::snew Example: interface Messageable{ Message getMessage(String msg); ee } ENGINEERING EXPRESS class Message{ Message(String msg) ‘System.out.print(msg); } public class ConstructorReference { public static void main(String[] args) { Messageable hello = Message::new; hello.getMessage("ENGINEERING EXPRESS"); } } Engineering Express default. are known as default. “meth ods “These methods are non= abstract methods. Java Default Method Example: In_the follow | i jonal_ini hi contains a default and an abstract method. The concept of default method is used to define a method with default_implementation, You can override default method also_to_provide more specific implementation for the method. interface Sayable{ /! Default method default void say(){ System.out.printin("Hello, this is default method"); } /! Abstract method void sayMore(String msg); } public class DefaultMethods implements Sayable{ public void sayMore(String msg{__// implementing abstract m ethod ‘System.out.printin(msg); } public static void main(String] args) { DefaultMethods dm = new DefaultMethods(); dm.say(); // calling default method dm.sayMore("Work is worship"); // calling abstract method } Output } Hello, this is default method Work is worship Engineering Express import java.util. Base64; public class EncryptionExample { public static void main(String] args) { 1/ Getting encoder Base64.Encoder encoder = Base64.getEncoder(); // Creating byte array byte byteArr{] = {1,2}; // encoding byte array byte byteArr2{] = encoder.encode(byteArr); System.out.printin("Encoded byte array: "+byteArr2); byte byteArr3[] = new byte[5]; J/ Make sure it has enough size to store copied bytes int x = encoder.encode(byteArr,byteArr3); _// Returns number of bytes written System.out printin("Encoded byte array written to another array: "+byteArr3); System.out.printin("Number of bytes written: "+x); // Encoding string String str = encoder.encodeToString ("Welcome To IIMT".getBytes()); System.out.printin("Encoded string: "+str); / Getting decoder Base64.Decoder decoder = Base64.getDecoder(); 1 Decoding string String dStr= new String(decoder.decode(str)); System.out.printin("Decoded string: "+dStr); ritten to another array: [BR14991ad i ASAD eli It uses the Base64 alphabet specified by Java in RFC 4648 for encoding and decoding operations, The encoder does not add any line separator character, The decoder rejects data that contains characters outside the base64 alphabet. Example: Engineering Express import java.util.Base64; public class URLEncryptionExample { public static void main(String[] args) { // Getting encoder Base64.Encoder encoder = Base64.getUriEncoder(); // Encoding URL String eStr = encoder.encodeToString("http://www.google.com”.getBytes()); System.out.printin("Encoded URL: "+eStr); // Getting decoder Base64.Decoder decoder = Base64.getUrlDecoder(); // Decoding URI String dStr = new String(decoder.decode(eStr)); System.out.printIn("Decoded URL: "+dStr); } } Output Encoded URL: alR@cDovL3d3dySnb29nbGuul29t Decoded URL: http:// google.com ~ Java forEach Method Java_provides a new method forEach() to_iterate the elements. It_is defined in Iterable and Stream interface, It is a default method in_the | le_intertc llection_cl ich ni Iterable interface can use forEach loop to iterate elements. This method takes a single parameter which is a functional interface, So, you can pass lambda expression as an argument. Syntax: default void forEach(Consumeraction) | Engineering Express ‘orEachQ)_Example 1 import java.util.ArrayList; | _____]] import java.util.List; }_ public class ForEachExample { ___| public static void main(String] args) { a Se List gamesList = new | ArrayList(); }_ gamesList.add("Football"); gamesList.add("Cricket"); gamesList.add("Chess"); gamesList.add("Hocky"); System.out.printin("------- Iterating by passing lambda expression-------");||__ gamesList.forEach(games -> System.out.printIn(games)); OUTPUT .---Iterating by passing lambda expression: Football Cricket Chess Hocky Java Annotations Java Annotation is a tag that represents the metadata_ie, attached with class, «_|linterface, methods or fields to indicate some additional information which can be used by java compiler and JVM, pt «_|| Annotations in Java are used to provide additional information, so it is an alternative option for XML and Java marker interfaces. Engineering Express ~~ There are two types of Annotations Builth : | Custom annotations —— Built-in Annotations There are several built-in annotations_in Java, Some annotations are . . Built-In Java Annotations used in Java code @Override @SuppressWamings |@Deprecated | Built-In Java Annotations used in other annotations a | @Target @Retention | @Inherited | @Documented. y, an | @Override the parent class method, If it_is not so, compile time error occurs. Sometimes, we does the silly mistake such as spelling mistakes etc. * i . - . , | that method is overridden. | Engineering Express Importjava.util."; classRect { intl,b; publicvoidGetData() { Scannert=newScanner(System.in); System.out.print("\nénterLength:”); let nextint(); System.out.print("\nEnterBreadth:"); b=t.nextint(); } publicvoidDisplay() { System.out.print("\nLength:“+1); System.outprint{“\nBreadth:"+b); Importjava.util.*; classCuboidextendsRect { inth; @Override publicvoidGetData() { super.GetData(); System.out.print(\nEnterHeight:"); h=tnextint(); } @Override publicvoidDisplay() { Super.Display(); System.out.print(“\nHeight:"+h); @Deprecated Dep . . . compiler prints warning. It informs user that it may be removed in the future versions, So, it is better not to use such methods. Engineering Express After releasing of Java SE 3 , annotations can be applied to any type use, li i Ve For example, if you want to avoid NullPointerException in your code, you _can declare a string variable like this: @NonNull_ String str; Following are the examples of type annotations: |__» @NowNull List +_List<@NonNull String> str. ae . < i > = @Encrypted File file + @Oren C ( . + void dividelntegerCint a, int b) throws @ZeroDivisor |___ ArithmeticExcept ion - - ; is of Java programs. It supports way of ensuring stronger type checking. Java Rereatinn Annotati In Java 3 release, Java allows you to use repeating annotations in your source code, It_is helpful when you want to reuse annotation for the same class. You can repeat an annotation anywhere that you would use a standard annotation. Engineering Express F ave " j . . . . 1 compiler, In_order for the compiler to do this, two declarations are required in your code : J___Declare a repeatable annotation tye 2, Declare the containing annotation type Declare a repeatable annotation type Declaring of repeatable annotation type must be marked with the | @Repentable metaannotation — |ln_the following example, we have defined_a custom @Game___ |repeatable annotation type. @Repeatable(Games.class) @interfaceGamet AX _ || String nameQ; ap String dayO; The value of the @Repeatable meta-annotation, in parentheses, is the type of the container annotation that the Java compiler generates to store repeating annotations. In the following example, the containing in_an @Games annotation. 2) Declare the containing annotation type Containing annotation type must have a value element with an array type. The component type of the array type must be the repeatable annotation type. Engineering Express 1 j j abstractclassPerson { abstractvoideat(); t classTestAnonymousInner { publicstaticvoidmain(Stringargs[]) { Personp=newPerson(}{ voideat(){System.out.printin("nicefruits");} ik p.eat(); } } ____Internal_working of given code Person p=new Personi){ void eat(){System.out.printIn("nice fruits");} hb A_class is created, but its name is decided by the-compiler, which Lextends the Person class and provides the implementation of the | |eatC)_ method. |An object of the Anonymous class is created that is. refered to by 'p, | a reference variable of Person type. Intemal class generated by the compiler ___| import java.io.PrintStream; static class TestAnonymousInner$11 extends Person { TestAnonymousinner$1(){} void eat() { System.out.printin("nice fruits"); } } Engineering Express program and makes the program more readable, The diamond operator could not be used with Anonymous inner classes in JDK 7. ! aj " simplify code and improves readability. Before JDK 7, we have to create an object with Generic type on both side of the expression like: // Here we mentioned the generic type // on both side of expression while creating object List geeks = new ArrayList(); List geeks = new ArrayList<>(); Engineering Express Di f Di ; Lmentioning th | generic type on the right hand side of the expression. But the _| problem is it will only work with normal classes. Suppose you want to use the diamond operator for anonymous inner class in jdk 7 then ler will throw. error il is = abstract class Sample { abstract T add(T num1, T num2); } public class DiamondDemo{ public static void main(String[] args) { Sample obj= new Sample<>() { Integer add(Integer n1, Integer n2) { return (n1 +n2); } i Integer result = obj.add(10, 20); System.out.printIn("Addition of two numbers: " + result); } } Output in IDK 7: prog.java:9: error: cannot infer type arguments for Sample Sample obj = new Sample() { A reason: cannot use " with anonymous inner classes where T is a type-variable: T extends Object declared in class Sample error Engineering Express Output in jdk % Addition of two numbers: 30 Yield Keyword. The yield keyword is used_to exit from a switch expression by returning a value that_becomes the value of the switch expression. This_means we can assign the value of a switch expression toa | variable. Lastly, by using yield in a switch expression, we get an implicit check_| | that _we’re covering our cases, which makes our_code more robust. |The yield keyword can_be used in two ways = L_yield with Awow Operator = Ae 2. yield with Colon Delimiter ee an . String message = switch (n%2) {case 0 -> { yield “Even Number"; } case 1->{ yield “Odd Number"; } fault -> {yield “hi"; } hb | | Engineering Express © yield with Colon Operator - Example ____||| String message = switch (n%2) { u [aah case 0: tT yield “Even Number"; case 1: el yield “Odd Number"; a | default : i yield “hi";

You might also like