Core Java
Last updated
Was this helpful?
Last updated
Was this helpful?
Java manipulates objects 'by reference,' but it passes object references to methods 'by value.'
pass by value: The method parameter values are copied to another variable and then the copied object is passed.
pass by reference: An alias or reference to the actual parameter is passed to the method
Figure 1. After being passed to a method, an object will have at least two references
Figure 2. Only the method references are swapped, not the original ones
This means the references passed to the method are actually _copies _of the original references. Figure 1 below shows two references pointing to the same object after Java passes an object to a method.
Java copies and passes the _reference _by value, not the object. Thus, method manipulation will alter the objects, since the references point to the original objects. But since the references are copies, swaps will fail. As Figure 2 illustrates, the method references swap, but not the original references. Unfortunately, after a method call, you are left with only the unswapped original references. For a swap to succeed outside of the method call, we need to swap the original references, not the copies.
belong to concurrence collection.
fail-safe iterator.
1) Lambda Expressions :
it reduces the code where it is obvious, such as in an anonymous innerclass.
2)Parallel operations
eg: Parallel sorting
Array.sort(myArray); now can use Arrays.parallelSort(myArray);
3) Nashorn - The Node.js on JVM:
This is the JavaScript engine that enables us to run javascript to run on a jvm. It is similar to the V8 engine provided by chrome over which Node.js runs. It is compatible with Node.js applications while also allowing actual Java libraries to be called by the javascript code running on server. This is exciting to say at the least as it marries scalability and asynchronous nature of Node.js with safe and widespread server side Java middleware directly.
4) New data/time APIs
5)Concurrent Adders
Another beautiful addition to Java 8, meant specifically for code running at scale, is the concurrent “Adders”. One of the most basic concurrency patterns is reading and writing the value of a numeric counter. As such, there are many ways in which you can do this today, but none so efficient or elegant as what Java 8 has to offer.
The difference between this and the old Atomics is that here, when a CAS fails due to contention, instead of spinning the CPU, the Adder will store the delta in an internal cell object allocated for that thread. It will then add this value along with any other pending cells to the result of intValue(). This reduces the need to go back and CAS or block other threads.
There are three types of built-in ClassLoader in Java:
1) Bootstrap Class Loader - It loads JDK internal classes, typically loads rt.jar and other core classes for example java.lang.* package classes.
2) Extensions Class Loader - It loads classes from the JDK extensions directory, usually $JAVA_HOME/lib/ext directory.
3) System Class Loader - It loads classes from the current classpath that can be set while invoking a program using -cp or -classpath command line options.
Java ClassLoader are hierarchical and whenever a request is raised to load a class, it delegates it to its parent and in this way uniqueness is maintained in the runtime environment. If the parent class loader doesn’t find the class then the class loader itself tries to load the class
When JVM requests for a class, it invokesloadClass
function of the ClassLoader by passing the fully classified name of the Class.
loadClass function calls forfindLoadedClass()
method to check that the class has been already loaded or not. It’s required to avoid loading the class multiple times.
If the Class is not already loaded then it will delegate the request to parent ClassLoader to load the class.
If the parent ClassLoader is not finding the Class then it will invoke findClass() method to look for the classes in the file system.
Modularize a system and load, unload and update modules at runtime
Use different versions of an API library (e.g. an XML parser) in parallel
Isolate different applications running within the same JVM (ensuring they don't interfere with each other, e.g. through static variables)
1). by String literal
by using double quotes. Each time you create a string literal, the JVM checks the string constant pool first. If the String already exists in the pool, a reference to the pooled instance is returned. If string doesn't exist in the pool, a new String instance is created and placed in the pool.
eg: String s1 = "Welcome";
In the above example only one object will be created. Firstly JVM will not find any string object with the value "Welcome" in string constant pool, so it will create a new object. After that it will find the string with the value "Welcome" in the pool, it will not create new object but will return the reference to the same instance.
note: String objects are stored in a special memory area known as string constant pool.
Why java uses concept of String literal?
To make Java more memory efficient(because no new objects are created if it exists already in string constant pool).
2). by new keyword
eg: String s = new String("Welcome");//creates two objects and one reference variable
In such case, JVM will create a new string object in normal(non pool) heap memory and the literal "Welcome" will be placed in the string constant pool. The variable will refer to the object in heap(non pool).
We can compare String in java on the basis of content and reference.
It is used in authentication(by equals() method), sorting(by compareTo() method), reference matching(by == operator) etc.
4.2.1 euqals()// compares the original content of the string
1)public boolean equals(Object another)
2)public boolean equalsIgnoreCase(String another)// ignoring case
4.2.2 ==//compares references not values
4.2.3 compareTo()// compares values lexicographically and returns an integer value that describes if first string is less than, equal to or greater than second string.
s1==s2 : 0
s1>s2 : positive value
s1<s2 : negative value
eg: s1="Sa";
s1.compareTo(s2) // ==0
s1.compareTo(s3)); //1(because s1>s3)
s3.compareTo(s1)); //1(because s1<s3)
eg: String s = "Hello"+" World";// s==Hello World
String s=(new StringBuilder()).append("Hello").append(" World).toString();
concat() method concatenates the specified string to the end of current string.
eg:
String s1 = "Hello";
String s2 = "World";
String s3 = s1.concat(s2); // s3==Hello World
public String substring(int startIndex):This method returns new String object containing the substring of the given string from specified startIndex (inclusive).
public String substring(int startIndex, int endIndex):
This method returns new String object containing the substring of the given string from specified startIndex to endIndex.
https://www.javatpoint.com/static-keyword-in-java
static variable:
The static variable can be used to refer the common property of all objects (that is not unique for each object) e.g. company name of employees, college name of students etc.
The static variable gets memory only once in class area at the time of class loading.
It makes your program memory efficient(i.e it saves memory).
When a variable is declared as static, then a single copy of variable is created and shared among all objects at class level. Static variables are, essentially, global variables. All instances of the class share the same static variable.
static method: main method is static!
A static method belongs to the class rather than object of a class.
A static method can be invoked without the need for creating an instance of a class.
static method can access static data member and can change the value of it.
They can only directly call other static methods.
They can only directly access static data.
note:There are two main restrictions for the static method.
The static method can not use non static data member or call non-static method directly.
this and super cannot be used in static context.
static block:
Is used to initialize the static data member.
It is executed before main method at the time of classloading.
eg: static{System.out.println("Static block is invoked!");}
usage:
super can be used to refer immediate parent class instance variable.
super can be used to invoke immediate parent class method.
super() can be used to invoke immediate parent class constructor.
Note: super() is added in each class constructor automatically by compiler if there is no super() or this().
two uses of a final class:
2) The other use of final with classes is to create an immutable class like the predefined String class.
Access Levels
Modifier
Class
Package
Subclass
World
public
Y
Y
Y
Y
protected
Y
Y
Y
N
no modifier
Y
Y
N
N
private
Y
N
N
N
Abstract class in java can’t be instantiated. Abstract class is mostly used to provide base for subclasses to extend and implement the abstract methods and override or use the implemented methods in abstract class.
keyword is used to create an abstract class in java.
Abstract class in java can’t be instantiated.
We can useabstract
keyword to create an abstract method, an abstract method doesn’t have body.
If a class have abstract methods, then the class should also be abstract using abstract keyword, else it will not compile.
It’s not necessary to have abstract class to have abstract method.
If abstract class doesn’t have any method implementation, its better to use interface because java doesn’t support multiple class inheritance.
The subclass of abstract class in java must implement all the abstract methods unless the subclass is also an abstract class.
Java Abstract class can implement interfaces without even providing the implementation of interface methods.
Java Abstract class is used to provide common method implementation to all the subclasses or to provide default implementation.
We can run abstract class in java like any other class if it hasmain()
method.
The instanceof keyword can be used to test if an object is of a specified type.
Since a subclass 'is a' type of its superclass, the following if statement, where Child is a subclass of Parent, returns true.
eg:
Main difference between stack and heap
1) Whenever an object is created, it’s always stored in the Heap space and stack memory contains the reference to it. Stack memory only contains local primitive variables and reference variables to objects in heap space. eg: as a member variable, local variable or class variable, they are always created inside heap space in Java.
2) Each Thread in Java has their own stack which can be specified using -Xss JVM parameter, similarly, you can also specify heap size of Java program using JVM option -Xms and -Xmx where -Xms is starting size of the heap and -Xmx is a maximum size of java heap.
3) If there is no memory left in the stack for storing function call or local variable, JVM will throw java.lang.StackOverFlowError, while if there is no more heap space for creating an object, JVM will throw java.lang.OutOfMemoryError.
4) If you are using Recursion, on which method calls itself, you can quickly fill up stack memory. Another difference between stack and heap is that size of stack memory is a lot lesser than the size of heap memory in java. Because of simplicity in memory allocation (LIFO), stack memory is very fast when compared to heap memory.
5) Variables stored in stacks are only visible to the owner Thread while objects created in the heap are visible to all thread. In other words, stack memory is kind of private memory of Java Threads while heap memory is shared among all threads. Heap memory is used by all the parts of the application whereas stack memory is used only by one thread of execution.
7) Stack memory is short-lived whereas heap memory lives from the start till the end of application execution.
Read more:
fail-fast in Java
As name suggest fail-fast Iterators fail as soon as they realized that structure of Collection has been changed since iteration has begun. Structural changes means adding, removing or updating any element from collection while one thread is Iterating over that collection. fail-fast behavior is implemented by keeping a modification count and if iteration thread realizes the change in modification count it throws ConcurrentModificationException.
It happens because ArrayList iterator is fail-fast by design. What it means is that once the iterator is created, if the ArrayList is modified, it throws
ConcurrentModificationException
fail-safe in Java
Contrary to fail-fast Iterator, fail-safe iterator doesn't throw any Exception if Collection is modified structurally while one thread is Iterating over it because they work on clone of Collection instead of original collection and that’s why they are called as fail-safe iterator. Iterator of CopyOnWriteArrayList is an example of fail-safe Iterator also iterator written by ConcurrentHashMap keySet is also fail-safe iterator and never throw ConcurrentModificationException in Java.
Java iterator is an interface belongs to collection framework allow us to traverse the collection and access the data element of collection without bothering the user about specific implementation of that collection it.
Basically, List and Set collection provides the iterator.
Syntax:
It comes inside java.util package. as public interface Iterator and contains three methods:
boolean hasNext():
this method returns true if this Iterator has more element to iterate.
Object next():
remove():
method remove the last element return by the iterator this method only calls once per call to next().
size()
is a method specified injava.util.Collection
, which is then inherited by every data structure in the standard library.length
is a field on any array (arrays are objects, you just don't see the class normally), andlength()
is a method onjava.lang.String
//below is allowed
//below is compile error
In general, a set of curly brackets{} defines a scope.
In Java, we can usually access a variable as long as it was defined within the same set of brackets as the code we are writing or within any curly brackets inside of the curly brackets where the variable was defined.
Any variable defined in a class outside of any method can be used by all member methods.
When a method has same local variable as a member, this keyword can be used to reference the current class variable.
For a variable to be read after the termination of a loop, It must be declared before the body of the loop.
This will automatically break up the target collection into several parts, which will be sorted independently across a number of cores and then grouped back together. The only caveat here is that when called in highly multi-threaded environments, such as a busy web container, the benefits of this approach will begin to diminish (by ) due to the cost of increased CPU context switches.
Up until now this was done using Atomics, which used a direct CPU compare and swap (CAS) instruction (via theclass) to try and set the value of a counter. The problem was that when a CAS failed due to contention, the AtomicInteger would spin, continually retrying the CAS in an infinite loop until it succeeded. At high levels of contention this could prove to be pretty slow.
Enter Java 8’s s. This set of classes provides a convenient way to concurrently read and write numeric values at scale. Usage is super simple. Just instantiate a new LongAdder and use itsandmethods to increase and sample the counter.
They cannot refer to or in any way.
1)One is definitely to prevent , as final classes cannot be extended. For example, all like , etc. are final classes.
All the methods in an interface are implicitly abstract unless the interface methods are static or default. Static methods and default methods in interfaces are added in Java 8, for more details read .
6) Memory management in stack is done in LIFO manner whereas it’s more complex in Heap memory because it’s used globally. Heap memory is divided into Young-Generation, Old-Generation etc, more details at .
Java doc says this is not a guaranteed behavior instead its done of "best effort basis", So application programming can not rely on this behavior. Also since multiple threads are involved while updating and checking modification count and this check is done without synchronization, there is a chance that Iteration thread still sees a stale value and might not be able to detect any change done by parallel threads. Iterators returned by most of JDK1.4 collection are fail-fast including Vector, , HashSet etc.
return the next element in the collection until the hasNext() method return true. Its always recommended to call hasNext() method before calling next() method to avoid