SlideShare a Scribd company logo
checked exception
Core Java
mahika.a.motwani@gmail.com
Programming Languages
High Level Languages
(Machine independent)
Low-Level Languages
(Machine dependent)
Assembly
language
Machine(Binary)
language
Java
 Java was created by James Gosling at Sun Microsystems (which is now acquired by
Oracle Corporation) and released in 1995.
 Java is a high level, object-oriented programming language.
OOPs Concepts
Encapsulation
Binding (or wrapping) code and data together into a single unit.
A java class is the example of encapsulation.
Abstraction
Hiding internal details and showing functionality only.
With Abstraction
WithoutAbstraction
Inheritance
A mechanism by which a class acquires all the properties and behaviours of an
existing class.
Provides code reusability.
Used to achieve runtime polymorphism.
Polymorphism
Ability to take multiple forms.
Example-
int a=10,b=20,c;
c=a+b; //addition
String firstname=“Sachin”, lastname=“Tendulkar”, fullname;
fullname=firstname+lastname;//concatenation
OOPLs
(Four OOPs features)
Partial OOPL Pure OOPLFully OOPL
Classes not mandatory.
Data members and methods can be
given outside class.
e.g. C++
Classes mandatory.
Data members and methods cannot
be given outside class.
e.g. Java
Classes mandatory.
Data members and methods cannot
be given outside class.
Primitive data types not supported.
e.g. Smalltalk
Java supports primitive data types , hence it is a fully OOPL but not pure OOPL.
int i=20; //primitive type
Integer a=new Integer(20); //Class type
Core Java
Signature of main()
public static void main(String[] args) {
…………..
…………..
}
returnType methodName(arguments)
{
……
}
void m1()
{
…..
…..
}
int m2()
{
…..
return 2;
}
int m3(int n)
{
…..
return n*n;
}
public static void main(String[] args) {
…………..
…………..
}
class Test
{
public static void myStatic()
{
-----
-----
-----
}
public void myNonStatic()
{
-----
}
}
class Sample
{
public void CallerFunction()
{
// Invoking static function
Test.myStatic();
// Invoking non-static function
Test t= new Test();
t.myNonStatic();
}
}
Invoking Member Funtions Of A Class
class Test
{
public static void main(String[] args)
{
-----
-----
-----
}
}
// Incase of static main()
Test.main();
Invoking main()
Since the main method is static Java virtual Machine can call it without creating any
instance of a class which contains the main method.
// Incase of non-static main()
Test t=new Test()
t.main();
Thank You
Java Code (.java)
JAVAC
Compiler
Byte Code (.class)
JVM JVM JVM
Linux Mac Windows
JVM
JVM (Java Virtual Machine) is an abstract machine. It is a specification
that provides runtime environment in which java bytecode can be
executed.
JVM is the engine that drives the java code
The JVM performs following main tasks:
 Loads code
 Verifies code
 Executes code
JRE
 JRE is an acronym for Java Runtime Environment.
JRE
JVM
Llibraries
like rt.jar
Other files
JRE
JVM
Llibraries
like rt.jar
Other files
Development
tools like
javac, java etc.
JDK
JDK
JDK is an acronym for Java Development Kit.
Includes a complete JRE (Java Runtime Environment) plus tools for developing, debugging, and
monitoring Java applications.
Internal Architecture of JVM
Java
Runtime
System
Class Loader
Class
Area
Heap Stack
PC
Register
Native
Method
Stack
Execution
engine
Native Method
Interface
Java Native
Libraries
Memory areas
allocated by JVM
Internal Architecture of JVM
Java
Runtime
System
Class Loader
Class
Area
Heap Stack
PC
Register
Native
Method
Stack
Execution
engine
Native Method
Interface
Java Native
Libraries
Memory areas
allocated by JVM
Java Keywords
Words that cannot be used as identifiers in programs.
There are 50 java keywords.
All keywords are in lower-case.
Each keyword has special meaning for the compiler.
Keywords that are not used in Java so far are called reserved words.
Category Keywords
Access modifiers private, protected, public
Class, method, variable
modifiers
abstract, class, extends, final, implements, interface, native,new, static,
strictfp, synchronized, transient, volatile
Flow control break, case, continue, default, do, else, for, if, instanceof,return, switch,
while
Package control import, package
Primitive types boolean, byte, char, double, float, int, long, short
Exception handling assert, catch, finally, throw, throws, try
Enumeration enum
Others super, this, void
Unused const, goto
Points to remember
 const and goto are resevered words.
 true, false and null are literals, not keywords.
List of Java Keywords
Rules for Naming Java Identifiers
Allowed characters for identifiers are[A-Z], [a-z],[0-9], ‘$‘(dollar sign) and ‘_‘
(underscore).
Should not start with digits(0-9).
Case-sensitive, like id and ID are different.
Java keyword cannot be used as an identifier.
Java Identifiers
Names given to programming elements like variables, methods,
classes, packages and interfaces.
Java Naming conventions
Name Convention
class name should start with uppercase letter and be a noun e.g.Shape, String, Color, System, Thread etc.
interface name should start with uppercase letter and be an adjective e.g. Runnable, Clonable etc.
method name should start with lowercase letter and be a verb e.g. compute(), print(), println() etc.
variable name should start with lowercase letter e.g. firstName, lastName etc.
package name should be in lowercase letter e.g. java, lang, sql, util etc.
constants name should be in uppercase letter. e.g. BLUE, MAX_PRIORITY etc.
Core Java
Class
 A template that describes the data and behavior.
Object
An entity that has state and behavior is known as an object e.g. chair, bike, table, car etc.
state: represents data (value) of an object.
behavior: represents the functionality of an object such as deposit, withdraw etc.
Student
Data members
id
name
Methods
setId()
setName()
getId()
getName()
class
public class Student {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Java class example
Instantiation/ Object Creation-
Classname referenceVariable=new Classname();
e.g.-
Student s=new Student();
Method Invocation/Call-
Non-static method:
referenceVariable.methodname();
e.g.- s.show();
static method:
Classname.methodname();
e.g.- Sample.display();
Scanner class
A class in java.util package
Used for obtaining the input of the primitive types like int, double etc. and strings
Breaks its input into tokens using a delimiter pattern, which by default matches whitespace.
To create an object of Scanner class, we usually pass the predefined object System.in, which
represents the standard input stream.
We may pass an object of class File if we want to read input from a file.
Creating instance of Scanner class
To read from System.in:
Scanner sc = new Scanner(System.in);
To read from File:
Scanner sc = new Scanner(new File("myFile"));
Commonly used methods of Scanner class
Method Description
public String next() it returns the next token from the scanner.
public byte nextByte() it scans the next token as a byte.
public short nextShort() it scans the next token as a short value.
public int nextInt() it scans the next token as an int value.
public long nextLong() it scans the next token as a long value.
public float nextFloat() it scans the next token as a float value.
public double nextDouble() it scans the next token as a double value.
Thank You
Types of Variable
local instance static
public class Student
{
int rn; //instance variable
String name; //instance variable
static String college; //static variable
void m1()
{
int l; //local variable
……
}
……….
}
id=1
name= Hriday
Stack
Heap
id=2
name= Anil
s1
s2
college=“SVC””
Class Area
class Student{
int id;
String name;
static String college=“SVC”;
………
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
…………
}
}
Thank You
Core Java Tutorials by Mahika Tutorials
Data Type Default Value Default size
boolean false 1 bit
char 'u0000' 2 byte
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
float 0.0f 4 byte
double 0.0d 8 byte
lowest unicode value:u0000
highest unicode value:uFFFF
Control Structures
1. Conditional
a) Simple if
b) if–else
c) if-else-if ladder
d) Nested if
e) switch case
2. Looping
a) while loop
b) for loop
c) do while loop
d) for each/enhanced for loop
if Statement:
if(condition){
//code to be executed
}
if –else Statement:
if(condition){
//code if condition is true
}
else{
//code if condition is false
}
if-else-if ladder Statement
if(condition1){
//code to be executed if condition1 is true
}
else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}
Test
Expression 1
Test
Expression 2
Test
Expression 3
No
No
No
Statement 1
Statement 2
Statement 3
else Body
Yes
Yes
Yes
if(Boolean_expression 1)
{
// Executes when the Boolean expression 1 is true
if(Boolean_expression 2)
{
// Executes when the Boolean expression 2 is true
}
}
Nested if
Core Java
switch Statement
switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
default:
//code to be executed if all cases are not matched;
}
Expression
case 1?
case 2?
case 3?
No
No
No
Case Block 1
Case Block 2
Case Block 3
default Block
Yes
Yes
Yes
switch Statement
Expression can be byte, short, char, and int.
From JDK7 onwards, it also works with enumerated types ( Enums in java), the String class
and Wrapper classes.
Duplicate case values are not allowed.
switch(ch)
{
case 1: .......
break;
case 1: ......
break;
…………
}
The value for a case must be the same data type as the variable in the
switch.
switch(ch)
{
case 1: ......
break;
case 2: ......
break;
}
The value for a case must be a constant or a literal.Variables are not
allowed.
The break statement is used inside the switch to terminate a statement sequence.
The break statement is optional. If omitted, execution will continue on into the next
case.
The default statement is optional.
while Loop
while(condition){
//code to be executed
}
do-while Loop
do{
//code to be executed
}while(condition);
for Loop
for(initialization;condition;incr/decr){
//code to be executed
}
break Statement
Used to break loop or switch statement.
continue Statement
Used to continue loop.
Skips the remaining code at specified condition.
Polymorphism
Run-time PolymorphismCompile-time Polymorphism
Method OverridingMethod Overloading
Method Overloading
When a class have multiple methods by same name but different parameters.
Advantage :
Increases the readability of the program.
Different ways to overload the method:
1) By changing number of arguments
2) By changing the data type of arguments
Method Overloading is not possible by changing the return type or access specifier of a method.
Method Overloading and Type Promotion
 If we have overloaded methods with one byte/short/int/long parameter then
