Java Notes
Java Notes
Characteristics of Java:
1. Simple
2. Portable
3. Object-oriented
4. Secure: Java doesn't support pointer explicitly, But Java uses pointer implicitly.
Java is used in a networked and distributed environment. The following features make Java
a secure language:
JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime
environment in which java bytecode can be executed.
The JVM performs following operation:
o Loads code
o Verifies code
o Executes code
o Provides runtime environment
o Memory area
o Class file format
o Register set
o Garbage-collected heap
o Fatal error reporting etc.
JVM is the one that actually calls the main method present in a Java code. JVM is a part of
JRE(Java Runtime Environment). When we compile a .java file, .class files(contains byte-code)
with the same class names present in .java file are generated by the Java compiler.
This .class file goes into various steps when we run it. These steps together describe the
whole JVM.
1. Classloader
Classloader is a subsystem of JVM which is used to load class files. It is mainly responsible for
three activities.
Loading
Linking
Initialization
Loading: The Class loader reads the “.class” file, generate the corresponding binary data and
save it in the method area. After loading the “.class” file, JVM creates an object of type Class
to represent this file in the heap memory. Please note that this object is of type Class
predefined in java.lang package. These Class object can be used by the programmer for
getting class level information like the name of the class, parent name, methods and variable
information etc. To get this object reference we can use getClass() method of Object class.
Linking: Performs verification, preparation, and (optionally) resolution.
Verification: It ensures the correctness of the .class file i.e. it checks whether this file is
properly formatted and generated by a valid compiler or not. If verification fails, we get
run-time exception java.lang.VerifyError. This activity is done by the component
ByteCodeVerifier. Once this activity is completed then the class file is ready for
compilation.
Preparation: JVM allocates memory for class static variables and initializing the memory to
default values.
Resolution: It is the process of replacing symbolic references from the type with direct
references. It is done by searching into the method area to locate the referenced entity.
Initialization: In this phase, all static variables are assigned with their values defined in the
code and static block. This is executed from top to bottom in a class and from parent to child
in the class hierarchy.
JVM Memory
1. Method area: In the method area, all class level information like class name, immediate
parent class name, methods and variables information etc. are stored, including static
variables. There is only one method area per JVM, and it is a shared resource.
2. Heap area: Information of all objects is stored in the heap area. There is also one Heap
Area per JVM. It is also a shared resource.
4. Stack area: For every thread, JVM creates one run-time stack which is stored here. Every
block of this stack is called activation record/stack frame which stores methods calls. All
local variables of that method are stored in their corresponding frame. After a thread
terminates, its run-time stack will be destroyed by JVM.
5. PC Registers: Store address of current execution instruction of a thread. Obviously, each
thread has separate PC Registers.
5. Native method stacks: For every thread, a separate native stack is created. It stores native
method information.
Execution Engine
Execution engine executes the “.class” (bytecode). It reads the byte-code line by line, uses
data and information present in various memory area and executes instructions. It can be
classified into three parts:
Interpreter: It interprets the bytecode line by line and then executes. The disadvantage
here is that when one method is called multiple times, every time interpretation is
required.
Just-In-Time Compiler(JIT) : It is used to increase the efficiency of an interpreter. It
compiles the entire bytecode and changes it to native code so whenever the interpreter
sees repeated method calls, JIT provides direct native code for that part so re-
interpretation is not required, thus efficiency is improved.
Garbage Collector: It destroys un-referenced objects.
Java Variables:
1. Local variables: Variables declared inside the body of a method
2. Instance variables: Variables declared inside the class but outside the body of
method.
3. Static variable: Variable declared as static. It cannot be local. They are allocated
memory only one time when the class is loaded.
Java Tokens
1. Keywords
2. Identifiers
3. Constants/Literals
4. Special Symbols: [] () {}, ; * =
5. Operators
6. Comments
7. Separators
1.Keywords:
abstract assert boolean
break byte case
catch char class
const continue default
do double else
enum exports extends
final finally float
for goto if
implements import instanceof
int interface long
module native new
open opens package
private protected provides
public requires return
short static strictfp
super switch synchronized
this throw throws
to transient transitive
try uses void
volatile while with
1. Constants: Constants are also like normal variables. But the only difference is, their
values cannot be modified by the program once they are defined. Constants refer to
fixed values.
final int PI = 3.14; //Here final keyword is used to define the constant PI
2. Operators:
Arithmetic Operators
Unary Operators
Assignment Operator
Relational Operators
Logical Operators
Ternary Operator: variable = Expression1 ? Expression2: Expression3
Bitwise Operators
Shift Operators
instance of operator
Precedence and Associativity
// Main class
class ABC {
public static void main(String[] args)
{
// Creating object of class inside main()
ABC object = new ABC();
// Returning instanceof
System.out.println(object instanceof ABC);
}
}
Output
true
// Class 1
// Parent class
class Parent {
}
// Class 2
// Child class
class Child extends Parent {
}
// Class 3
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
// A simple case
if (cobj instanceof Child)
System.out.println("cobj is instance of Child");
else
System.out.println("cobj is NOT instance of Child");
Whenever you create the instance of subclass, an instance of parent class is created implicitly
which is referred by super reference variable.
Usage of Java super Keyword
1. super can be used to refer immediate parent class instance variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.
class Animal{
String color="white";
}
class Dog extends Animal{
String color="black";
void printColor(){
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class Test{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}
}
Output:
black
white
In the above example, Animal and Dog both classes have a common property color. If we print
color property, it will print the color of current class by default. To access the parent property,
we need to use super keyword.
Output:
eating...
barking...
In the above example Animal and Dog both classes have eat() method if we call eat() method
from Dog class, it will call the eat() method of Dog class by default because priority is given to
local. To call the parent class method, we need to use super keyword.
Output:
animal is created
dog is created
As we know well that default constructor is provided by compiler automatically if there is no
constructor. But, it also adds super( ) as the first statement.
Another example of super keyword where super( ) is provided by the compiler implicitly.
class Animal{
Animal ( ){
System.out.println("animal is created");
}
}
class Dog extends Animal{
Dog( ){
System.out.println("dog is created");
}
}
class TestSuper{
public static void main(String args[ ]){
Dog d=new Dog( );
}}
Output:
animal is created
dog is created
Output
This is class A
This is class B
This is class C
Java String
In Java, string is basically an object that represents sequence of char values. An array of
characters works same as Java string. For example:
1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. String s=new String(ch);
is same as:
1. String s="javatpoint";
The java.lang.String class is used to create a string object.
Java String class provides a lot of methods to perform operations on strings such as compare(),
concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.
1. By string literal
2. By new keyword
1) String Literal
1. String s="welcome";
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 the string doesn't
exist in the pool, a new string instance is created and placed in the pool. For example:
1. String s1="Welcome";
2. String s2="Welcome";//It doesn't create a new instance
To make Java more memory efficient (because no new objects are created if it exists already in
the string constant pool).
2) By new keyword
1. 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 s will refer to the
object in a heap (non-pool).
A String in Java that is specified as immutable
import java.io.*;
class ABC {
public static void main(String[ ] args)
{
String s1 = "java";
s1.concat(" rules");
Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality to
the user.
Abstraction lets you focus on what the object does instead of how it does it.
Points to Remember
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the body of the
method.
An abstract class is a class that is declared abstract —it may or may not include abstract
methods. Abstract classes cannot be instantiated, but they can be subclassed. When an
abstract class is subclassed, the subclass usually provides implementations for all of the
abstract methods in its parent class.
Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality to
the user.
Another way, it shows only essential things to the user and hides the internal details, for
example, sending SMS where you type the text and send the message. You don't know the
internal processing about the message delivery.
In this example, Bike is an abstract class that contains only one abstract method run. Its
implementation is provided by the Honda class.
abstract class Bike{
abstract void run( );
}
class Honda extends Bike{
void run(){
System.out.println("running safely");
}
public static void main(String args[ ]){
Bike obj = new Honda();
obj.run();
}
}
Any class that contains one or more abstract methods must also be declared abstract. To declare a class
abstract, you simply use the abstract keyword in front of the class keyword at the beginning of the class
declaration. There can be no objects of an abstract class. That is, an abstract class cannot be directly
instantiated with the new operator. Such objects would be useless, because an abstract class is not fully
defined. Also, you cannot declare abstract constructors, or abstract static methods.
Using final to Prevent Overriding While method overriding is one of Java’s most powerful features,
there will be times when you will want to prevent it from occurring. To disallow a method from being
overridden, specify final as a modifier at the start of its declaration.
class A {
final void meth() {
System.out.println("This is a final method.");
}
}
class B extends A {
void meth() {
// ERROR! Can't override.
System.out.println("Illegal!");
}
}
Because meth( ) is declared as final, it cannot be overridden in B. If you attempt to do so, a compile-time
error will result.
Sometimes you will want to prevent a class from being inherited. To do this, precede the class
declaration with final. Declaring a class as final implicitly declares all of its methods as final, too.
final class A {
// ...
}
// The following class is illegal.
class B extends A { // ERROR! Can't subclass A
// ...
}
Subpackages: Packages that are inside another package are the subpackages. These are not
imported by default, they have to imported explicitly.
xample :
import java.util.*;
util is a subpackage created inside java package.
// Class name is generally used when two packages have the same
// class name. For example in below code both packages have
// date class so using a fully qualified name to avoid conflict
import java.util.Date;
import my.package.Date;
Access Protection
Access to a private member of a class is granted only to other members of that class. Packages
add another dimension to access control. As you will see, Java provides many levels of
protection to allow fine-grained control over the visibility of variables and methods within
classes, subclasses, and packages. Classes and packages are both means of encapsulating and
containing the name space and scope of variables and methods. Packages act as containers for
classes and other subordinate packages. Classes act as containers for data and code. The class is
Java’s smallest unit of abstraction.
Java addresses four categories of visibility for class members:
• Subclasses in the same package
• Non-subclasses in the same package
• Subclasses in different packages
• Classes that are neither in the same package nor subclasses
The three access specifiers, private, public, and protected, provide a variety of ways to produce
the many levels of access required by these categories.
Anything declared public can be accessed from anywhere.
Anything declared private cannot be seen outside of its class. When a member does not have
an explicit access specification, it is visible to subclasses as well as to other classes in the same
package. This is the default access. If you want to allow an element to be seen outside your
current package, but only to classes that subclass your class directly, then declare that element
protected.