Java Basics
Java Basics
• }
• }
• //for numbers + symbol acts as arthemetic operator
• //for non numerics +symbol acts as concatenation operator
loops
• Java’s iteration statements are
• For
• While
• Do-while
Arrays
• Grouping the data objects of same type in a
contiguous block of memory.
• Array is an object created with new operator.
• Array index starts with zero.
• Array size cannot be resized.
Array Declaration and Instantiation
-> Array Declaration:
<Data type> [ ]<array name >
Ex: int[] myArray;
ppublic class A {
int add(int i,int j) {
return( I + j);
}
}
public class B extends A {
public static void main(String args[]) {
B b =new B();
int s= 9 ;
System.out.println(b.add(s, 6 ));
}
}
Static/NonStatic members works
when ever a java program is executed .....the
following steps happen
i)memory is allotted for execution
ii)and this memory is divided into heap and
stack
iii)java enter into stack and calls class loader
iv)the class loader loads static members of
class into heap memory.
v)all static members of class reside in an area called static pool
vi)java calls main methods for execution
vii)main method enters into stack on top of java
viii)when ever a object creation statement encounters , object will get
created into heap.
ix)on that time, the non static members of the class will be loaded into
object.
x)we can create multiple objects of a class .for each object creation a
copy of non static members will be loaded.
xi)after the completion of main method , the JVM calls garbage collection
to clean the heap.
xii)After that java releases the memory back to main memory
xiii)local variables are created in the stack and the life of the variable is
as long as the method is in the stack.
java gives preferences to local variables.
xiv)if any object does not have a reference then such object are known
as abundant object.
Object and Object References
• Object is the instance of class.
• Object Reference is the information on how to find
the object.
• A Single object can have more than 1 object
references.
EX : 2 objects[java,C+ +)] 2 reference
objects(Str1,Srtr2).
String Str1=new String(“Java”);
String Str2=new String(“C+ + “);
EX : 1 object with 2 object references
String Str1=new String(“Java”);
String Str2=Str1;
Call By Value
• Passing a value held in the variable as an
argument to the method.
• The value is copied to method parameters and
changes takes place to that parameters.
• That is why changes made to the variable
within the method had no effect on the
variable that was passed.
Call By Reference
• The Object is passed as an argument to the
method.
• No copy of object is made here.
• Changes made in the method will be reflected
in the original object
constructors
• It can be tedious to initialize all of the variables in a class each
time an instance is created.
• it would be simpler and more concise to have all of the setup
done at the time the object is first created.
• Java allows objects to initialize themselves when they are
created. This automatic initialization is performed through
the use of a constructor.
• Constructor is a special block in java class invoked at the time
of object creation
• Constructor should always be public
• A constructor name is same as class name ,the constructor
should not have return type and return statement
• Whenever we create an object , the constructor body will get
executed.
Difference between constructor and
method
Method constructor
• Method can be executed • Constructor gets executed
when we explicitly call it. only when object is created
• Method name will not have • Constructor name will be
same name as class name same as class name
• Method should have return • Constructor should not
type have return type
• A method can be executed • Constructor will get
n number of times on a executed only once per
object object
Super keyword
• Using super keyword
• We can call immediate super class instance
variable.
this
1.this keyword can be used to refer current class instance
variable.
2.this() can be used to invoke current class constructor
3.this keyword can be used to invoke current class method
(implicitly).
4.this can be passed as an argument in the method call
5.this can be passed as argument in the constructor call
6.this keyword can also be used to return the class instance.
7.We cannot use this and super at a time
final
• Final is the keyword to avoid inheritance
• We use final in three ways
1.Before a variable(you can’t change)
2.Before a method (you can’t over ride)
3.Before a class(you can’t inherit)
Inheritance
• Deriving members of one class to another class is known as inheritance.
• The class from where member s are inherited are known a super class or
base class
• The class to which members are inherited are known as subclass or
derived class
• The general syntax to write inheritance class
• Class SubClassName extends SuperClassName
• Using extends keyword a class can inherit from super class
• Always inheritance happens from super class to subclass.
• Static members of the super class will not be inherited to subclass
because the static members will not be loaded into object memory
• Whenever an object of subclass is created both super class member and
sub class member will be loaded into object
• Inheritance happens through constructor chain.
Inheritance contd…
• Whenever an object of sub class is created
,the subclass constructor calls super class
constructor ,the super class constructor calls
its super class constructor . this is known as
constructor chain.
Types of inheritance
• There are 3 types of inheritance
• Single
• Circular(no prg supports )
• Multiple (java does not support)
a A B
A
b c
B C
Interface
• Java supports 3 different structures
1. Fully implemented
2. Fully unimplemented
3. Partly implemented/unimplemented
• Interface contains abstract methods(with no body)
• Interface is an fully unimplemented structure
• We need to provide body for all methods in interface
• In interface, we cannot create the object of interface
• Can contain constants, but not variables
• All methods, variables are public static final
Interface
• It is a class with no implemented methods
• Interface must not be static
• It contains only declarations
• Methods in interface must be static
• All variables must be assigned a value
• Interface variables are static ;we cannot change values
• Interface methods are neither static nor non static
• Creating interface reference ,we can access implemented
class methods which are defined in interface class but not
methods defined in implemented class.
Abstract class
• It is partly unimplemented or partly
implemented class which contains zero or
more abstract methods
• Concrete method is the method with body
• Abstract method is the method with out body
• If user want to inherit the abstract class;he
need to extend but not implement
Difference between interface and
abstract class
interface Abstract class
• Fully unimplemented • Partly implemented or
structure that contains all unimplemented structure
abstract metods
• Can contain variables
• Interface contains only
constants • Can contain constructors
• The object of interface can’t • Abstract class object get
be created directly created automatically when
,anomous class is recquired sub class object got created
to create object for this • Uses “extends”
class
• Uses “implements “
Overloading and over riding methods
• Redefining method of parent class with the
same name in child class is method over riding
• Redefining same method with different
parameters is called method overloading
• Note:
1.Reference type determines which overloaded
method is used at compile time.
2.Object type determines which over riden
method is used at runtime.
Over loading
• Overloading is about creating multiple methods with the
same name, but different signatures, in the same scope.
• overloading can take place in the same class or in the
subclass.
• overloaded methods MUST have a different argument
list.
• overloaded methods MAY change the return type (in
case argument list is different).
• overloaded methods MAY change the access modifier.
• reference type determines which overloaded method
will be used at compile time.
• constructors MAY be overloaded .
Over Riding
• Overriding is about changing the behavior of a certain method in
the child class from the way it is behaving in the parent class.
• Applies ONLY to inherited methods
• is related to polymorphism
• object type (NOT reference variable type) determines which over
riden method will be used at runtime
• overriding method MUST have the same argument list (if not, it
might be a case of overloading)
• Abstract methods MUST be overridden
• Final methods CANNOT be overridden
• Static methods CANNOT be overridden
• Constructors CANNOT be overridden
Packages
• Java Package is a mechanism for organizing Java
classes in to a namespace.
• Classes present in the package can access the
each others class members.
• We are going to import classes from the package.
• Package name usually starts with lower case.
• Classes within a package can access classes and
members declared with default access and class
members declared with the protected.
Access Control Modifiers
Java provides a number of access modifiers to
set access levels for classes, variables,
methods and constructors. The four access
levels are:
• Default:-Visible to the package. No modifiers
are needed.
• Private:-Visible to the class only .
• Public:-Visible to the world.
• Protected:-Visible to the package and all
subclasses.
Non Access Modifiers
Java provides a number of non-access modifiers
to achieve many other functionality.
• The static modifier for creating class methods
and variables
• The final modifier for finalizing the
implementations of classes, methods, and
variables.
• The abstract modifier for creating abstract
classes and methods.
• The synchronized and volatile modifiers, which
are used for threads.
Exception Handling
->Exception is an Event which halts normal execution
abruptly and alternatively the program will be
terminated.
• Exception occurs when our code asks JVM to do
technically impossible tasks.
• Ex:Divide by Zero.
• All Exception classes are subclasses of Throwable.
• Throwable has two subclass :Exception and Error
contd
Types of Exception
1)Checked Exception: A checked exception is an exception
that is typically a user error or a problem that cannot
be foreseen by the programmer.
EX: If a file is to be opened, but the file cannot be found, an
exception occurs
2)A runtime exception is an exception that occurs that
probably could have been avoided by the programmer.
EX:ArrayIndexOutOfBoundException
63
Keywords of Exception
• Try
• Catch
• Throw
• Throws
• finally
Try-Catch block
• In this mechanism Try block will contain the
code which may throw the exception.
• Catch block will declare the type of exception
occurred.
• EX:try{ }
catch(Exception E){ }
Throws-Throws
• If a method does not handle a checked exception,
throws keyword should be used at the end of a
method's signature.
• To explicitly throw the exception of a newly
instantiated one or an exception that you just
caught, we use Throw keyword.
• EX: public void deposit(double amount) throws
RemoteException { // Method implementation throw
new RemoteException(); } //Remainder of class
definition }
Finally
• The finally keyword is used to create a block
of code that follows a try block. A finally block
of code always executes, whether or not an
exception has occurred.
• A finally block appears at the end of the catch
blocks .
Collections
• Collection is a set containing the classes and
interfaces which implements reusable data
structures like List,Array,HashTable.
• There are so many interfaces available like
java.util.ArrayList;
java.util.Iterator;
java.util.List;
java.util.ListIterator;
Array List
1)We are Creating the ArrayList as
ArrayList<String> list = newArrayList<String>();
2)To add elements to the list is
list.add("A");
List.add(2,”S”);//index=2
3)To get the element from list
list.get(index).
stack
• Stack is a subclass of Vector that implements a
standard last-in, first-out stack.
• boolean empty()
• Object peek( )
• Object pop( )
• Object push(Object element)
• int search(Object element)
HashTable
• The java.util.Hashtable class implements a
hashtable, which maps keys to values.
• Hash function will compute unique value as a
index to the key.
• Methods are:
• Set<Map.Entry<K,V>> entrySet()
• Collection<String> collection =ht.values();
• Set<String> set1 =ht.keySet()
Linked HashSet
• Linked HashSet maintains a list of the entries
in the set, in the order in which they were
inserted. This allows insertion-order iteration
over the set.
• The values will be retrieved in same order of
insertion using iterator.
Reflection API