always method with int is called.
 To invoke method with long parameter L should be append to the value while
calling
 Method with byte/short is called only if we pass the variable of that type or we
typecast the value.
 If we have overloaded method with one int/float/double and we pass long value
then method with int parameter is called.
 If we have overloaded method with one float/double and we pass long value
then method with float parameter is called.
Ambiguity in Method Overloading
class Test{
void sum(int a,long b){System.out.println(a+b);}
void sum(long a,int b){System.out.println(a+b);}
public static void main(String args[]){
Test obj=new Test();
obj.sum(20,20);// ambiguity
}
}
Output:Compile Time Error
Constructor
 Special type of method that is used to initialize the object.
 Invoked at the time of object creation.
 Can be overloaded.
Rules for creating java constructor:
 Constructor name must be same as its class name
 Constructor must have no explicit return type
Types of java constructors:
 Default constructor (no-arg constructor)
 Parameterized constructor
If there is no constructor in a class, compiler automatically creates a
default constructor.
class Student{
}
class Student{
Student()
{
}
}
compiler
Student.java Student.class
Java Copy Constructor
There is no copy constructor in java. But, we can copy the values of one
object to another like copy constructor in C++.
There are many ways to copy the values of one object into another in java.
They are:
 By constructor
 By assigning the values of one object into another
 By clone() method of Object class
static keyword
static is a non-access modifier.
Used for memory management mainly.
 The static can be:
