Features and Components of Java
## Platform Independent
write once, run anywhere (WORA)
Can be run multiple system without recompilation.Java code is compiled into byte-code,to be executed by a virtual machine.
JVM is machine dependent
## Object orientation
In real life , state and behavior are tied to an object .Java emulates real life object definition and behavior .
it uses classes , interfaces ,or enums to define all its code.
## Abstraction
Something only existing as an idea .
Basic idea is hiding the implementation details
while just presenting the features to the outside world. open for interpretation .
## Encapsulation
we can encapsulate state and behavior of an object .state or fields of class are protected from unwanted
access and ,manipulation.
Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the data (methods) together as a single unit.
In encapsulation, the variables of a class will be hidden from other classes, and can be accessed only through the methods of their current class.
Therefore, it is also known as data hiding.
To achieve encapsulation in Java −
Declare the variables of a class as private.
Provide public setter and getter methods to modify and view the variables values.
## Inheritance (Saves from redefining common code)
Inheritance is the object oriented programming concept where an object is based on another object.
Inheritance can be defined as the process where one class acquires the properties (methods and fields) of another.
Inheritance is the mechanism of code reuse.
With the use of inheritance the information is made manageable in a hierarchical order.
classes can inherit other classes and implementing interfaces.
interfaces can inherit other interfaces .
We use extends keyword in java to implement inheritance
## Polymorphism
Java enables instances of its classes to exhibit multiple behaviors for the same method calls.
concept by which we can perform a single action by different ways.
Polymorphism is the ability of an object to take on many forms.
Polymorphism is the concept where an object behaves differently in different situations. There are two types of polymorphism –
compile time polymorphism and runtime polymorphism.
Compile time polymorphism is achieved by method overloading
Runtime polymorphism is implemented when we have “IS-A” relationship between objects. This is also called as method
overriding because subclass has to override the superclass method for runtime polymorphism. If we are working in terms
of superclass, the actual implementation class is decided at runtime. Compiler is not able to decide which class method
will be invoked. This decision is done at runtime, hence the name as runtime polymorphism
Bank b;
b=new SBI();
System.out.println("SBI Rate of Interest: "+b.getRateOfInterest());
b=new ICICI();
System.out.println("ICICI Rate of Interest: "+b.getRateOfInterest());
b=new AXIS();
System.out.println("AXIS Rate of Interest: "+b.getRateOfInterest());
## Type Safety
## Automatic memory management
## Support multi-threading and concurrency
## Security
secure class loading
cryptography and public key infrastructure
from encapsulation and data hiding - secure the objects state
#It is important to know that the only possible way to access an object is through a reference variable.
A reference variable can be of only one type. Once declared, the type of a reference variable cannot be changed.
public interface Vegetarian{}
public class Animal{}
public class Deer extends Animal implements Vegetarian{}
Now, the Deer class is considered to be polymorphic since this has multiple inheritance. Following are true for the above examples −
A Deer IS-A Animal
A Deer IS-A Vegetarian
A Deer IS-A Deer
A Deer IS-A Object
When we apply the reference variable facts to a Deer object reference, the following declarations are legal −
Example
Deer d = new Deer();
Animal a = d;
Vegetarian v = d;
Object o = d;
All the reference variables d, a, v, o refer to the same Deer object in the heap
# Method is overridden not the datamembers, so runtime polymorphism can't be achieved by data member
class Bike{
int speedlimit=90;
}
class Honda3 extends Bike{
int speedlimit=150;
public static void main(String args[]){
Bike obj=new Honda3();
System.out.println(obj.speedlimit);//90
}
## Irrelevant features of java
#Single thread language -(java is multi-threaded language)
## .java file - source code file , .class file - byte code file
# every entity can't use , every access modifier
# access modifier (control the accessibility of our class and its methods and variables ,outside the class and package)
public , protected , default , private
# Non access modifier(Change the default behavior of class and its members)
abstract , final , static
# Abstract class can't be instantiated .
Interface is abstract by default
Abstract method doesn't have a body , it is implemented by derived class .No {}... public abstract newMethod()
None of variable type can use with abstract
Abstract classes may or may not contain abstract methods, i.e., methods without body ( public void get(); )
But, if a class has at least one abstract method, then the class must be declared abstract.
public abstract class Employee
If you want a class to contain a particular method but you want the actual implementation of that method to be determined by child classes,
you can declare the method in the parent class as an abstract.
public static void main(String [] args) {
Salary s = new Salary("Mohd Mohtashim", "Ambehta, UP", 3, 3600.00); //Salary is , extended by Employee classs
Employee e = new Salary("John Adams", "Boston, MA", 2, 2400.00); // Employee is abstract class
System.out.println("Call mailCheck using Salary reference --");
s.mailCheck(); //S METHOD
System.out.println("\n Call mailCheck using Employee reference--");
e.mailCheck(); //salary method
}
# Salary s = new Salary("Mohd Mohtashim", "Ambehta, UP", 3, 3600.00);
Employee e = new Salary("John Adams", "Boston, MA", 2, 2400.00);
Here, we instantiate two Salary objects. One using a Salary reference s, and the other using an Employee reference e
mailCheck() on e is quite different because e is an Employee reference. When the compiler sees e.mailCheck(),
the compiler sees the mailCheck() method in the Employee class.
Here, at compile time, the compiler used mailCheck() in Employee to validate this statement. At run time,
however, the JVM invokes mailCheck() in the Salary class.
This behavior is referred to as virtual method invocation, and these methods are referred to as virtual methods.
An overridden method is invoked at run time, no matter what data type the reference is that was used in the source code at compile time.
# final can be use with class , variables , methods . Can't be use with interfaces .
Final class can't be extend
final variables can't reassign after assign values.(Can't assign objects again , but can call methods , that change state )
final methods defined in base class can't be override by a derived class
# static modifier can use with variables , methods , classes , interfaces
Static variables belongs to class . Static attributes can be access even , when no instances of class have been created.
static and final can be use >>> static final int x = 0 ;
static methods are associated not with objects and cant use any of instance variables of class.
Instance variables are used by Objects to store their states. Variables which are defined without the STATIC keyword and are Outside any
method declaration are Object specific and are known as instance variables. They are called so because their values are instance specific
and are not shared among instances.
# non-private static variables and methods are inherited by derived classes .The static members aren't involved in run-time polymorphism .
You can't override the static members in a derived class , but you can redefine them .
# neither static methods nor static variables can access the non static variables and methods of a class. but reverse is true ,
because static members of a class exist even if no instances of a class exist.
Both static variables and methods belong to a class and not to an instance. we can use them using variables , which initialized to null.
no run time exception
you can access static variables and methods using a null reference .
you can't prefix the definition of a top level class or an interface with the keyword static .
this is ok
class Person{
static class Address{}
static interface MyInterface{}
}
#primitive variable - uses primitive data type 8
char (16 bit ) ,byte , short , int , long, float , double , boolean
#Category Boolean is not the same as the primitive data type boolean or wrapper class Boolean .
#primitive data types can be categorized as follows . Boolean , character and numeric
# Java is strongly typed language
# Signed numeric - INTEGERS (Byte , int short , long) - whole numbers , include both negative and positive
byte - 8 bits -128 to 127
short - 16 bits - 32,768 to 32, 767
int - 32 bits - 2,147,483,648 to 2,147,483,647
long - 64 bits ....
# default type of a nondecimal number is int.
long lingNum = 4345565L ; or 454556l;
# Integer literal values comes in four flavors. binary 2, octal 8, decimal 10 and hexadecimal 16.
# you can assign integer literal in base decimal,
binary (use OB or Ob prefix ),
octal (use prefix o)
hexadecimal(use OX or ox prefix)
int basedecimalValue = 267 ;
int octVal = 04213;
int hexadecimalValue = ox10B
int binVal = ob10100101
#java 7 - use of underscores as part of literal values.
#you can place and underscore right after the prefix o , which is used to define an octal literal value .
#you can't start or end a literal value with an underscore .
#you can't place an underscore right after the prefixes Ob , OB and OX which are used to define binary and
hexadecimal literal value
#you can't place an underscore prior to an L suffix
#you can't use an underscore in positions where a string of digits is expected .
int i = Integer.parseInt("45_98") ; run time error
#By default , S.o.p wil print out a number in its decimal base , regardless of the base number system that
you use to initialize number
#float 32 bits - use of the suffixes F and f , while initializing the variables .
# you can use D or d suffixes , but not necessary
# in java 7 >> new law instead early mentioned >> you can't place an underscore
adjacent to a decimal point .
ex:- 100._47F or 100_.56;
#Internally ,Java stores char data as an unsigned inter value (positive integer )
char c = 112 ; //acceptable , can't use negative numbers .
#But you can forcefully assign a negative number to a char type by casting it to char
char c3 = (char)-122 ;
S.o.p(c3) >>>.-122
#int and char are shortened.
# can use currency sign at any position £ $ and others
# Can't starts with a number
#goto key word , can't use keywords
# can't use hyphen -
# Two type variables
- primitive variables
- reference variables (object reference variable)
#object reference is , in fact ,a memory address that points to a memory area where an
object's data is located.
#when an object is instantiated with the new operator , a memory address value to that
object is returned .that address is usually assigned to the reference variable.
# Person newPerson = new Person()
1. a new newPerson object is created (in heap memory)
2 . a variable named person is created in the stack with an empty(null) value .
3. variable newPerson is assigned the memory address(stack memory) value where the object is located.
# java objects that's not referred to any object reference variable is liable to be garbage collected (removed from memory by the JVM)
#default value of all types of object reference variable is null
Person objPerson = null;
iN this case reference variable objPerson can be compared to a leash without a dog.
#primitive variables store actual values , where as reference variables store the addresses of the
objects they refer to .
#To compare reference variable, use the == operator. To comapre the objects I(reference variable) refer to ,use the equals()
method.
#for primitive values uses == , for determine equality //memory value allso consider , without using new operator its ok
#if reference variable ,don't refer its object further then garbage collector
#primitive values are not marked for garbage collection
#+= ,-=,*=,/=
#a = b = 10 ;
#long lnum = 11123444444L ;
int num = lnum ; //Compilation error
#int a = 7 , b = 5 ;
a = b =c // assignment starts from right to left
#++ , -- unary operator works with variables , but not with literal value
#when you apply the addition operator to char values, their corresponding ASCII
values are added and subtracted.
char char1 = 'a'
S.o.p.(char1 ); //a
S.o.p.(char1 + char1); //194
you can use all arithmatic operators with char primitive data type , including unary increment and decrement operators.
# all byte , short and char values are automaticaly widened to int when used as operand as arithmatic operations .
If long valu is involved somewhere , then every thing widened to long.
if it includes float or double , then widned to double .
byte num1 = 10 ;
byte num2 = 20 ;
short sum = num1 + num2 ;//compilation error
# final byte num1 = 10 ;
final byte num2 = 20 ;
short sum = num1 + num2 ;//compile successfully
#unary operators
int a = 20 ;
int b = 10 ;
++a ;
b++;
S.o.p(a);//21
S.o.p(b);//11
int a = 10 ;
a = a++ +a + a -- + ++a;
a = 10 + 11 + 11 +11
= 43
## Relational Operators .
> ,>= , < , <=
== , !=
## int a = 13 ;
int b = 8 ;
S.o.p(a=b); // 8
## && , || logical operators >>> short circuit operator >>> && if first operand false ,then false .
|| first operand true >> then true . don't evaluate second.
## S.o.p(total < marks && ++marks > 5);
## all relational and logical operators return a boolean value
## Operator Precedence
POSTFIX >>>> experession++ , experession--
unary >>>> ++experession ,--experession , +experession , -experession , !
multiplication >>>> * , / , %
addition >>>> + , -
relational >>>> < , > , <= , >=
equality >>>> == , !=
Logical AND >>>> &&
Logical OR ||
Assignment = , += , -= , *= , /= ,%=
## You can use parentheses to override the default operator precedence.
inner parentheses are evaluated prior to the outer ones.
##Java defines wrapper class for each of its primitive data types
wrapper classes are used to wrap primitives in an object, so they
can added to a collection object . They enable all types to be
treated like object instances .Wrapper classes help us to write cleaner
code .
##All the wrapper classes are immutable - classes that don't allow changes to the state
of their instances after initialization.
## Object Serializable Comparable
Boolean Character Number
Byte Short Integer Long Float Double
##All the numeric wrapper classes extend the class java.lang.Number. Classes Boolean and
Character directly extend the class object
All the wrapper classes implement the interfaces java.io.Serializable and java.lang.Comparable
All these classes can be serialized to a stream .
##wrapper classes are immutable.Adding a primitive value to wrapper
class variable doesn't modify the value of the object it refers to.
The wrapper class variable is assigned a new object
##You can create objects of all the wrapper classes in multiple ways .
1. Assignment ---- By assigning a primitive to a wrapper class variable (Autoboxing )
Boolean blOne = true ;
Character charVar = 'a';
2.Constructor ----- using wrapper class constructors
Boolean bool = new Boolean(true);
Byte byte2 = new Byte((byte)10);
3.Static metogds ---- By calling static method of wrapper classes, like valueof()
Boolean bool1 = Boolean.valueOf(true);
Boolean bool2 = Boolean.valueOf(true);
Boolean bool3 = Boolean.valueOf("True");
##Method to retrieve primitive vlaues from wrapper classes .
Boolean Character Byte , Short , Integer , Long , Float , Double
booleanValue() charValue() byteValue() shortValue() intValue() longValue() floatValue() doubleValue()
Integer obj = new Integer(15);
// returns the value of this Integer as an int
int i = obj.intValue();
##Each wrapper class (except Character) defines a method to parse a string to the corresponding
primitive value .
public static boolean parseBoolean(String s);
public static byte parseByte(String s);
public static short parseShort (String s);
public static int parseInt(String s);
public static long parseLong(String s);
public static double parseDouble(String s);
public static float parseFloat(String s);
#Long.parseLong("12344");
Boolean.parseBoolean("true");
Boolean.parseBoolean("TRue") ; //String argument is not case sensitive
#The valueOf() method returns an object of the corresponding wrapper class when it's passes an argument
of a primitive type or String .
#Wrapper classes Byte, Short , Long ,Integer cache objects with values in the range of -128 to 127 .the
Character class caches objects with values 0 to 127. These classes define inner static classes that store
objects for the primitive values -128 to 127 or 0 to 127 in an array .If you request an object of any of these
classes, from this range, the valueOf method returns to a predefined object . Otherwice ,it creates
a new object and returns its reference.
Long var1 = Long.valueOf(123);
Long va2 = Long.valueOf("123");
S.o.p(var1 == var2);//True
Long var3 = Long.valueOf(223);
Long var4 = Long.valueOf(223);
S.o.p(var3 == var4);//false
#Wrapper classes Float and Double don't cache objects for any range of values .
#In the case Boolean class , the cached instances are accessible directly because
only two exist:static constants Boolean.TRUE and Boolean.FALSE .
#Comparing objects of wrapper classes
compare objects of wrapper classes for equality by using the method equals or the comparison operator , that is ==.
Method equals() always compares the primitive value stored by a wrapper instance , and == compares object references .The
operator == returns true if the variables being compared to refer to the same instance.
#Depending on how you intialize wrapper instances , they might or might not refer to the same instances.
Integer i1 = new Integer(10); //Construction always create new instances .
Integer i2 = new Integer(10);
Integer i3 = Integer.valueOf(10);//valueOf returns a cached copy for Int value 10 .
Integer i4 = Integer.valueOf(10);
Integer i5 = 10 ;
Integer i6 = 10 ; //Autoboxing returns a cached copy for applicable values.
S.o.p(i1 ==i2); //false
S.o.p(i3 ==i4); //true
S.o.p(i4 ==i5); //true
S.o.p(i5 ==i6); //true
S.o.p(i1.equals(i2); //true
S.o.p(i3.equals(i4); //true
S.o.p(i4.equals(i5); //true
S.o.p(i5.equals(i6); //true
#But the same isn't applicable for Integer instances created for int value 200 and
compared using == (Because they aren't stored in the Integer cache ).
Integer i1 = new Integer(210); //Construction always create new instances .
Integer i2 = new Integer(210);
Integer i3 = Integer.valueOf(210);//valueOf returns a cached copy for Int value 10 .
Integer i4 = Integer.valueOf(210);
Integer i5 = 210 ;
Integer i6 = 210 ; //Autoboxing returns a cached copy for applicable values.
S.o.p(i1 ==i2); //false
S.o.p(i3 ==i4); //false
S.o.p(i4 ==i5); //false
S.o.p(i5 ==i6); //false
S.o.p(i1.equals(i2); //true
S.o.p(i3.equals(i4); //true
S.o.p(i4.equals(i5); //true
S.o.p(i5.equals(i6); //true
##The comaprison operator == compares reference variables - checking
whether they refer to the same instance.
#####
StringBuilder objects are like String objects, except that they can be modified. Internally, these objects are treated like
variable-length arrays that contain a sequence of characters. At any point, the length and content of the sequence can be
changed through method invocations.should always be used unless string builders offer an advantage in terms of simpler code
(see the sample program at the end of this section) or better performance. For example, if you need to concatenate a large
number of strings, appending to a StringBuilder object is more efficient.
// creates empty builder, capacity 16
StringBuilder sb = new StringBuilder();
void setLength(int newLength) Sets the length of the character sequence. If newLength is less than length(),
the last characters in the character sequence are truncated. If newLength is greater than length(), null characters are added
at the end of the character sequence.
void ensureCapacity(int minCapacity) Ensures that the capacity is at least equal to the specified minimum.
A number of operations (for example, append(), insert(), or setLength()) can increase the length of the character sequence in
the string builder so that the resultant length() would be greater than the current capacity(). When this happens, the capacity is automatically increased.
StringBuilder append(char[] str, int offset, int len )
StringBuilder append(Object obj)
StringBuilder delete(int start, int end)
StringBuilder deleteCharAt(int index)
The first method deletes the subsequence from start to end-1 (inclusive) in the StringBuilder's
char sequence. The second method deletes the character located at index.
StringBuilder insert(int offset, boolean b)
StringBuilder insert(int offset, char c)
StringBuilder insert(int offset, char[] str)
StringBuilder insert(int index, char[] str, int offset, int len)
StringBuilder insert(int offset, double d)
StringBuilder insert(int offset, float f)
StringBuilder insert(int offset, int i)
StringBuilder insert(int offset, long lng)
StringBuilder insert(int offset, Object obj)
StringBuilder insert(int offset, String s)
StringBuilder replace(int start, int end, String s)
void setCharAt(int index, char c)
Replaces the specified character(s) in this string builder.
StringBuilder reverse() Reverses the sequence of characters in this string builder.
https://docs.oracle.com/javase/tutorial/java/data/buffers.html
## memebers of an array are defined in continous memory locations ,
hence improved memory access.
References Used :- OCAJP 8 By Mala Gupta
:- oops-concepts-java-example - journaldev