Concepts to Know Java
Concepts to Know Java
This article shows you a few ways to generate the serialVersionUID for
serialization class.
For Eclipse IDE, move the mouse over the serialization class, or click on
the serialization class and press CTRL + 1.
Puts serialVersionUID=1L; It should be sufficient in most cases.
private static final long serialVersionUID = 1L;
To make a request to run the garbage collector, you can call one of the
following methods:
System.gc()
Runtime.getRuntime().gc()
}
}
Even though o2 is created to refer to null, the object String(string) is not
recyclable since o1 refers to it.
The subclass overrides the method finalize()to free itself from system
resources or for another cleanup:
protected void finalize() throws Throwable
6.Strings in Java
Java Strings
Mutable and Immutable String
String Class Methods
Command Line Arguments
7. Java Keywords
Static Variable and Object
Static Method in Java
super Keyword in Java
Java this Keyword
Java final Keyword
8. Packages in Java
Java Packages
Creation of Packages
Access Specifier
9. Exception Handling
Java Exception Handling
Try Catch Block in Java
NumberFormatException, NullPointerException and
IndexOutofBoundsException
throw Keyword in Java
Single try and Multiple Catch
Multiple try and multiple Catch
Finally Block in Java
throws Keyword in Java
0. Java Arrays
Arrays in Java
Exception in Array
For-each Array
Anonymous Array
Variable Arguments
11. Multithreading
Multithreading in Java
Life cycle of thread
Methods of thread class
Constructor of thread class
Main as a thread
Creation of thread
Priority thread
Daemon thread
Synchronization
Runnable Interface
Wait notify and notifyall methods
12. Wrapper Classes
Java Wrapper Class
Parsing in Java
Boxing and Unboxing in Java
Character Class in Java
13. Generics in Java
Generic Classes in Java
Generic Methods in Java
Bounded Generics in Java
14. Java Collections
Collections in Java
Collection Hierarchy
Collection Methods
Methods of List Interface
Array List in Java
Linked List in Java
Vector Class in Java
Stack in Java
Set Interface in Java
Tree Set in Collection
Cursors in Java
Maps in Java
Map Interface Methods
15. Java Input/Output
I/O in Java
File Handling in Java
File Streams
Serialization in Java
Deserialization in Java
Serialization with Inheritance
Character Stream in Java
How to design console base login application
16. Java Swing
Introduction to Java Swing
GUI application in Java Swing
Login Application in Swing using NetBeans
17. New Java Concepts
Java features added after Java 8
Lambda expression in Multithreading
Lambda Expression and Functional Interface
Method Reference
Method Reference in Multithreading
Anonymous Class in Java
Predefined Functional Interface
Types of Annotation in Java
Types of Interface in Java
Sealed Classes and Interfaces
Record Class
Text Blocks
18. Projects
GUI Calculator in Java
Car Moving Application
Note Pad in Java
Tic-Tac-Toe Game in Java
Java Banking Management System
Billing System Application in Java
String allocation, like all object allocation, proves to be a costly affair in both the cases of
time and memory. The JVM performs some steps while initializing string literals to
increase performance and decrease memory overhead. To decrease the number of String
objects created in the JVM, the String class keeps a pool of strings.
Each time a string literal is created, the JVM checks the string literal pool first. If the
string already exists in the string pool, a reference to the pooled instance returns. If the
string does not exist in the pool, a new String object initializes and is placed in the pool.
Strings CheatSheet:
Creating a String
String in Java is an object that represents a sequence of
char values. A String can be created in two ways:
1. Using a literal
System.out.println(str1 == str2);
System.out.println(str1 == "abc");
String Conversions
Important Programs
This program tells you how to trim trailing spaces from the
string but not leading spaces.
int len = str.length();
for( ; len > 0; len--)
{
if( ! Character.isWhitespace( str.charAt( len - 1)))
break;
}
return str.substring( 0, len);
StringJoiner Class
StringJoiner mystring = new StringJoiner("-");
// Passing Hyphen(-) as delimiter
mystring.add("edureka");
// Joining multiple strings by using add() method
mystring.add("YouTube");
String reverse using Recursion
class StringReverse
{
/* Function to print reverse of the passed string */
void reverse(String str)
{
if ((str==null)||(str.length() <= 1))
System.out.println(str);
else
{
System.out.print(str.charAt(str.length()-1));
reverse(str.substring(0,str.length()-1));
}
}
/* Driver program to test above function */
public static void main(String[] args){
String str = "Edureka for Java";
StringReverse obj = new StringReverse();
obj.reverse(str);
}
}
String Methods
Few of the most important and frequently used String
methods are listed below:
str1==str2 //compares address;
String newStr = str1.equals(str2); //compares the values
String newStr = str1.equalsIgnoreCase() //compares the values
ignoring the case
newStr = str1.length() //calculates length
newStr = str1.charAt(i) //extract i'th character
newStr = str1.toUpperCase() //returns string in ALL CAPS
newStr = str1.toLowerCase() //returns string in ALL LOWERCASE
newStr = str1.replace(oldVal, newVal) //search and replace
newStr = str1.trim() //trims surrounding whitespace
newStr = str1.contains("value"); //check for the values
newStr = str1.toCharArray(); // convert String to character type
array
newStr = str1.IsEmpty(); //Check for empty String
newStr = str1.endsWith(); //Checks if string ends with the given
suffix
Immutable Strings
String s="JavaStrings";
s.concat(" CheatSheet");
System.out.println(s);
}
}
Method Description
getFields() Returns all the public fields (both for
class & superclass).
getDeclaredFields() Retrieves all the fields of the class.
getModifier() Returns integer representation of
access modifier of the field.
set(classObject, value) Assigns the specified value to the field.
field1.set(s1,"test");
get(classObject) Retrieves field value. (String) field1.get(s1)
setAccessible(boolean) Make private field accessible by
passing true.
getField("fieldName") Returns the field (public) with a
specified field name.
getDeclaredField("field Returns the field with a specified name.
Name")
getType MyFirstClass2.getClass().getDeclaredField("x
").getType() Return Public
Class The getClass() method is used to get the
name of the class to which an object
belongs.
Constructors The getConstructors() method is used to
get the public constructors of the class to
which an object belongs.
Methods The getMethods() method is used to get
the public methods of the class to which
an object belongs.
Reflection: Method
Method Description
getMethods() Retrieves all public methods
defined in the class and its
superclass.
getDeclaredMethod() Returns methods declared in
the class.
getName() Returns the method names.
getModifiers() Returns integer representation
of method’s access modifier.
getReturnType() Returns the method return
type.
Reflection: Constructor
Method Description
getConstructors() Returns all the constructors
declared in class and its
superclass.
getDeclaredConstructor() Returns all the declared
constructors.
getName() Retrieves the name of the
constructor.
getModifiers() Returns the integer
representation of access
modifier of constructors.
getParameterCount() Returns the total number of
parameters for a constructors.
import java.lang.reflect.Constructor->
s1.getClass().getDeclaredConstructors();
System.out.println("MyFirstClass2-get "+MyFirstClass6.getName());
for(Method x : MyFirstClass6.getDeclaredMethods())
System.out.println("MyFirstClass6-get "+x);
Method.invoke example
try {
MyFirstClass MyFirstClass101 = new MyFirstClass();
Method printMessage = MyFirstClass101.getClass().getDeclaredMethod("PrintHello",
String.class, int.class);
printMessage.invoke(MyFirstClass101, "Hello",6);}
catch (InvocationTargetException e)
{
System.out.println(e.getCause());
}
public void PrintHello(String str,int a)
{
System.out.println("string showed:"+str +" value :"+ a);
}
Output :
string showed:Hello value :6
…
MyFirstClass MyFirstClass1 = new MyFirstClass(4,5,6);//This is good method used in EMS
Field field101 = MyFirstClass1.getClass().getDeclaredField("x");
drawbacks of Reflection:
Performance Overhead: Though reflection is a powerful feature,
reflective operations still have slower performance than non-
reflective operations. Hence we should avoid using reflections in
performance-critical applications.
Security Restrictions: As reflection is a runtime feature, it might
require run-time permissions. So for the applications that require the
code to be executed in a restricted security setting, then reflection
may be of no use.
Exposure of Internals: By using reflection, we can access private
fields and methods in a class. Thus reflection breaks abstraction that
might render code unportable and dysfunctional.
https://medium.com/@AlexanderObregon/javas-class-forname-method-explained-
8e9f359f1195
class User {
@Override
public String toString() {
}
}
In the code above, we're creating a User class which Overrides the
toString Object Method. We are able to make it much more clear by
adding the @Override Annotation.
In the Main class, we're creating an Instance of User, but we're not using
it. In Oder to bypass the IDE's warnings about unused instance, we're
using the @SuppressWarnings annotation. We're also passing it a String
value unused which makes it clear that we want to ignore the fact that
the Instance is not being used after creation.
But the overriding was pretty clear already & for the warning we can
maybe configure our IDE to ignore certain ones, so, the question arises.
Annotations are needed to provide additional Info that will be useful for
the Developer, Compiler as well as Run-Time.
For the Developer: It makes it clear that the method is being overridden
& it originally belongs to the Superclass.
For the Compiler: It clarifies that the Method is being overridden. Java
Compiler uses this information to verify that the Original Method
Definition or Declaration (in case of Abstract Methods) does exist in the
SuperClass. If not, then we receive a compile time Error. Now this might
not seem like a big deal but consider the following code:
class User {
public String getGreetingString() {
return "Hello";
}
}
In the code above, we're defining a User Class with a method called
getGreetingString. Then, we're extending it in Admin Class. Admin Class
is Overriding the method & annotating it with @Override.
Most of us might not have even noticed it, but in Admin the method name
has an extra 's' it's defined as getGreetingsString which means it's a
new Method within Admin & not an Overridden Method. Now, such a
mistake would have gone overlooked, but thanks to @Override Annotation
compiler will verify the method Signature & throw an error informing us
that the Method is not Overriding anything because the Method name is
incorrect.
Types of Annotations
1. Source Annotations: These Annotations are only used by the Source Code & the
IDEs to keep the Developer Informed about Certain Details as well as empowering
certain IDE tools. Source Annotations are completely ignored & discarded by the
Compiler & Run-Time. Matter of fact, these annotations don't even reach to the
compiled code or JVM, they are just ignored by compiler & removed at compilation.
Example: @SuppressWarnings.
2. Compiler Annotations: These are used at Compilation to perform certain actions &
to provide info about the Code. These annotations are used by the Compiler, but they
don’t reach the Run-Time. Best example as demonstrated above is @Override.
3. Run-Time Annotations: These annotations are compiled & then used by the Run-
Time. At Run-Time, we can get access to the Annotations Metadata using Reflection
API. This is the type of Annotation mostly used by Frameworks Like, Spring.
But before creating an Annotation there are a few questions that need to
be answered, like Can I use @Override for a Class instead of a Method, Or
can I use @FunctionalInterface for a Method or a Field instead of an
Interface. Another set of Questions will be How exactly Annotations are
restricted for Source, Compiler & Run-Time.
For this, we have Annotations that are used on Top of Annotations to
Configure their Behavior.
@Target(ElementType[])
@Retention(RetentionPolicy)
@Retention specifies to what level the Annotation & Its data should be
retained in the Code. It takes in a single RetentionPolicy.
RetentionPolicy.SOURCE: This is the default value. This means the Annotation will
be ignored by the Compiler so, obviously, by the Run-Time as well.
RetentionPolicy.CLASS: Annotation is processed by the Compiler & it retains in the
Class File. It can not be used by the Run-Time.
RetentionPolicy.RUNTIME: Annotation is processed by the compiler & it's
available to use by the Run-Time using Reflection API.
import java.lang.annotation.ElementType
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Execute {
int times() default 1;
};
@Execute(times = 3)
public void shout() {
System.out.println("Inside Shout");
}
}
In the above code, We're annotating show & shout methods of the User
Class with our Custom @Execute Annotation.
import java.lang.annotation.Annotation
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
/* Output:
Inside Shout
Inside Shout
Inside Shout
Inside Show
*/
In the code above, we're getting access to the User's Class Object. Using
that, we're iterating Over User's Declared Methods, checking if the Method
is Annotated with our Custom @Execute Annotation. In which case, we're
invoking the Method number of times as defined by the Annotations Data.
1. Using @Query
2. Using @Query with Parameters
3. @Modifying Queries (preview lesson)
4. Named Queries
5. Returning a Custom Object from a Query
6. Advanced Features
5 LESSONS (Text) ~ 3.5 HOURS
Microservices :
Department service:
In the same url->
spring.application.name=department-service
Right click on the department service project and Run as -> Sprint boot
app
After refreshing the page we can see the eureka service is getting the clients listed as
below.
If you could not see the pack in maven then add below things to pom.xml
@EnableConfigServer
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
spring.application.name=config-server
application.yaml
server:
port: 8088
spring:
profiles:
active: native
NoClassDefFoundError: WebMvcConfigurer
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-config-server</artifactId>
</dependency>
jar file checked in this path : (Got it from Maven and placed.)
C:\Users\6114400\.m2\repository\org\springframework\cloud\spring-cloud-config-server\
4.1.3\ spring-cloud-config-server-4.1.3.jar
logger.setLevel(Level.FINE);
future.thenApply(result -> {
// Transform the result
return result.toUpperCase();
}).thenAccept(transformedResult -> {
// Consume the transformed result
System.out.println("Transformed Result: " + transformedResult);
});
//output: Transformed Result: RESULT OF THE ASYNCHRONOUS
COMPUTATION