variable (also known as class variable)
method (also known as class method)
block
nested class
static variable
Used to refer the common property of all objects e.g. company name
of employees,college name of students etc.
Gets memory only once in class area at the time of class loading.
Local variables cannot be static.
Advantage :
It makes your program memory efficient (i.e it saves memory).
//Program for static variable
class Student{
int id;
String name;
static String college =“SVC";
Student(int i,String n){
id=i;
name = n;
}
void display (){
System.out.println(id+" "+name+" "+college);}
public static void main(String args[]){
Student s1 = new Student(1,“Hriday");
Student s2 = new Student(2,“Anil");
s1.display();
s2.display();
}
}
id=1
name= “Hriday”
Stack
Heap
id=2
name= “Anil”
s1
s2
college=“SVC””
Class Area
static method
Method defined with the static keyword.
 Belongs to the class rather than object of a class.
 Can be invoked without the need for creating an instance of a class.
 Can access static data members and can change the value of it.
 Cannot use non static data member or call non-static method directly.
 this and super cannot be used in static context.
static block
Used to initialize the static data member.
 Is executed before main method at the time of classloading.
Example :
class A{
static{
System.out.println("static block invoked");
}
public static void main(String args[]){
System.out.println(“main invoked");
}
}
this keyword in java
A reference variable that refers to the current object.
Usage of this keyword :
this keyword can be used to refer current class instance variable.
this() can be used to invoke current class constructor.
this can be used to invoke current class method (implicitly)
this can be used to return the current class instance from the method.
this can be passed as an argument in the method call.
this can be passed as argument in the constructor call.
this() : to invoke current class constructor
Used for constructor chaining.
Used to reuse the constructor.
Call to this() must be the first statement in constructor.
Syntax
this(); // call default constructor
this(value1,value2,.....) //call parametrized constructor
//this() : to invoke current class constructor
public class Rectangle {
private int x, y;
private int width, height;
public Rectangle() {
this(0, 0, 0, 0);
}
public Rectangle(int width, int height) {
this(0, 0, width, height);
}
public Rectangle(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
}
……….
}
this :to invoke current class method (implicitly)
Can be used to invoke method of the current class.
If you don't use the this keyword, compiler automatically adds this
keyword while invoking the method.
class Test{
void m1( )
{ …. }
void m2( )
{
m1()
}
….
}
class Test{
void m1( )
{ …. }
void m2( )
{
this.m1()
}
….
}
compiler
Test.java Test.class
this: to pass as an argument in the method
class Test
{
int a;
int b;
Test()
{
a = 40;
b = 60;
}
// Method that receives 'this' keyword as parameter
void display(Test obj)
{
System.out.println("a = " + a + " b = " + b);
}
// Method that pases current class instance
void get()
{
display(this);
}
public static void main(String[] args)
{
Test object = new Test();
object.get();
}
}
Output:-
a=40 b=60
Core Java
mahika.tutorials@gmail.com
this: to pass as argument in the constructor call
class B{
A obj;
B(A obj)
{
this.obj=obj;
}
void display(){
System.out.println(obj.data); //10
}
}
class A{
int data=10;
A()
{
B b=new B(this);
b.display();
}
public static void main(String args[]){
A a=new A();
}
}
this keyword in java
A reference variable that refers to the current object.
Usage of this keyword :
 this keyword can be used to refer current class instance variable.
 this() can be used to invoke current class constructor.
 this can be used to invoke current class method (implicitly)
 this can be used to return the current class instance from the method.
 this can be passed as an argument in the method call.
 this can be passed as argument in the constructor call.
this keyword cannot be used in static context.
Inheritance
 A mechanism in which one object acquires all the properties and behaviors of parent object.
 Represents the IS-A relationship, also known as parent-child relationship
 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.
 A class which is inherited is called parent or super class and the new class is called child or
subclass.
Inheritance in java is used:
 For Method Overriding (so runtime polymorphism can be achieved).
 For Code Reusability.
Syntax of Java Inheritance:
class Subclass-name extends Superclass-name
{
//methods and fields
}
Types of inheritance in java
Multiple inheritance is not supported in java through class
Object class is the superclass of all the classes in java by default.
Every class in Java is directly or indirectly derived from the Object class.
Object class is present in java.lang package.
class A
{
……..
}
class A extends Object
{
……..
}
Object class
class A
{
…….
}
class B extends A
{
…….
}
class A extends Object
{
……..
}
class B extends A
{
…….
}
Object class
Commonly used Methods of Object class:
Method Description
public boolean equals(Object obj) compares the given object to this object.
protected Object clone() throws
CloneNotSupportedException
creates and returns the exact copy (clone) of this object.
public String toString() returns the string representation of this object.
public final void notify() wakes up single thread, waiting on this object's monitor.
public final void notifyAll() wakes up all the threads, waiting on this object's
monitor.
public final void wait(long timeout)throws
InterruptedException
causes the current thread to wait for the specified
milliseconds, until another thread notifies (invokes
notify() or notifyAll() method).
protected void finalize()throws Throwable is invoked by the garbage collector before object is being
garbage collected.
Account
SavingAccount
Single Inheritance
Account
• String accountId
• double accountBalance
SavingAccount
• double interestRate
• double minimumBalance
Account
SavingAccount
SilverSavingAccount
Multilevel Inheritance
Account
• String accountId
• double acctBalance
SavingAccount
• double interestRate
• double minimumBalance
SilverSavingAcccount
• String specialOfferId
Account
SavingAccount CurrentAccount
Hierarchical Inheritance
Account
• String accountId
• double acctBalance
SavingAccount
• double interestRate
• double minimumBalance
CurrentAccount
• double transactionFee;
mahika.a.motwani@gmail.com
Multiple Inheritance
A feature where a class can inherit properties of more than one parent class.
Java doesn’t allow multiple inheritance by using classes ,for simplicity and to avoid the ambiguity caused by it.
It creates problem during various operations like casting, constructor chaining etc.
mahika.a.motwani@gmail.com
Multiple Inheritance and Ambiguity
class A
{
void show()
{
System.out.println("Hello");}
}
class B
{
void show()
{
System.out.println("Welcome");
}
}
class C extends A,B //suppose if it was allowed
{
public static void main(String args[])
{
C obj=new C();
obj.show(); //ambiguity
}
}
mahika.a.motwani@gmail.com
Multiple Inheritance and Diamond Problem
mahika.a.motwani@gmail.com
Multiple inheritance in Java by interface
If a class implements multiple interfaces, or an interface extends multiple interfaces.
Polymorphism
Run-time PolymorphismCompile-time Polymorphism
Method OverridingMethod Overloading
Method Overriding
If subclass (child class) has the same method as declared in the parent class, it is known as method overriding
in java.
Usage :
 Used to provide specific implementation of a method that is already provided by its super class.
 Used for runtime polymorphism
class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
class Bike extends Vehicle{
void run(){System.out.println("Bike is running ”);}
public static void main(String args[]){
Bike obj = new Bike();
obj.run();
}
Example:
class Shape{
void draw()
{
System.out.println("No Shape");
}
}
class Rectangle extends Shape{
void draw()
{
System.out.println("Drawing rectangle");
}
}
class Circle extends Shape{
void draw()
{
System.out.println("Drawing circle");
}
}
class Triangle extends Shape{
void draw()
{
System.out.println("Drawing circle");
}
}
public class Test{
public static void main(String args[]){
Shape s;
s=new Shape();
s.draw();
s =new Circle();
s.draw();
s=new Rectangle();
s.draw();
s=new Triangle();
s.draw();
}
}
At compile-time:
class Shape{
void draw()
{
System.out.println("No Shape");
}
}
class Circle extends Shape{
void draw()
{
System.out.println("Drawing circle");
}
}
class Rectangle extends Shape{
void draw()
{
System.out.println("Drawing rectangle");
}
} class Triangle extends Shape{
void draw()
{
System.out.println("Drawing circle");
}
}
public class Test{
public static void main(String args[]){
Shape s;
s=new Shape();
s.draw();
s =new Circle();
s.draw();
s=new Rectangle();
s.draw();
s=new Triangle();
s.draw();
}
}
At run-time:
Rules for Method Overriding:
 Method must have same name as in the parent class
 Method must have same parameter as in the parent class.
 Method must have same return type(or sub-type).
 Must be IS-A relationship (inheritance).
 private method cannot be overridden.
 final method cannot be overridden
 static method cannot be overridden because static method is bound with class whereas instance method
is bound with object.
 We can not override constructor as parent and child class can never have constructor with same name.
 Access Modifier of the overriding method (method of subclass) cannot be more restrictive than the
overridden method of parent class.
 Binding of overridden methods happen at runtime which is known as dynamic binding.
ExceptionHandling with MethodOverriding in Java
 If the superclass method does not declare an exception, subclass overridden
method cannot declare the checked exception.
class Child extends Parent{
void msg()throws IOException
{
System.out.println(“child");
}
public static void main(String args[])
{
Parent p=new Child();
p.msg();
}
}
class Parent{
void msg()
{
System.out.println("parent");
}
}
Output:Compile Time Error
 If the superclass method does not declare an exception, subclass
overridden method cannot declare the checked exception but can declare
unchecked exception.
class Parent{
void msg()
{
System.out.println("parent");
}
}
class Child extends Parent{
void msg()throws ArithmeticException
{
System.out.println("child");
}
public static void main(String args[])
{
Parent p=new Child();
p.msg();
}
}
Output:child
 If the superclass method declares an exception, subclass overridden method can declare
same, subclass exception or no exception but cannot declare parent exception.
class Child extends Parent{
void msg()throws Exception
{
System.out.println("child");
}
public static void main(String args[])
{
Parent p=new Child();
try{
p.msg();
}catch(Exception e){
}
}
}
class Parent{
void msg()throws ArithmeticException{
System.out.println("parent");
}
}
Output:Compile Time Error
class Parent{
void msg()throws Exception{
System.out.println("parent");
}
}
Class Child extends Parent{
void msg()throws ArithmeticException{
System.out.println("child");
}
public static void main(String args[]){
Parent p=new Child();
try{
p.msg();
}catch(Exception e){}
}
}
Example in case subclass overridden method declares subclass exception
Output:child
Covariant Return Type
Specifies that the return type may vary in the same direction as the subclass.
Since Java5, it is possible to override method by changing the return type if subclass overrides
any method, but it changes its return type to subclass type.
class ShapeFactory {
public Shape newShape()
{
…………
}
}
class CircleFactory extends ShapeFactory {
public Circle newShape()
{
……
}
}
class Shape
{
………
}
class Circle extends Shape
{
………
}
super keyword
A reference variable that is used to refer immediate parent class object.
super keyword cannot be used in static context.
Usage :
 super is used to refer immediate parent class instance variable.
 super() is used to invoke immediate parent class constructor,.
 super is used to invoke immediate parent class method.
super used to refer immediate parent class instance variable:
class Vehicle{
int speed=70;
}
class Bike extends Vehicle{
int speed=100;
void display(){
System.out.println(super.speed);// Vehicle speed
System.out.println(speed);// Bike speed
}
public static void main(String args[]){
Bike b=new Bike();
b.display();
}
}
super() to invoke parent class constructor:
class Vehicle{
Vehicle(){System.out.println("Vehicle created");}
}
class Bike extends Vehicle{
Bike(){
super();//invokes parent class constructor
System.out.println("Bike created");
}
public static void main(String args[]){
Bike b=new Bike();
}
}
 If used, super() must be the first statement inside the constructor, hence either
super() or this() can be used inside the constructor.
 super() is added in each class constructor automatically by compiler if there is
no super() or this().
class Bike{
Bike()
{
}
}
class Bike{
Bike()
{
super();
}
}
compiler
Bike.java Bike .classa
super() :to invoke parent class constructor
super used to invoke parent class method:
class Vehicle{
void show(){System.out.println("Vehicle Runing");}
}
class Bike extends Vehicle{
void show(){System.out.println("Bike Runing ");
}
void display(){
super.show();
show();
}
public static void main(String args[]){
Bike b=new Bike();
b.display();
}
}
final Keyword
Used to restrict the user.
final can be:
1) VariableIf you make any variable as final, you cannot change the
value of final variable(It will be constant).
2) Method->If you make any methode as final, you cannot override it.
3) Class->If you make any class as final, you cannot extend it.
 final method is inherited but you cannot override it.
 A final variable that is not initialized at the time of declaration is known as blank final variable.
 We can initialize blank final variable only in constructor. For example:
class Test{
final int i;//blank final variable
Test(){
i=80;
......
}
}
 If a method is declared private and final in superclass then we can have method with the same signature
in subclass also because private is not inherited.
 Constructor cannot be declared as final because constructor is never inherited.
final Keyword
Core Java
Java Package
Group of similar types of classes, interfaces and sub-packages.
Types:
built-in package (such as java, lang, io, util, sql etc.)
user-defined package.
Advantages:
 Used to categorize the classes and interfaces so that they can be easily maintained.
 Provides access protection.
 Removes naming collision.
Core Java Tutorials by Mahika Tutorials
Ways to access the package from outside the package:
1) import packageName.*;
2) import packageName.classname;
3) fully qualified name.
If you import a package, subpackages will not be imported.
Core Java
Access Modifiers
Specifies accessibility (scope) of a data member, method, constructor or class.
Types :
 private
 package-private (no explicit modifier)
 protected
 public
There are many non-access modifiers such as static, abstract, synchronized,
native, volatile, transient etc.
Access Modifier within class within package outside package by
subclass only
outside
package
private Y N N N
package-private (no explicit modifier) Y Y N N
protected Y Y Y N
public Y Y Y Y
Note: A class cannot be private or protected except nested class.
Mahika.a.motwani@gmail.com
Modifier A B C D
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N
Visibiity
The following table shows where the members of the A class are visible for each of the access modifiers that can be
applied to them.
Package 1
A
B
Package 2
C
D
subclass
Java Array
Collection of similar type of elements.
Contiguous memory location.
Fixed size.
Index based, first element of the array is stored at 0 index.
Types of Array:
Single Dimensional Array
Multidimensional Array
Single Dimensional Array in java
Syntax:
dataType[] arr; (or)
dataType []arr; (or)
dataType arr[];
Instantiation :
arrayRefVar=new datatype[size];
Declaration, Instantiation and Initialization :
int a[]={33,3,4,5};//declaration, instantiation and initialization
Core Java
Mahika.a.motwani@gmail.com
Diamond problem
An ambiguity that can arise as a consequence of allowing multiple inheritance.
Since Java 8 default methods have been permitted inside interfaces, which may
cause ambiguity in some cases.
Mahika.a.motwani@gmail.com
Diamond Structure:Case#1
[+] void m () <<default>>
<<interface>>
A
<<interface>>
B
<<interface>>
C
[+] void main(String arg[]) <<static>>
<<class>>
D
interface A
{
default void m()
{
System.out.println("m() from interface A ");
}
}
interface B extends A
{
}
interface C extends A
{
}
public class D implements B,C {
public static void main(String[] args) {
new D().m();
}
}
Mahika.a.motwani@gmail.com
Diamond Structure:Case#2
[+] void m () <<default>>
<<interface>>
A
[+] void m () <<default>> <<override>>
<<interface>>
B
<<interface>>
C
[+] void main(String arg[]) <<static>>
<<class>>
D
interface A
{
default void m()
{
System.out.println("m() from interface A ");
}
}
interface B extends A
{
@Override
default void m()
{
System.out.println("m() from interface B ");
}
}
interface C extends A
{
}
public class D implements B,C {
public static void main(String[] args) {
new D().m();
}
}
Mahika.a.motwani@gmail.com
Diamond Structure:Case#3
[+] void m () <<default>>
<<interface>>
A
[+] void m () <<default>> <<override>>
<<interface>>
B
[+] void m () <<default>> <<override>>
<<interface>>
C
[+] void m () <<override>>
[+] void main(String arg[]) <<static>>
<<class>>
D
interface A
{
default void m()
{
System.out.println("m() from interface A ");
}
}
interface B extends A
{
@Override
default void m()
{
System.out.println("m() from interface B ");
}
}
interface C extends A
{
@Override
default void m()
{
System.out.println("m() from interface C");
}
}
public class D implements B,C {
@Override
public void m() {
B.super.m();
}
public static void main(String[] args) {
new D().m();
}
}

More Related Content

PDF
Java Tutorial For Beginners - Step By Step | Java Basics | Java Certification...
Edureka!
 
PPTX
Core java
Ravi varma
 
PDF
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Edureka!
 
PPT
Introduction to Java Programming, Basic Structure, variables Data type, input...
Mr. Akaash
 
PPT
Core java slides
Abhilash Nair
 
PDF
Introduction to java (revised)
Sujit Majety
 
PDF
Basic Java Programming
Math-Circle
 
PDF
Overview of Java
josemachoco
 
Java Tutorial For Beginners - Step By Step | Java Basics | Java Certification...
Edureka!
 
Core java
Ravi varma
 
Java Tutorial | Java Programming Tutorial | Java Basics | Java Training | Edu...
Edureka!
 
Introduction to Java Programming, Basic Structure, variables Data type, input...
Mr. Akaash
 
Core java slides
Abhilash Nair
 
Introduction to java (revised)
Sujit Majety
 
Basic Java Programming
Math-Circle
 
Overview of Java
josemachoco
 

What's hot (20)

PPTX
Introduction to java
Sandeep Rawat
 
PDF
Introduction to Java Programming
Ravi Kant Sahu
 
PPT
Java basic
Sonam Sharma
 
PPTX
Core Java
Priyanka Pradhan
 
PPT
Java Basics
Brandon Black
 
PPTX
Presentation on Core java
mahir jain
 
PPT
Java basic introduction
Ideal Eyes Business College
 
PPSX
Introduction to java
Ajay Sharma
 
PPTX
Static keyword ppt
Vinod Kumar
 
PPTX
Core java complete ppt(note)
arvind pandey
 
PPTX
core java
Roushan Sinha
 
PPTX
Super Keyword in Java.pptx
KrutikaWankhade1
 
PPTX
Java Virtual Machine (JVM), Difference JDK, JRE & JVM
shamnasain
 
PPTX
Core Java
NA
 
ODP
OOP java
xball977
 
PPTX
Java Method, Static Block
Infoviaan Technologies
 
PPTX
Introduction to java
Java Lover
 
PDF
Learn Java with Dr. Rifat Shahriyar
Abir Mohammad
 
PPTX
Java
Tony Nguyen
 
PPTX
Constructor in java
Madishetty Prathibha
 
Introduction to java
Sandeep Rawat
 
Introduction to Java Programming
Ravi Kant Sahu
 
Java basic
Sonam Sharma
 
Core Java
Priyanka Pradhan
 
Java Basics
Brandon Black
 
Presentation on Core java
mahir jain
 
Java basic introduction
Ideal Eyes Business College
 
Introduction to java
Ajay Sharma
 
Static keyword ppt
Vinod Kumar
 
Core java complete ppt(note)
arvind pandey
 
core java
Roushan Sinha
 
Super Keyword in Java.pptx
KrutikaWankhade1
 
Java Virtual Machine (JVM), Difference JDK, JRE & JVM
shamnasain
 
Core Java
NA
 
OOP java
xball977
 
Java Method, Static Block
Infoviaan Technologies
 
Introduction to java
Java Lover
 
Learn Java with Dr. Rifat Shahriyar
Abir Mohammad
 
Constructor in java
Madishetty Prathibha
 
Ad

Similar to Core Java Tutorials by Mahika Tutorials (20)

PPTX
Core-Java-by-Mahika-Tutor.9459891.powerpoint.pptx
NagarathnaRajur2
 
PPTX
Chapter 2 java
Ahmad sohail Kakar
 
PPTX
Java Notes
Sreedhar Chowdam
 
PPTX
Java Notes by C. Sreedhar, GPREC
Sreedhar Chowdam
 
PPT
java01.ppt
Godwin585235
 
PPT
java01.pptbvuyvyuvvvvvvvvvvvvvvvvvvvvyft
nagendrareddy104104
 
PPT
Java Simple Introduction in single course
binzbinz3
 
PPTX
Java programmingjsjdjdjdjdjdjdjdjdiidiei
rajputtejaswa12
 
PPTX
Java platform
Visithan
 
PDF
Java basic concept
University of Potsdam
 
PPTX
Java For Automation
Abhijeet Dubey
 
PPTX
chapter 1-overview of java programming.pptx
nafsigenet
 
PPSX
DISE - Windows Based Application Development in Java
Rasan Samarasinghe
 
PPSX
Esoft Metro Campus - Certificate in java basics
Rasan Samarasinghe
 
PPT
Java
Manav Prasad
 
PPTX
Java tutorial for beginners-tibacademy.in
TIB Academy
 
PPTX
Java
Zeeshan Khan
 
PPSX
DITEC - Programming with Java
Rasan Samarasinghe
 
PPT
Present the syntax of Java Introduce the Java
ssuserfd620b
 
PPT
Java PPt.ppt
NavneetSheoran3
 
Core-Java-by-Mahika-Tutor.9459891.powerpoint.pptx
NagarathnaRajur2
 
Chapter 2 java
Ahmad sohail Kakar
 
Java Notes
Sreedhar Chowdam
 
Java Notes by C. Sreedhar, GPREC
Sreedhar Chowdam
 
java01.ppt
Godwin585235
 
java01.pptbvuyvyuvvvvvvvvvvvvvvvvvvvvyft
nagendrareddy104104
 
Java Simple Introduction in single course
binzbinz3
 
Java programmingjsjdjdjdjdjdjdjdjdiidiei
rajputtejaswa12
 
Java platform
Visithan
 
Java basic concept
University of Potsdam
 
Java For Automation
Abhijeet Dubey
 
chapter 1-overview of java programming.pptx
nafsigenet
 
DISE - Windows Based Application Development in Java
Rasan Samarasinghe
 
Esoft Metro Campus - Certificate in java basics
Rasan Samarasinghe
 
Java tutorial for beginners-tibacademy.in
TIB Academy
 
DITEC - Programming with Java
Rasan Samarasinghe
 
Present the syntax of Java Introduce the Java
ssuserfd620b
 
Java PPt.ppt
NavneetSheoran3
 
Ad

Recently uploaded (20)

PDF
Phylum Arthropoda: Characteristics and Classification, Entomology Lecture
Miraj Khan
 
PPTX
Nursing Management of Patients with Disorders of Ear, Nose, and Throat (ENT) ...
RAKESH SAJJAN
 
PDF
5.EXPLORING-FORCES-Detailed-Notes.pdf/8TH CLASS SCIENCE CURIOSITY
Sandeep Swamy
 
PPTX
CARE OF UNCONSCIOUS PATIENTS .pptx
AneetaSharma15
 
PDF
1.Natural-Resources-and-Their-Use.ppt pdf /8th class social science Exploring...
Sandeep Swamy
 
PPTX
Information Texts_Infographic on Forgetting Curve.pptx
Tata Sevilla
 
PPTX
How to Manage Leads in Odoo 18 CRM - Odoo Slides
Celine George
 
PPTX
Congenital Hypothyroidism pptx
AneetaSharma15
 
PPTX
TEF & EA Bsc Nursing 5th sem.....BBBpptx
AneetaSharma15
 
PDF
Virat Kohli- the Pride of Indian cricket
kushpar147
 
PPTX
Five Point Someone – Chetan Bhagat | Book Summary & Analysis by Bhupesh Kushwaha
Bhupesh Kushwaha
 
PPTX
Software Engineering BSC DS UNIT 1 .pptx
Dr. Pallawi Bulakh
 
PDF
7.Particulate-Nature-of-Matter.ppt/8th class science curiosity/by k sandeep s...
Sandeep Swamy
 
PDF
UTS Health Student Promotional Representative_Position Description.pdf
Faculty of Health, University of Technology Sydney
 
PPTX
PREVENTIVE PEDIATRIC. pptx
AneetaSharma15
 
DOCX
UPPER GASTRO INTESTINAL DISORDER.docx
BANDITA PATRA
 
PDF
Arihant Class 10 All in One Maths full pdf
sajal kumar
 
PDF
Sunset Boulevard Student Revision Booklet
jpinnuck
 
PDF
What is CFA?? Complete Guide to the Chartered Financial Analyst Program
sp4989653
 
DOCX
Action Plan_ARAL PROGRAM_ STAND ALONE SHS.docx
Levenmartlacuna1
 
Phylum Arthropoda: Characteristics and Classification, Entomology Lecture
Miraj Khan
 
Nursing Management of Patients with Disorders of Ear, Nose, and Throat (ENT) ...
RAKESH SAJJAN
 
5.EXPLORING-FORCES-Detailed-Notes.pdf/8TH CLASS SCIENCE CURIOSITY
Sandeep Swamy
 
CARE OF UNCONSCIOUS PATIENTS .pptx
AneetaSharma15
 
1.Natural-Resources-and-Their-Use.ppt pdf /8th class social science Exploring...
Sandeep Swamy
 
Information Texts_Infographic on Forgetting Curve.pptx
Tata Sevilla
 
How to Manage Leads in Odoo 18 CRM - Odoo Slides
Celine George
 
Congenital Hypothyroidism pptx
AneetaSharma15
 
TEF & EA Bsc Nursing 5th sem.....BBBpptx
AneetaSharma15
 
Virat Kohli- the Pride of Indian cricket
kushpar147
 
Five Point Someone – Chetan Bhagat | Book Summary & Analysis by Bhupesh Kushwaha
Bhupesh Kushwaha
 
Software Engineering BSC DS UNIT 1 .pptx
Dr. Pallawi Bulakh
 
7.Particulate-Nature-of-Matter.ppt/8th class science curiosity/by k sandeep s...
Sandeep Swamy
 
UTS Health Student Promotional Representative_Position Description.pdf
Faculty of Health, University of Technology Sydney
 
PREVENTIVE PEDIATRIC. pptx
AneetaSharma15
 
UPPER GASTRO INTESTINAL DISORDER.docx
BANDITA PATRA
 
Arihant Class 10 All in One Maths full pdf
sajal kumar
 
Sunset Boulevard Student Revision Booklet
jpinnuck
 
What is CFA?? Complete Guide to the Chartered Financial Analyst Program
sp4989653
 
Action Plan_ARAL PROGRAM_ STAND ALONE SHS.docx
Levenmartlacuna1
 

Core Java Tutorials by Mahika Tutorials

