This presentation is ideal for a beginner of Java or someone who wants to brush up their Java Knowledge. It's simple to understand and well organized in a way most of the area in core Java has been covered.
2. Prerequisites
For this you should have a basic knowledge of Object Oriented Principles (OOPs).
Let’s start with the basics
Object
A real world Entity which has a state and a
behavior
Class
A class is a collection of Objects. It serves as
a template for creating, or instantiating,
specific objects within a program.
E.g:- A Car class can have a model, color, manufacturedYear as
state and drive, reverse as behaviours. Ferrari is a real world
Object that we can create from that class
3. Fundamentals of OOP
▪ Abstraction – Hiding Internal details and showing only the functionality
Abstract classes, Interfaces are ways of achieving this
▪ Encapsulation – Binding and wrapping code and data together
Java class (having private fields and public accessors,mutators) are an
example for this
▪ Polymorphism – One task is performed in different ways
Method overriding and overloading are ways to achieve this
▪ Inheritance – One object acquires all the propertiese and behaviours of a parent
object
- Inheritance provides code reusability and used to achieve runtime polimorphism
- Java doesn’t allow multiple inheritance
4. Features of Java
Simple
Syntax is based on C++
Many confusing features are removed (e.g: pointers, Multiple inheritance)
Not required to remove unreferenced objects since Automatic Garbage Collection
is there
Portable
Write Once Run Anywhere (WORA)
Distributed
RMI and EJB are used to create distributed Apps
Multi Threaded
Object Oriented
Platform Independent
Java code is compiled by the compiler and converted into bytecode. This is
platform independent thus can be run on multiple platforms
Secured
No pointers
Program run inside Virtual machine sandbox
Robust
Strong (e.g:- uses strong memory management AGC)
7. Basic Structure of a Java
program
public class HelloWorld{
public static void main(String[] args){
System.out.println(“Hello World”);
}
}
Access modifier Class name Method name
Argument
list(expects an
array of String
arguments)
System is a final class in the java.lang package
Out is a static member of System class and is an instance
of java.io.PrintStream
Println is a method available in java.io.PrintStream class
Here the println() method in the PrintStream class is
overridden
8. Few important keywords in
Java
▪ Variable - A Java variable is a piece of memory that can contain a data
value. A variable thus has a data type.
▪ Data Type – They further explain the kind of data that needs to be stored
e.g :- int, char
▪ Literals – Source code representation of a fixed value
e.g :- int age=20;
▪ Default Values – If variables are not assigned with a value then compiler
will add a value automatically
e.g :- default value for String is null, default value for boolean is false
Identifiers – Name of the variable
Keywords – Reserved words in java
9. ▪ short
▪ byte
▪ int
▪ long
▪ double
▪ float
▪ char
▪ boolean
Basic Data Types in Java
Data Types
Primitive Data Types Reference Data Types
▪ Objects such as String,
Array, HashMap etc.
▪ Default value is null
▪ Reference can be used to
access the object
integer types
floating points
13. Decision making in java
If
e.g:-
if(num%2 ==0){
//print even
}
If-else
e.g:-
if(num%2 ==0){
//print even
}
else{
//print odd
}
If- else if - else
e.g:-
if(num%2 ==0){
//print even
}
else if(num%2 !=0){
//print odd
}
else{
//print invalid input
}
switch
e.g:-
char grade=‘A’;
switch(g){
case ‘A’ : //print ‘Pass’
break;
case ‘F’ : //print ‘Fail’
break;
default: //print ‘Invalid’
}
14. Loops in Java
while
e.g:-
int x=0;
while(x<words.length){
//print words[x]
x++;
}
do-while
e.g:-
int x=0;
do{
//print words[x]
x++;
} while(x<words.length);
for
e.g:-
for(int x=0 ; x<words.length ; x++){
//print words[x]
}
foreach
e.g:-
for(String word : words){
//print word
}
String words[]={“apple” , “banana”, “grapes”};
15. Break and Continue
keywords in Java
Break
e.g:-
int x=0;
while(x<words.length){
if(words[x].equals(“banana”)){
break;
}
else{
System.out.println(words[x]);
}
x++;
}
Continue
e.g:-
int x=0;
while(x<words.length){
if(words[x].equals(“banana”)){
continue;
}
else{
System.out.println(words[x]);
}
x++;
}
String words[]={“apple” , “banana”, “grapes”};
apple apple
grapes
OUT
16. Constructors in Java
Constructor is a special type of method that is used to initialize the object
There are rules to define a constructor
- Constructor name must be as same same as the class name
- Must not have an explicit return type
There are two types of Constructors in Java
- Default constructor
- Parameterized constructor
If there is no constructor in a class, compiler will automatically create a
default constructor
Defaulot construtor will set default values for class variables wheras if
you want to set values of your own then go for a parameterized
constructor
17. Constructor Overloading in
Java
A class can have any number of Constructors
Number of parameters and type of them differentiate each one another
e.g:-
18. Ways to copy objects in
Java
There are three ways to copy one object to another in java
1. Copy by constructor
19. Ways to copy objects in
Java...
2. By assigning values of on object to another
20. Ways to copy objects in
Java...
3. By clone() method of Object class
21. Method Overloading in java
If a class have multiple methods by same name but different parameters it
is known as ‘Method Overloading’
Method Overloading increaces the readability of the program
There are two ways that we can overload methods
- By changing the no of arguments
- By changing the data type
24. Method Overloading in
java…
Can we overload methods by changing their return types?
NO, method overloading cannot be achieved by changing the return type of
the methods.
e.g:- int sum(int a, int b){};
double sum(int a, int b){};
int result=sum(10,30); //Compile time error!
Can we overload main() method of a java program?
YES. You can have any number of main methods in your java class through
method overloading. This is achieved by changing the parameters of the
main method
25. Method Overloading & Type
promotion
One type is promoted to another type implicitly if no matching data type is
found
byte
short
int
long
char float
double
Since no method with two int arguments are found, the compiler will automatically
considers the method with int, double (second int literal will be promoted to double)
26. Method Overriding in Java
If subclass provides the specific implementation of the method that has
been provided by one of its parent class, it is known as method overriding
in java.
Method overriding is used for runtime polymorphism
Rules for method overriding in Java
- Method must have the same name as in the parent class
- Method must have same parameter as in the parent class
- There must be an IS-A relationship (inheritance)
We can override methods by changing their return type only if their
return type is covariant (subtype of the super method’s return type)
27. Method Overriding in
Java… Example
•
• run() method is overridden in Bike
class with its own implementation
• super keyword is used to access
the parent class method
• During runtime it decides which
method to invoke. This is called
runtime polymorphism
• Static methods cannot be
overridden in java
• Thus main() method cannot be
overridden.
28. Method Overriding Vs
Method Overloading
Method Overloading Method Overriding
Used to increase the readability of the program Used to provide the specific implementation of the
method that is already provided by its super class
Is performed within the class Occurs in two classes that have an IS-A
relationship (Inheritance)
In case of method overloading, parameter must be
different
In case of method overriding, parameter must be
same
Is an example for compile time polymorphism Is an example for runtime polymorphism
In Java, method overloading cannot be performed
by changing the return type. Return type must be
same or different but you have to change the
parameter
Type must be same or Covariant in method
overriding
29. ‘Super’ Keyword in Java
Super is a reference variable that is used to refer immediate parent class
Object
e.g:- When you create a Student object, a Person
object also being created automatically.
There are three main usages of ‘super’ key word in Java
Person
Student
30. ‘Super’ Keyword in Java…
1. ‘super’ is used to refer immediate parent class instance variable
31. ‘Super’ Keyword in Java…
2. super() is used to invoke immediate parent class constructor
32. ‘Super’ Keyword in Java…
3. Super is used to invoke immediate parent clas method
33. Access Modifiers in Java
Access Modifier Within Class Within Package
private Yes No
Default Yes Yes
Protected Yes Yes
Public Yes Yes
Note that there is no keyword call Default. A variable/
method defined without any access modifier is a
variable to any other classes in the same package.
E.g:- the fields of an interface are implicitly public static
final, the methods of an interface are by default public
Can’t apply to classes and interfaces . Fields and
methods that are marked as protected in a superclass,
only its subclasses can access them.
34. Access Modifiers in Java…
Where to use protected access modifier?
• If the openSpeaker() method is
marked as public, then any class
can access it.
• If openSpeaker() method is marked
as private then it is accessible only
within the AudioPlayer class
• To allow only its subclasses to use
it, we have to mark it as protected
35. Access control and
Inheritance
These rules must be enforced in inheritance
Methods declared public in super class must be marked as public in all of
its subclasses
Methods declared protected in super class can either be marked as
protected or public in its subclasses
Methods declared private are not inherited at all, so theres no rule for
them.
36. Arrays in Java
Java Array is an object that contains similar type of data
We can store a fixed set of elements in Java Array
Array in Java is indexed based, first element is stored at index 0.
0 1 2 3 4 indicesFirst index
Array length
37. Arrays in Java…
Advantages of Java Array
Code optimization (we can retrieve or sort data easily)
Random Access
Disadvantages
Size limit – we can store only fixed size of elements in java array. It
doesn’t grow as we store elements at runtime
Types of Arrays in Java
1. Single dimensional Array
2. Multidimensional Array
38. Arrays in Java…
Declaration syntax for single dimensional Array
dataType[] arr;
dataType []arr;
dataType arr[];
Declaration syntax for multi dimensional Array
dataType[][] arrayRefVar;
dataType [][]arrayRefVar;
dataType arrayRefVar [][];
dataType []arrayRefVar [];
39. Arrays in Java…
Initializing Single dimensional
Arrays in Java
int arr;
arr=new int[10];
arr[0]=23;
arr[1]=54; etc…
OR
int arr[]={23,54};
Initializing Multi dimensional
Arrays in Java
int[][] arr;
arr=new int[3][3];
arr[0][0]=10;
arr[0][1]=30;
OR
Int arr[][]={{1,2,3},{4,6,7}, …};
40. Collection Framework in Java
Collection in java is a framework that provides an architecture to store
and manipulate the group of Objects
Java collection framework provides many interfaces e.g:- Set, List, Queue,
Dequeue etc
And classes e.g:- ArrayList, Vector, LinkedList, HashSet, TreeSet etc.
42. Iterator Interface
An iterator over a collection. Iterator takes the place of Enumeration in
the Java Collections Framework. Iterators differ from enumerations in
two ways:
- Iterators allow the caller to remove elements from the underlying
collection during the iteration with well-defined semantics.
- Method names have been improved.
This interface is a member of the Java Collections Framework.
Methods that are available in iterator interface
- public Boolean hasNext() returns true if iterator has more elements
- public Object hasNext() returns the element and moves the cursor
pointer to the next element
- public void remove() it removes the last element returned by the
iterator
43. Exception Handling in Java
Exception handling in java is one of the powerful mechanism to handle the
runtime errors so that normal flow of the application can be maintained.
In Java, Exception is an event that distrupts the normal flow of the
program. It as an Object which is thrown at runtime.
What is Exception Handling?
It’s a mecahnism to handle runtime errors such as ClassNotFound, SQL,
Remote etc.
Advantages of Exception Handling
The core advantage of exception handling is to maintain the normal flow of
the application
45. Types of Exceptions in Java
Checked Exception
* The classes that extend Throwable class except RuntimeException
and Error are known as checked exceptions e.g.IOException,
SQLException etc.
* Checked exceptions are checked at compile-time.
Unchecked Exception
* The classes that extend RuntimeException are known as unchecked
exceptions e.g. ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc.
* Unchecked exceptions are not checked at compile-time rather they
are checked at runtime.
Error
* Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError,
AssertionError etc.
46. Few examples where Exceptions
may occur
ArithmeticException
This occurs where any number is devided by zero
int x=100/0;
NullPointerException
If we have null value in any varible and performing any operation by the
variable causes a NullPointerException
String x=null;
System.out.println(x.length());
47. Few examples where Exceptions
may occur…
NumberFormatException
The wrong formatting of any value causes this Exception
String xyz=“apple”;
int number=Integer.parseInt(xyz);
ArrayIndexOutOfBoundsException
If a value entered in a wrong index of an array, it causes this Exception
Int arr[]=new int[5];
arr[7]=100;
48. Keywords used in Java Exception
handling
try
Java try block is used to enclose the code that might throw an
Exception. It must be used within the method. Must be followed either
by catch or finally block
catch
Java catch block is used to handle the Exception. It must be used after
the try block only.
finally
Java finally block is a block that is used to execute important code
such as closing connection, stream etc. Java finally block is always
executed whether exception is handled or not. Java finally block must
be followed by try or catch block.
49. Keywords used in Java Exception
handling…
throw
throw keyword is used to throw Exception from any method or static
block in Java
throws
throws keyword, used in method declaration, denoted which
Exception can possible be thrown by this method.