Yes, We can declare a constructor private by using the private access specifier.
If a constructor is declared with private access specifier, we are not able to create
an object of the class.
we can use this private constructor in Singleton Design Pattern.
There are many ways to iterate a HashMap.
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class IterateMapExample {
public static void main(String args[]){
Map empMap = new HashMap();
empMap.put(1,"Raju");
empMap.put(2,"Anita");
empMap.put(3,"Satish");
//#1 Using KeySet
for(Map.Entry entrySet : empMap.entrySet()){
System.out.println("key==" +entrySet.getKey() + ", value=="+entrySet.getValue());
}
//#2 Using KeySet For loop
for(Integer id : empMap.keySet()){
System.out.println("key==" +id + ", value=="+empMap.get(id));
}
//#3 Using Iterator
Iterator> itr = empMap.entrySet().iterator();
while(itr.hasNext()){
Map.Entry entry = itr.next();
System.out.println("key==" +entry.getKey() + ", value=="+entry.getValue());
}
//#4 Using foreach
empMap.forEach((k,v) -> System.out.println("key==" +k + ", value=="+v));
}
}
Cloning is the process to create exact copy of an object.
The clone() method of Object class is used to clone an object.
There are two types of exception.
There are two types of exception.
Those exception are checked on compile time. If some code throws a checked exception, then the method must either handle the exception or it must specify the exception using the throws keyword.
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class CheckedExceptionExample {
public static void main(String[] args) throws IOException {
FileReader file = new FileReader("C:\\folder1\\sample.txt");
BufferedReader br = new BufferedReader(file);
while(br.readLine()!=null) {
System.out.println(br.readLine());
}
br.close();
}
}
Those exception are not checked on compile time that is called Unchecked Exception. Exceptions under Error and RuntimeException classes are unchecked exceptions.
public class UncheckedException {
public static void main(String args[]){
int[] intArray = new int[]{ 1,2,3,4,5,6 };
System.out.println(intArray[10]);
}
}
Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 6
at com.inventory.sample.UncheckedException.main(UncheckedException.java:6)
JDK stands Java Development Kit. JDK provides the environment to develop, execute or run the Java program. JRE is a part of JDK and JVM is a part of JRE.
JRE stands Java Runtime Environment. JRE is a part of JDK, it provides an environment to run the java program or application onto machine. JRE does not provides development tools, its provides the functionality to run the program/application only.
JVM stands Java Virtual Machine and it is a part of JRE(Java Runtime Environment). JVM is a run-time engine to run Java applications. JVM calls the main method present in a Java code. It provides a runtime environment for driving Java applications or code. JVM is an abstract machine that converts the Java bytecode into machine language. It is called a virtual machine because it doesn't physically exist.
The below process will be executed when we compile the file.
The next step is to run the ".class" file.
Some of the areas are created by the JVM and some of the areas are created by the threads that are used in a program. When thread start creates the dat and destroy when thread exits but the memory area created by JVM is destroyed only when the JVM exits.
Java Memory Areas
Java Memory Areas
Method area is a part of the heap memory which is shared among all the threads. The method area is allocated for class structure, superclass name, interface name, and constructors.
The Native method Stack is also known as C stack. A Native method Stack is created when a thread is created.
The Garbage collector finds the unused objects and deletes them to free up memory. When Java programs run on the JVM, objects are created on the heap, after execution, some objects will no longer be needed. The garbage collector finds these unused objects and deletes them to free up memory.
We can execute System.gc().
When ever stack memeory is out of space space that time we get the Stack Overflow Error. It may occur due to not handling the termination condition or infinite recursion.
Example of Stack Overflow Error
public class StackOverflowErrorExample {
public static void main(String args[]){
StackOverflowErrorExample.getAdditionValue(5);
}
public static Integer getAdditionValue(Integer i){
i=i+5;
getAdditionValue(i);
return i;
}
}
Output:
Exception in thread "main" java.lang.StackOverflowError
at com.sample.StackOverflowErrorExample.getAdditionValue( StackOverflowErrorExample.java:10 )
The default Java thread stack size 320kb but we can increase the size with
the stack size with the one -Xss option from below list.
Go to the tomcal directory and open tomcat\bin\setenv.bat, choose one from the below list
and write in the setenv.bat.
OutOfMemoryError is a runtime error in Java. It occurs due to insufficient space
in the Java heap memory.
Go to the tomcal directory and open tomcat\bin\setenv.bat, add -Xms64m -Xmx256m.
PermGen stands for Permanent Generation. Java 8 and above has no PermGen space. From Java 8 PermGen was replaced by a new memory area called Metaspace. It is also a type of heap space. JVM uses PermGen to keep track of loaded class metadata which are not changed frequently.
MetaSpace is introduceed in Java 8 to replace the PermGen space. The MetaSpace is used to hold class metadata and the size dynamically resize based on the application’s demands.
When new class is loaded, the JVM identified the class defination and extracts metadata about the class, including as its name, parent class, interfaces implemented, fields and methods. Subsequently, JVM allocates memory in the MetaSpace for the class’s metadata.
JVM tracks the MetaSpace’s size as well as the amount of memory utilised by each class’s information. If the MetaSpace exceeds the allocated space, JVM checks which metadata is no longer is use and start the process of Garbage Collection to clear up space.
If a class is no longer is used or the JVM shuts down, the metadata in the MetaSpace will clean up immediately.
import java.lang.management.MemoryUsage;
public class MetaSpaceExample {
public static void main(String args[]) {
MemoryUsage memory = ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage();
long usedMetaspace = memory.getUsed();
long maxMetaspace = memory.getMax();
System.out.println( "usedMetaspace="+usedMetaspace );
System.out.println( "maxMetaspace="+maxMetaspace );
}
}
java -XX:+PrintFlagsFinal -version | grep MetaspaceSize
-XX:MetaspaceSize=100M
public class ComparableExample implements Comparable<
ComparableExample>{ private Integer id; private String name; private String email; private Integer age; @Override //Override compareTo method public int compareTo(ComparableExample obj) { if(age==obj.age) return 0; else if(age>obj.age) return 1; else return -1; } }
import java.util.Comparator; public class Employee { private Integer id; private String name; private String email; private Integer age; public Employee(Integer id, String name, String email, Integer age) { this.id = id; this.name = name; this.email = email; this.age = age; } public Integer getId() { return id; } public String getName() { return name; } public String getEmail() { return email; } public Integer getAge() { return age; } } //Seperate class need to create class DemoComtarorExample implements Comparator<
Employee> { @Override //Override the compare method public int compare(Employee obj1, Employee obj2) { if(obj1.getAge() == obj2.getAge()) return 0; else if(obj1.getAge() > obj2.getAge()) return 1; else return -1; } }
An array is a container object that holds a fixed number of values of a single type.
public static void main(String[] args) throws IOException {
Integer[] array = new Integer[3];
array[0]=3;
array[1]=4;
array[2]=5;
or
Integer[] array1 = {3,4,5};
}