  • 2. [email protected] Programming Languages High Level Languages (Machine independent) Low-Level Languages (Machine dependent) Assembly language Machine(Binary) language
  • 3. Java  Java was created by James Gosling at Sun Microsystems (which is now acquired by Oracle Corporation) and released in 1995.  Java is a high level, object-oriented programming language.
  • 5. Encapsulation Binding (or wrapping) code and data together into a single unit. A java class is the example of encapsulation.
  • 6. Abstraction Hiding internal details and showing functionality only. With Abstraction WithoutAbstraction
  • 7. Inheritance A mechanism by which a class acquires all the properties and behaviours of an existing class. Provides code reusability. Used to achieve runtime polymorphism.
  • 8. Polymorphism Ability to take multiple forms. Example- int a=10,b=20,c; c=a+b; //addition String firstname=“Sachin”, lastname=“Tendulkar”, fullname; fullname=firstname+lastname;//concatenation
  • 9. OOPLs (Four OOPs features) Partial OOPL Pure OOPLFully OOPL Classes not mandatory. Data members and methods can be given outside class. e.g. C++ Classes mandatory. Data members and methods cannot be given outside class. e.g. Java Classes mandatory. Data members and methods cannot be given outside class. Primitive data types not supported. e.g. Smalltalk Java supports primitive data types , hence it is a fully OOPL but not pure OOPL. int i=20; //primitive type Integer a=new Integer(20); //Class type
  • 12. public static void main(String[] args) { ………….. ………….. }
  • 13. returnType methodName(arguments) { …… } void m1() { ….. ….. } int m2() { ….. return 2; } int m3(int n) { ….. return n*n; }
  • 14. public static void main(String[] args) { ………….. ………….. }
  • 15. class Test { public static void myStatic() { ----- ----- ----- } public void myNonStatic() { ----- } } class Sample { public void CallerFunction() { // Invoking static function Test.myStatic(); // Invoking non-static function Test t= new Test(); t.myNonStatic(); } } Invoking Member Funtions Of A Class
  • 16. class Test { public static void main(String[] args) { ----- ----- ----- } } // Incase of static main() Test.main(); Invoking main() Since the main method is static Java virtual Machine can call it without creating any instance of a class which contains the main method. // Incase of non-static main() Test t=new Test() t.main();
  • 18. Java Code (.java) JAVAC Compiler Byte Code (.class) JVM JVM JVM Linux Mac Windows
  • 19. JVM JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment in which java bytecode can be executed. JVM is the engine that drives the java code The JVM performs following main tasks:  Loads code  Verifies code  Executes code
  • 20. JRE  JRE is an acronym for Java Runtime Environment. JRE JVM Llibraries like rt.jar Other files
  • 21. JRE JVM Llibraries like rt.jar Other files Development tools like javac, java etc. JDK JDK JDK is an acronym for Java Development Kit. Includes a complete JRE (Java Runtime Environment) plus tools for developing, debugging, and monitoring Java applications.
  • 22. Internal Architecture of JVM Java Runtime System Class Loader Class Area Heap Stack PC Register Native Method Stack Execution engine Native Method Interface Java Native Libraries Memory areas allocated by JVM
  • 23. Internal Architecture of JVM Java Runtime System Class Loader Class Area Heap Stack PC Register Native Method Stack Execution engine Native Method Interface Java Native Libraries Memory areas allocated by JVM
  • 24. Java Keywords Words that cannot be used as identifiers in programs. There are 50 java keywords. All keywords are in lower-case. Each keyword has special meaning for the compiler. Keywords that are not used in Java so far are called reserved words.
  • 25. Category Keywords Access modifiers private, protected, public Class, method, variable modifiers abstract, class, extends, final, implements, interface, native,new, static, strictfp, synchronized, transient, volatile Flow control break, case, continue, default, do, else, for, if, instanceof,return, switch, while Package control import, package Primitive types boolean, byte, char, double, float, int, long, short Exception handling assert, catch, finally, throw, throws, try Enumeration enum Others super, this, void Unused const, goto Points to remember  const and goto are resevered words.  true, false and null are literals, not keywords. List of Java Keywords
  • 26. Rules for Naming Java Identifiers Allowed characters for identifiers are[A-Z], [a-z],[0-9], ‘$‘(dollar sign) and ‘_‘ (underscore). Should not start with digits(0-9). Case-sensitive, like id and ID are different. Java keyword cannot be used as an identifier. Java Identifiers Names given to programming elements like variables, methods, classes, packages and interfaces.
  • 27. Java Naming conventions Name Convention class name should start with uppercase letter and be a noun e.g.Shape, String, Color, System, Thread etc. interface name should start with uppercase letter and be an adjective e.g. Runnable, Clonable etc. method name should start with lowercase letter and be a verb e.g. compute(), print(), println() etc. variable name should start with lowercase letter e.g. firstName, lastName etc. package name should be in lowercase letter e.g. java, lang, sql, util etc. constants name should be in uppercase letter. e.g. BLUE, MAX_PRIORITY etc.
  • 29. Class  A template that describes the data and behavior. Object An entity that has state and behavior is known as an object e.g. chair, bike, table, car etc. state: represents data (value) of an object. behavior: represents the functionality of an object such as deposit, withdraw etc.
  • 31. public class Student { private int id; private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } } Java class example
  • 32. Instantiation/ Object Creation- Classname referenceVariable=new Classname(); e.g.- Student s=new Student(); Method Invocation/Call- Non-static method: referenceVariable.methodname(); e.g.- s.show(); static method: Classname.methodname(); e.g.- Sample.display();
  • 33. Scanner class A class in java.util package Used for obtaining the input of the primitive types like int, double etc. and strings Breaks its input into tokens using a delimiter pattern, which by default matches whitespace. To create an object of Scanner class, we usually pass the predefined object System.in, which represents the standard input stream. We may pass an object of class File if we want to read input from a file.
  • 34. Creating instance of Scanner class To read from System.in: Scanner sc = new Scanner(System.in); To read from File: Scanner sc = new Scanner(new File("myFile"));
  • 35. Commonly used methods of Scanner class Method Description public String next() it returns the next token from the scanner. public byte nextByte() it scans the next token as a byte. public short nextShort() it scans the next token as a short value. public int nextInt() it scans the next token as an int value. public long nextLong() it scans the next token as a long value. public float nextFloat() it scans the next token as a float value. public double nextDouble() it scans the next token as a double value.
  • 37. Types of Variable local instance static
  • 38. public class Student { int rn; //instance variable String name; //instance variable static String college; //static variable void m1() { int l; //local variable …… } ………. }
  • 39. id=1 name= Hriday Stack Heap id=2 name= Anil s1 s2 college=“SVC”” Class Area class Student{ int id; String name; static String college=“SVC”; ……… public static void main(String args[]){ Student s1=new Student(); Student s2=new Student(); ………… } }
  • 42. Data Type Default Value Default size boolean false 1 bit char 'u0000' 2 byte byte 0 1 byte short 0 2 byte int 0 4 byte long 0L 8 byte float 0.0f 4 byte double 0.0d 8 byte lowest unicode value:u0000 highest unicode value:uFFFF
  • 43. Control Structures 1. Conditional a) Simple if b) if–else c) if-else-if ladder d) Nested if e) switch case 2. Looping a) while loop b) for loop c) do while loop d) for each/enhanced for loop
  • 45. if –else Statement: if(condition){ //code if condition is true } else{ //code if condition is false }
  • 46. if-else-if ladder Statement if(condition1){ //code to be executed if condition1 is true } else if(condition2){ //code to be executed if condition2 is true } else if(condition3){ //code to be executed if condition3 is true } ... else{ //code to be executed if all the conditions are false } Test Expression 1 Test Expression 2 Test Expression 3 No No No Statement 1 Statement 2 Statement 3 else Body Yes Yes Yes
  • 47. if(Boolean_expression 1) { // Executes when the Boolean expression 1 is true if(Boolean_expression 2) { // Executes when the Boolean expression 2 is true } } Nested if
  • 49. switch Statement switch(expression){ case value1: //code to be executed; break; //optional case value2: //code to be executed; break; //optional ...... default: //code to be executed if all cases are not matched; } Expression case 1? case 2? case 3? No No No Case Block 1 Case Block 2 Case Block 3 default Block Yes Yes Yes
  • 50. switch Statement Expression can be byte, short, char, and int. From JDK7 onwards, it also works with enumerated types ( Enums in java), the String class and Wrapper classes. Duplicate case values are not allowed. switch(ch) { case 1: ....... break; case 1: ...... break; ………… }
  • 51. The value for a case must be the same data type as the variable in the switch. switch(ch) { case 1: ...... break; case 2: ...... break; } The value for a case must be a constant or a literal.Variables are not allowed.
  • 52. The break statement is used inside the switch to terminate a statement sequence. The break statement is optional. If omitted, execution will continue on into the next case. The default statement is optional.
  • 54. do-while Loop do{ //code to be executed }while(condition);
  • 56. break Statement Used to break loop or switch statement.
  • 57. continue Statement Used to continue loop. Skips the remaining code at specified condition.
  • 59. Method Overloading When a class have multiple methods by same name but different parameters. Advantage : Increases the readability of the program. Different ways to overload the method: 1) By changing number of arguments 2) By changing the data type of arguments Method Overloading is not possible by changing the return type or access specifier of a method.
  • 60. Method Overloading and Type Promotion
  • 61.  If we have overloaded methods with one byte/short/int/long parameter then always method with int is called.  To invoke method with long parameter L should be append to the value while calling  Method with byte/short is called only if we pass the variable of that type or we typecast the value.  If we have overloaded method with one int/float/double and we pass long value then method with int parameter is called.  If we have overloaded method with one float/double and we pass long value then method with float parameter is called.
  • 62. Ambiguity in Method Overloading class Test{ void sum(int a,long b){System.out.println(a+b);} void sum(long a,int b){System.out.println(a+b);} public static void main(String args[]){ Test obj=new Test(); obj.sum(20,20);// ambiguity } } Output:Compile Time Error
  • 63. Constructor  Special type of method that is used to initialize the object.  Invoked at the time of object creation.  Can be overloaded. Rules for creating java constructor:  Constructor name must be same as its class name  Constructor must have no explicit return type Types of java constructors:  Default constructor (no-arg constructor)  Parameterized constructor
  • 64. If there is no constructor in a class, compiler automatically creates a default constructor. class Student{ } class Student{ Student() { } } compiler Student.java Student.class
  • 65. Java Copy Constructor There is no copy constructor in java. But, we can copy the values of one object to another like copy constructor in C++. There are many ways to copy the values of one object into another in java. They are:  By constructor  By assigning the values of one object into another  By clone() method of Object class
  • 66. static keyword static is a non-access modifier. Used for memory management mainly.  The static can be: variable (also known as class variable) method (also known as class method) block nested class
  • 67. static variable Used to refer the common property of all objects e.g. company name of employees,college name of students etc. Gets memory only once in class area at the time of class loading. Local variables cannot be static. Advantage : It makes your program memory efficient (i.e it saves memory).
  • 68. //Program for static variable class Student{ int id; String name; static String college =“SVC"; Student(int i,String n){ id=i; name = n; } void display (){ System.out.println(id+" "+name+" "+college);} public static void main(String args[]){ Student s1 = new Student(1,“Hriday"); Student s2 = new Student(2,“Anil"); s1.display(); s2.display(); } } id=1 name= “Hriday” Stack Heap id=2 name= “Anil” s1 s2 college=“SVC”” Class Area
  • 69. static method Method defined with the static keyword.  Belongs to the class rather than object of a class.  Can be invoked without the need for creating an instance of a class.  Can access static data members and can change the value of it.  Cannot use non static data member or call non-static method directly.  this and super cannot be used in static context.
  • 70. static block Used to initialize the static data member.  Is executed before main method at the time of classloading. Example : class A{ static{ System.out.println("static block invoked"); } public static void main(String args[]){ System.out.println(“main invoked"); } }
  • 71. this keyword in java A reference variable that refers to the current object. Usage of this keyword : this keyword can be used to refer current class instance variable. this() can be used to invoke current class constructor. this can be used to invoke current class method (implicitly) this can be used to return the current class instance from the method. this can be passed as an argument in the method call. this can be passed as argument in the constructor call.
  • 72. this() : to invoke current class constructor Used for constructor chaining. Used to reuse the constructor. Call to this() must be the first statement in constructor. Syntax this(); // call default constructor this(value1,value2,.....) //call parametrized constructor
  • 73. //this() : to invoke current class constructor public class Rectangle { private int x, y; private int width, height; public Rectangle() { this(0, 0, 0, 0); } public Rectangle(int width, int height) { this(0, 0, width, height); } public Rectangle(int x, int y, int width, int height) { this.x = x; this.y = y; this.width = width; this.height = height; } ………. }
  • 74. this :to invoke current class method (implicitly) Can be used to invoke method of the current class. If you don't use the this keyword, compiler automatically adds this keyword while invoking the method. class Test{ void m1( ) { …. } void m2( ) { m1() } …. } class Test{ void m1( ) { …. } void m2( ) { this.m1() } …. } compiler Test.java Test.class
  • 75. this: to pass as an argument in the method class Test { int a; int b; Test() { a = 40; b = 60; } // Method that receives 'this' keyword as parameter void display(Test obj) { System.out.println("a = " + a + " b = " + b); } // Method that pases current class instance void get() { display(this); } public static void main(String[] args) { Test object = new Test(); object.get(); } } Output:- a=40 b=60
  • 77. [email protected] this: to pass as argument in the constructor call class B{ A obj; B(A obj) { this.obj=obj; } void display(){ System.out.println(obj.data); //10 } } class A{ int data=10; A() { B b=new B(this); b.display(); } public static void main(String args[]){ A a=new A(); } }
  • 78. this keyword in java A reference variable that refers to the current object. Usage of this keyword :  this keyword can be used to refer current class instance variable.  this() can be used to invoke current class constructor.  this can be used to invoke current class method (implicitly)  this can be used to return the current class instance from the method.  this can be passed as an argument in the method call.  this can be passed as argument in the constructor call. this keyword cannot be used in static context.
  • 79. Inheritance  A mechanism in which one object acquires all the properties and behaviors of parent object.  Represents the IS-A relationship, also known as parent-child relationship  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.  A class which is inherited is called parent or super class and the new class is called child or subclass. Inheritance in java is used:  For Method Overriding (so runtime polymorphism can be achieved).  For Code Reusability. Syntax of Java Inheritance: class Subclass-name extends Superclass-name { //methods and fields }
  • 80. Types of inheritance in java Multiple inheritance is not supported in java through class
  • 81. Object class is the superclass of all the classes in java by default. Every class in Java is directly or indirectly derived from the Object class. Object class is present in java.lang package. class A { …….. } class A extends Object { …….. } Object class
  • 82. class A { ……. } class B extends A { ……. } class A extends Object { …….. } class B extends A { ……. } Object class
  • 83. Commonly used Methods of Object class: Method Description public boolean equals(Object obj) compares the given object to this object. protected Object clone() throws CloneNotSupportedException creates and returns the exact copy (clone) of this object. public String toString() returns the string representation of this object. public final void notify() wakes up single thread, waiting on this object's monitor. public final void notifyAll() wakes up all the threads, waiting on this object's monitor. public final void wait(long timeout)throws InterruptedException causes the current thread to wait for the specified milliseconds, until another thread notifies (invokes notify() or notifyAll() method). protected void finalize()throws Throwable is invoked by the garbage collector before object is being garbage collected.
  • 84. Account SavingAccount Single Inheritance Account • String accountId • double accountBalance SavingAccount • double interestRate • double minimumBalance
  • 85. Account SavingAccount SilverSavingAccount Multilevel Inheritance Account • String accountId • double acctBalance SavingAccount • double interestRate • double minimumBalance SilverSavingAcccount • String specialOfferId
  • 86. Account SavingAccount CurrentAccount Hierarchical Inheritance Account • String accountId • double acctBalance SavingAccount • double interestRate • double minimumBalance CurrentAccount • double transactionFee;
  • 87. [email protected] Multiple Inheritance A feature where a class can inherit properties of more than one parent class. Java doesn’t allow multiple inheritance by using classes ,for simplicity and to avoid the ambiguity caused by it. It creates problem during various operations like casting, constructor chaining etc.
  • 88. [email protected] Multiple Inheritance and Ambiguity class A { void show() { System.out.println("Hello");} } class B { void show() { System.out.println("Welcome"); } } class C extends A,B //suppose if it was allowed { public static void main(String args[]) { C obj=new C(); obj.show(); //ambiguity } }
  • 90. [email protected] Multiple inheritance in Java by interface If a class implements multiple interfaces, or an interface extends multiple interfaces.
  • 92. Method Overriding If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in java. Usage :  Used to provide specific implementation of a method that is already provided by its super class.  Used for runtime polymorphism class Vehicle{ void run(){System.out.println("Vehicle is running");} } class Bike extends Vehicle{ void run(){System.out.println("Bike is running ”);} public static void main(String args[]){ Bike obj = new Bike(); obj.run(); } Example:
  • 93. class Shape{ void draw() { System.out.println("No Shape"); } } class Rectangle extends Shape{ void draw() { System.out.println("Drawing rectangle"); } } class Circle extends Shape{ void draw() { System.out.println("Drawing circle"); } } class Triangle extends Shape{ void draw() { System.out.println("Drawing circle"); } } public class Test{ public static void main(String args[]){ Shape s; s=new Shape(); s.draw(); s =new Circle(); s.draw(); s=new Rectangle(); s.draw(); s=new Triangle(); s.draw(); } } At compile-time:
  • 94. class Shape{ void draw() { System.out.println("No Shape"); } } class Circle extends Shape{ void draw() { System.out.println("Drawing circle"); } } class Rectangle extends Shape{ void draw() { System.out.println("Drawing rectangle"); } } class Triangle extends Shape{ void draw() { System.out.println("Drawing circle"); } } public class Test{ public static void main(String args[]){ Shape s; s=new Shape(); s.draw(); s =new Circle(); s.draw(); s=new Rectangle(); s.draw(); s=new Triangle(); s.draw(); } } At run-time:
  • 95. Rules for Method Overriding:  Method must have same name as in the parent class  Method must have same parameter as in the parent class.  Method must have same return type(or sub-type).  Must be IS-A relationship (inheritance).  private method cannot be overridden.  final method cannot be overridden  static method cannot be overridden because static method is bound with class whereas instance method is bound with object.  We can not override constructor as parent and child class can never have constructor with same name.  Access Modifier of the overriding method (method of subclass) cannot be more restrictive than the overridden method of parent class.  Binding of overridden methods happen at runtime which is known as dynamic binding.
  • 96. ExceptionHandling with MethodOverriding in Java  If the superclass method does not declare an exception, subclass overridden method cannot declare the checked exception. class Child extends Parent{ void msg()throws IOException { System.out.println(“child"); } public static void main(String args[]) { Parent p=new Child(); p.msg(); } } class Parent{ void msg() { System.out.println("parent"); } } Output:Compile Time Error
  • 97.  If the superclass method does not declare an exception, subclass overridden method cannot declare the checked exception but can declare unchecked exception. class Parent{ void msg() { System.out.println("parent"); } } class Child extends Parent{ void msg()throws ArithmeticException { System.out.println("child"); } public static void main(String args[]) { Parent p=new Child(); p.msg(); } } Output:child
  • 98.  If the superclass method declares an exception, subclass overridden method can declare same, subclass exception or no exception but cannot declare parent exception. class Child extends Parent{ void msg()throws Exception { System.out.println("child"); } public static void main(String args[]) { Parent p=new Child(); try{ p.msg(); }catch(Exception e){ } } } class Parent{ void msg()throws ArithmeticException{ System.out.println("parent"); } } Output:Compile Time Error
  • 99. class Parent{ void msg()throws Exception{ System.out.println("parent"); } } Class Child extends Parent{ void msg()throws ArithmeticException{ System.out.println("child"); } public static void main(String args[]){ Parent p=new Child(); try{ p.msg(); }catch(Exception e){} } } Example in case subclass overridden method declares subclass exception Output:child
  • 100. Covariant Return Type Specifies that the return type may vary in the same direction as the subclass. Since Java5, it is possible to override method by changing the return type if subclass overrides any method, but it changes its return type to subclass type. class ShapeFactory { public Shape newShape() { ………… } } class CircleFactory extends ShapeFactory { public Circle newShape() { …… } } class Shape { ……… } class Circle extends Shape { ……… }
  • 101. super keyword A reference variable that is used to refer immediate parent class object. super keyword cannot be used in static context. Usage :  super is used to refer immediate parent class instance variable.  super() is used to invoke immediate parent class constructor,.  super is used to invoke immediate parent class method.
  • 102. super used to refer immediate parent class instance variable: class Vehicle{ int speed=70; } class Bike extends Vehicle{ int speed=100; void display(){ System.out.println(super.speed);// Vehicle speed System.out.println(speed);// Bike speed } public static void main(String args[]){ Bike b=new Bike(); b.display(); } }
  • 103. super() to invoke parent class constructor: class Vehicle{ Vehicle(){System.out.println("Vehicle created");} } class Bike extends Vehicle{ Bike(){ super();//invokes parent class constructor System.out.println("Bike created"); } public static void main(String args[]){ Bike b=new Bike(); } }
  • 104.  If used, super() must be the first statement inside the constructor, hence either super() or this() can be used inside the constructor.  super() is added in each class constructor automatically by compiler if there is no super() or this(). class Bike{ Bike() { } } class Bike{ Bike() { super(); } } compiler Bike.java Bike .classa super() :to invoke parent class constructor
  • 105. super used to invoke parent class method: class Vehicle{ void show(){System.out.println("Vehicle Runing");} } class Bike extends Vehicle{ void show(){System.out.println("Bike Runing "); } void display(){ super.show(); show(); } public static void main(String args[]){ Bike b=new Bike(); b.display(); } }
  • 106. final Keyword Used to restrict the user. final can be: 1) VariableIf you make any variable as final, you cannot change the value of final variable(It will be constant). 2) Method->If you make any methode as final, you cannot override it. 3) Class->If you make any class as final, you cannot extend it.
  • 107.  final method is inherited but you cannot override it.  A final variable that is not initialized at the time of declaration is known as blank final variable.  We can initialize blank final variable only in constructor. For example: class Test{ final int i;//blank final variable Test(){ i=80; ...... } }  If a method is declared private and final in superclass then we can have method with the same signature in subclass also because private is not inherited.  Constructor cannot be declared as final because constructor is never inherited. final Keyword
  • 109. Java Package Group of similar types of classes, interfaces and sub-packages. Types: built-in package (such as java, lang, io, util, sql etc.) user-defined package. Advantages:  Used to categorize the classes and interfaces so that they can be easily maintained.  Provides access protection.  Removes naming collision.
  • 111. Ways to access the package from outside the package: 1) import packageName.*; 2) import packageName.classname; 3) fully qualified name. If you import a package, subpackages will not be imported.
  • 113. Access Modifiers Specifies accessibility (scope) of a data member, method, constructor or class. Types :  private  package-private (no explicit modifier)  protected  public There are many non-access modifiers such as static, abstract, synchronized, native, volatile, transient etc.
  • 114. Access Modifier within class within package outside package by subclass only outside package private Y N N N package-private (no explicit modifier) Y Y N N protected Y Y Y N public Y Y Y Y Note: A class cannot be private or protected except nested class.
  • 115. [email protected] Modifier A B C D public Y Y Y Y protected Y Y Y N no modifier Y Y N N private Y N N N Visibiity The following table shows where the members of the A class are visible for each of the access modifiers that can be applied to them. Package 1 A B Package 2 C D subclass
  • 116. Java Array Collection of similar type of elements. Contiguous memory location. Fixed size. Index based, first element of the array is stored at 0 index.
  • 117. Types of Array: Single Dimensional Array Multidimensional Array Single Dimensional Array in java Syntax: dataType[] arr; (or) dataType []arr; (or) dataType arr[]; Instantiation : arrayRefVar=new datatype[size]; Declaration, Instantiation and Initialization : int a[]={33,3,4,5};//declaration, instantiation and initialization
  • 119. [email protected] Diamond problem An ambiguity that can arise as a consequence of allowing multiple inheritance. Since Java 8 default methods have been permitted inside interfaces, which may cause ambiguity in some cases.
  • 120. [email protected] Diamond Structure:Case#1 [+] void m () <<default>> <<interface>> A <<interface>> B <<interface>> C [+] void main(String arg[]) <<static>> <<class>> D interface A { default void m() { System.out.println("m() from interface A "); } } interface B extends A { } interface C extends A { } public class D implements B,C { public static void main(String[] args) { new D().m(); } }
  • 121. [email protected] Diamond Structure:Case#2 [+] void m () <<default>> <<interface>> A [+] void m () <<default>> <<override>> <<interface>> B <<interface>> C [+] void main(String arg[]) <<static>> <<class>> D interface A { default void m() { System.out.println("m() from interface A "); } } interface B extends A { @Override default void m() { System.out.println("m() from interface B "); } } interface C extends A { } public class D implements B,C { public static void main(String[] args) { new D().m(); } }
  • 122. [email protected] Diamond Structure:Case#3 [+] void m () <<default>> <<interface>> A [+] void m () <<default>> <<override>> <<interface>> B [+] void m () <<default>> <<override>> <<interface>> C [+] void m () <<override>> [+] void main(String arg[]) <<static>> <<class>> D interface A { default void m() { System.out.println("m() from interface A "); } } interface B extends A { @Override default void m() { System.out.println("m() from interface B "); } } interface C extends A { @Override default void m() { System.out.println("m() from interface C"); } } public class D implements B,C { @Override public void m() { B.super.m(); } public static void main(String[] args) { new D().m(); } }