=======
DATA TYPES
boolean -->1bit
byte --> 1byte
Short --> 2bytes
char --> 2byte
int --> 4byte
float --> 4byte
long --> 8byte
double --> 8byte
* / % have a higher precedence than + or –
---------------------------------------------------------
Variables in Java
--Class Variables
.Copy created per class
static variables
--Instance Variables
.Copy created per instance of the class.
--Local Variable
.Occur within a method and blocks
.Copy created per method call
.If used must initialized otherwise complier complains
----------------------Architecture-neutral-----------------------------------
Java is architecture neutral because there are no implementation
dependent features, for example, the size of primitive types is fixed.
In C programming, int data type occupies 2 bytes of memory for
32-bit architecture and 4 bytes of memory for 64-bit architecture.
However, it occupies 4 bytes of memory for both 32 and 64-bit
architectures in Java.
-----------------------------JDK------------------------------------
The Java Development Kit (JDK) is a software development environment which is used
to develop Java applications and applets .
It physically exists.
It contains JRE + development tools.
Java Applet
Applet is a special type of program that is embedded in the webpage to generate the
dynamic content.
It runs inside the browser and works at client side.
Applet class extends Panel. Panel class extends Container which is the subclass of
Component
java.applet.Applet.
public void init():
public void start():
public void stop():
public void destroy():
java.awt.Component class
The Component class provides 1 life cycle method of applet.
public void paint(Graphics g): is used to paint the Applet. It provides Graphics
class object that can be used for drawing oval, rectangle, arc etc.
Who is responsible to manage the life cycle of an applet?
Java Plug-in software
-------------------------JRE--------------------------------
JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The
Java Runtime Environment is a set of software tools which are used for developing
Java applications. It is used to provide the runtime environment. It is the
implementation of JVM. It physically exists. It contains a set of libraries + other
files that JVM uses at runtime.
JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine
because it doesn't physically exist.
However, Java is platform independent. There are three notions/concept of the JVM:
specification, implementation, and instance.
The JVM performs the following main tasks:
Loads code
Verifies code
Executes code
Provides runtime environment
===================================================================================
==
---------------------INHERITANCE-----------------------------
The idea behind inheritance in Java is that you can create
new classes that are built upon existing classes. When you inherit
from an existing class, you can reuse methods and fields of the parent
class. Moreover, you can add new methods and fields in your current
class also.
It is important to note that a subclass is not a "subset" of a superclass.
In contrast, subclass is a "superset" of a superclass.
It is because a subclass inherits all the variables and methods of the superclass;
in addition, it extends the superclass by providing more variables and methods.
Inheritance represents the IS-A relationship which is also known as
a parent-child relationship.
Why use inheritance in java
For Method Overriding (so runtime polymorphism can be achieved).
The extends keyword indicates that you are making a new class that
derives from an existing class. The meaning of "extends" is to increase
the FUNCTIONALITY.
Q) Why multiple inheritance is not supported in java?
We have two classes B and C inheriting from A.
Assume that B and C are overriding an inherited method and they provide their own
implementation.
Now D inherits from both B and C doing multiple inheritance. D should inherit that
overridden method.
BUT which overridden method will be used? Will it be from B or C? Here we have an
ambiguity. This is known as Diamond Problem.
To avoid this problem , Java does not support multiple inheritance through classes
OR---------
To reduce the complexity and simplify the language, multiple inheritance is not
supported in java.
Consider a scenario where A, B, and C are three classes. The C class inherits A and
B classes.
If A and B classes have the same method and you call it from child class object,
there will be ambiguity to call the method of A or B class.
Since compile-time errors are better than runtime errors, Java renders compile-time
error if you inherit 2 classes.
So whether you have same method or different, there will be compile time error.
Since java does not support multiple inheritances in the
case of class, by using an interface it can achieve multiple
inheritances.
----------------------Polymorphism in Java--------------------------------
Polymorphism in Java is a concept by which we can perform a single action in
different ways.
Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means
many and "morphs" means forms.
So polymorphism means many forms.
There are two types of polymorphism in Java: compile-time polymorphism and runtime
polymorphism.
We can perform polymorphism in java by method overloading and method overriding
-----------------BINDINGS-----------------------------
static/early/compile time binding---> done by JAVAC
If there is any private, final or static method in a class, there is static binding
class Car {
public static void startEngine(){
System.out.println("Car Engine Started");
}
}
public class Porsche extends Car {
public static void startEngine(){
System.out.println("Porche's Engine Started");
}
public static void main(String args[]){
Car car1 = new Porsche();
Car car2 = new Car();
car1.startEngine();
car2.startEngine();
}
}
Output:
Car Engine Started
Car Engine Started
Let's examine the output of thementioned code.
We find that, even though the "startEngine" method was overridden in the derived
class Porsche and that the object "car1" was initialized with reference to the
class Porsche, the "startEngine()" method was left unmodified and still printed the
text of the superclass Car.
It was caused by the static function "startEngine()" of the class Car's being
constrained by the java compiler during compilation, making it impossible to
override.
Late or Dynamic Binding ---> done by JRE
Late binding or dynamic binding is used by the compiler if it is impossible to
determine which method call a specific method is bound to during compilation.
Method Overriding is the most effective example of dynamic binding.
A subclass overrides the method of the superclass, and during execution, methods
are linked to the appropriate references.
It should be emphasized that the method being overridden must not be defined as
static, final, or private in order for dynamic binding to take place.
Suppose any of the mentioned modifiers are used while declaring the method.
In that case, Java will use static binding since it can quickly identify the parent
reference and prevent the method from being overwritten.
Let's examine dynamic binding using the prior illustration. However, the methods
won't be declared "static" this time.
class Car {
public void startEngine(){
System.out.println("Car Engine Started");
}
}
public class Porsche extends Car {
public void startEngine(){
System.out.println("Porche's Engine Started");
}
public static void main(String args[]){
Car car1 = new Porsche();
Car car2 = new Car();
car1.startEngine();
car2.startEngine();
}
}
Output:
Porche's Engine Started
Car Engine Started
Early Binding
Early Binding is the way of resolving method calling
that takes place at compile time by utilizing the class information.
It takes place during compilation.
Early Binding resolves method calling by using the class information.
Early binding is also referred to as static binding.
Early binding is used to bond overloading methods.
Early binding has a faster execution speed.
Late Binding
The term "Late Binding" refers to the practice of a call to a method or function in
the body of the statement that takes place at run time.
It takes place at runtime.
The object is used by Late Binding to resolve method calling.
Late binding is also referred to as dynamic binding.
Late binding is used to bond overridden methods.
2
Late binding has a slower execution speed.
-=-=-==-=-=-=-=-=-=-=-=-==-=-=-=-=-=-=-=-=-=-=-=-=
static binding
When type of the object is determined at compiled time(by the compiler), it is
known as static binding.
class Dog{
private void eat(){System.out.println("dog is eating...");}
public static void main(String args[]){
Dog d1=new Dog();
d1.eat();
}
}
Dynamic binding
When type of the object is determined at run-time, it is known as dynamic binding.
Example of dynamic binding
class Animal{
void eat(){System.out.println("animal is eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("dog is eating...");}
public static void main(String args[]){
Animal a=new Dog();
a.eat();
}
}
output=dog is eating
In the above example object type cannot be determined by the compiler,
because the instance of Dog is also an instance of Animal.So compiler doesn't know
its type, only its base type
--------------------------------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,
Abstraction lets you focus on what the object does instead of how it does it.
Ways to achieve Abstraction
There are two ways to achieve abstraction in java
Abstract class (0 to 100%)
A class which is declared as abstract is known as an abstract class
it needs to be extended and its method implemented
EX:- abstract class A{}
An abstract class can have a data member, abstract method, method body (non-
abstract method), constructor, and even main() method
Rule: If there is an abstract method in a class, that class must be abstract.
class Bike12{
abstract void run();
}
OUTPUT:-
compile time error
Rule: If you are extending an abstract class that has an abstract method, you must
either provide the implementation of the method or make this class abstract.
Points to Remember
An abstract class must be declared with an abstract keyword.
It can have abstract and non-abstract methods.
It cannot be instantiated.
It can have constructors and static methods also.
It can have final methods which will force the subclass not to change the body of
the method
Abstract Method in Java
A method which is declared as abstract and does not have implementation is known as
an abstract method.
abstract void printStatus();//no method body and abstract
Interface (100%)
--------------------Encapsulation in Java------------------------------------
Encapsulation in Java is a process of wrapping code and data together into a single
unit
We can create a fully encapsulated class in Java by making all the data members of
the class private. Now we can use setter and getter methods to set and get the data
in it.
The Java Bean class is the example of a fully encapsulated class
It is a way to achieve data hiding in Java because other class will not be able to
access the data through the private data members.
===================================================================================
-----------------"Varargs"------------------------------------
In Java, varargs (variable-length arguments) is a feature that
allows a method to accept a variable number of arguments of the
same type.
Varargs are useful when you want to create methods that can take
a different number of arguments without having to specify them
individually.
Varargs are represented by an ellipsis (...) followed by the
argument type.
----------------------keyword "STATIC"-----------------------------------
Usages
1. static data members ---
--- Memory allocated only once at the class loading time
--- not saved on object heap
--- but in special memory area called method area (meta space) .
--- shared across all objects of the same class.
--- Initialized to their default values(eg --double --0.0,char -0, boolean -
false,ref -null)
How to refer ? -- className.memberName
2. static methods
--- Can be accessed w/o instantiation. (ClassName.methodName(....))
Can't access 'this' or 'super' from within static method.
Rules
-- 1. Can static methods access other static members directly(w/o instance) -- YES
-- 2. Can static methods access other non-static members directly(w/o instance) --
NO
-- 3. Can non-static methods access other static members directly(w/o instance) --
YES
4. static initializer block
syntax --
static {
// block gets called only once at the class loading time , by JVM's classloader
// usage --1. to init all static data members
//& can add functionality -which HAS to be called precisely once.
Use case : singleton pattern , J2EE for loading hibernate/spring... frmwork.
}
5. static nested classes ---
eg --
class Outer {
// static & non-static members
static class Nested
{
//can access ONLY static members of the outer class DIRECTLY(w/o inst)
}
}
public static void main
main() is static method and called before
instantiation of the class.
Since it is static, it is automatically invoked by the
startup code.
It is the entry point of a class.
Loader will load the class and search for main method
to enter into class, so main()is declared as static.
So, ClassName.main(…)
initialization blocks
Arbitrary blocks of code.
Executed before main() when class is loaded.
Used for initializing static variables.
A class can have more than one static blocks.
If more than one static blocks exists in a program
then called in the order they appear in the source
code.
-------------------------------keyword
"FINAL"------------------------------------------------
when used with variable ----> variable becomes constant
when used with Functions ----> prevent Functions to override
private methods are implicitly final.
when used with classes ----> prevents classes to get inherited
A class declared as a final cannot be subclassed.
Every method of a final class is by default final.
---------------------------operator "INSTANCEOF"------------------------
The java instanceof operator is used to test whether the object is an instance of
the specified type (class or subclass or interface).
The instanceof in java is also known as TYPE COMPARISON operator because it
compares the instance with type. It returns either true or false. If we apply the
instanceof operator with any variable that has null value, it returns false
-----------------------------Regarding "this" & "SUPER"
keywords---------------------------------------------------
this(...) implies invoking constructor from the same class.
super(...) implies invoking constructor from the immeidate super class
1. Only a constr can use this(...) or super(..)
2. It has to be 1st statement in the constructor
3. Any constructor can never have both ie. this() & super()
4. super & this (w/o brackets) are used to access (visible) members of super class
or the same class.
-----------------------------------INTERFACES
------------------------------------------------
In Java, an interface is a type that defines a contract of methods that a class
must implement.
The interface in Java is a mechanism to achieve abstraction. There can be only
abstract(HIDE UNNECESSARY) methods in the Java interface, not method body. It is
used to achieve abstraction and multiple inheritance in Java.
Java Interface also represents the IS-A relationship.
It cannot be instantiated just like the abstract class.
Since Java 8, we can have default and static methods in an interface.
Since Java 9, we can have private methods in an interface.
It is used to achieve abstraction.
By interface, we can support the functionality of multiple inheritance.
It can be used to achieve loose coupling
all the methods in an interface are declared with the empty body, and all the
fields are public, static and final by default. A class that implements an
interface must implement all the methods declared in the interface.
****The Java compiler adds public and abstract keywords before the interface
method.
Moreover, it adds public, static and final keywords before data members.i.e.
Interface fields are public, static and final by default, and the methods are
public and abstract****
Multiple inheritance in Java by interface
If a class implements multiple interfaces, or an interface extends multiple
interfaces, it is known as multiple inheritance.
class can extend only one 1 class..but it can implement any no of i/f
i/f can extend any no of i/f
Since Java 8, we can have method body in interface. But we need to make it default
method. & we can have static method in interface.
--TYPES
When an interface contains only one single abstract method, then it is
known as a FUNCTIONAL Interface.--> EX :- Runnable,ActionListenerJava provides an
anotation @FunctionalInterface, which is used to declare an interface as functional
interface.
What is marker or tagged interface?
An interface which has no member is known as a marker or tagged interface, for
example, Serializable, Cloneable, Remote, etc. They are used to provide some
essential information to the JVM so that JVM may perform some useful operation.
-------------------------------Java Lambda
Expressions-----------------------------------------------------------
Lambda expression is a new and important feature of Java which was included in Java
SE 8.
It provides a clear and concise way to represent one method interface using an
expression.
It is very useful in collection library.
It helps to iterate, filter and extract data from collection
The Lambda expression provides the implementation of functional interface.
Java lambda expression is treated as a function, so compiler does not create .class
file.
A lambda expression can have zero or any number of arguments.
if there is only one statement, you may or may not use return keyword but You must
use return keyword when lambda expression contains multiple statements.
------------------------------
Annotations ------------------------------------------------------
From JDK 1.5 onwards : Annoations are available --- metadata meant for Compiler or
JRE.(Java tools)
Java Annotation is a tag that represents the metadata i.e. attached with class,
interface, methods or fields to indicate some additional information which can be
used by java compiler and JVM.
Annotations in java are used to provide additional information, so it is an
alternative option for XML.
eg @Override,@Deprecated,@SuppressWarnings,@FunctionalInterface.....
@Override --
It is an annotation meant for javac.
It's Method level annotation ,that appears in a sub class
It's Optional BUT recommended.
-------------------Java String equals()------------------------------------
The Java String class equals() method compares the two given strings based on the
content of the string. If any character is not matched, it returns false. If all
characters are matched, it returns true.
The String equals() method overrides the equals() method of the Object class.
--------------------------WRAPPER
CLASS--------------------------------------------------
Wrapper classes are fundamental in Java because they help a Java program be
completely object-oriented. The primitive data types in java are not objects, by
default. They need to be converted into objects using wrapper classes.
Need of Wrapper Classes
1:They convert primitive data types into objects.
2:The classes in java.util package handles only objects and hence wrapper classes
help in this case also.
3:Data structures in the Collection framework, such as ArrayList and Vector, store
only objects (reference types) and not primitive types.
Use of Wrapper classes in Java
Java is an object-oriented programming language, so we need to deal with objects
many times like in Collections, Serialization, Synchronization, etc
Change the value in Method: Java supports only call by value. So, if we pass a
primitive value, it will not change the original value. But, if we convert the
primitive value in an object, it will change the original value.
Serialization: We need to convert the objects into streams to perform the
serialization. If we have a primitive value, we can convert it in objects through
the wrapper classes.
Synchronization: Java synchronization works with objects in Multithreading.
java.util package: The java.util package provides the utility classes to deal with
objects.
Collection Framework: Java collection framework works with objects only. All
classes of the collection framework (ArrayList, LinkedList, Vector, HashSet,
LinkedHashSet, TreeSet, PriorityQueue, ArrayDeque, etc.) deal with objects only.
Autoboxing
The automatic conversion of primitive types to the object of their corresponding
wrapper classes is known as autoboxing. For example – conversion of int to Integer,
long to Long, double to Double, etc.
Since Java 5, we do not need to use the valueOf() method of wrapper classes to
convert the primitive into objects.
//Converting int into Integer
int a=20;
Integer i=Integer.valueOf(a);//converting int into Integer explicitly
Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internally
Unboxing
It is just the reverse process of autoboxing. Automatically converting an object of
a wrapper class to its corresponding primitive type is known as unboxing. For
example – conversion of Integer to int, Long to long, Double to double, etc.
Since Java 5, we do not need to use the intValue() method of wrapper classes to
convert the wrapper type into primitives.
//Converting Integer to int
Integer a=new Integer(3);
int i=a.intValue();//converting Integer to int explicitly
int j=a;//unboxing, now compiler will write a.intValue() internally
-------------------------------
JAVA STRING--------------------------------------------------------------
Java String
In Java, string is basically an object that represents sequence of char values. An
array of characters works same as Java string.
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.
The java.lang.String class implements Serializable, Comparable and CharSequence
interfaces.
CharSequence Interface
The CharSequence interface is used to represent the sequence of characters. String,
StringBuffer and StringBuilder classes implement it. It means, we can create
strings in Java by using these three classes.
There are two ways to create String object:
By string literal
By new keyword
1) String Literal
Java String literal is created by using double quotes. For Example:
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.
Why Java uses the concept of String literal?
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
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).
aString Pool: One important use of the constant pool is the string pool. String
literals in Java are stored in the constant pool to conserve memory and facilitate
string interning. This means that if multiple string literals have the same value,
they share the same reference in the constant pool, reducing memory usage.
mmutable: One of the most important characteristics of the String class in Java is
that strings are immutable, which means once a String object is created, its value
cannot be changed. Any operation that appears to modify a String actually creates a
new String object with the modified value.
Creation: You can create a String in Java using either a string literal or by
instantiating a String object.
String str1 = "Hello, World!"; // Using a string literal
String str2 = new String("Hello, World!"); // Using a constructor
String Builder and String Buffer: For situations where you need to perform many
string manipulations, especially in a multi-threaded environment, you should use
StringBuilder or StringBuffer classes. These classes provide mutable strings and
are more efficient than using String for concatenation.
--------------------------------Nested
Class-------------------------------------------------------
In Java, a nested class is a class that is defined within another class.
Nested classes are also sometimes referred to as inner classes.
Nested classes are primarily used for two main purposes:
Encapsulation
access control
TYPES: INNER CLASS(NON-STATIC)---STATIC---LOCAL INNER CLASS---ANONYMOUS INNER CLASS
-----------------------------GARBAGE
COLLECTION--------------------------------------------------
Garbage Collection is a process to identify and delete the objects from Heap memory
which are not in use. GC frees the space after removing unreferenced objects
To do so, we were using free() function in C language and delete() in C++. But, in
java it is performed automatically. So, java provides better memory management.
How to request for GC ?
API of System class :--> System.gc(); ---for running GC thread.
How can an object be unreferenced?
There are many ways:
By nulling the reference
By assigning a reference to another
By anonymous object etc
finalize() method
The finalize() method is invoked each time before the object is garbage collected.
This method can be used to perform cleanup processing. This method is defined in
Object class as:
protected void finalize(){}
Note: The Garbage collector of JVM collects only those objects that are created by
new keyword. So if you have created any object without new, you can use finalize
method to perform cleanup processing (destroying remaining objects)
gc() method
The gc() method is used to invoke the garbage collector to perform cleanup
processing. The gc() is found in System and Runtime classes.
public static void gc(){}
Note: Garbage collection is performed by a daemon thread called Garbage
Collector(GC). This thread calls the finalize() method before object is garbage
collected.
Note: Neither finalization nor garbage collection is guaranteed.
-------------------------------------------------------------------------