0% found this document useful (0 votes)
32 views165 pages

Unit 1 Core Java - 240510 - 125907

unit 1 WT

Uploaded by

manyab009
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
32 views165 pages

Unit 1 Core Java - 240510 - 125907

unit 1 WT

Uploaded by

manyab009
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 165

Core Java

Content
 History of Java
 Features of Java
 Oops Concepts
 Keywords
 Opertaors
 Data Types
 Varaibles
 Array
 Methods
 Inheritance
 Interface
 Abstract Class
Content…
 Method Overloading
 Method Overriding
 Polymorphism in Java
 String Handling
 Package
 Exceptional Handeling
History of Java
 Java started out as a research project.

 Research began in 1991 as the Green Project at Sun Microsystems, Inc.

 Research efforts birthed a new language, OAK. ( A tree outside of the


window of James Gosling’s office at Sun).

 It was developed as an embedded programming language, which would


enable embedded system application.

 It was not really created as web programming language.

 Java is available as jdk and it is an open source s/w.


History of Java…
Language was created with 5 main goals:
• It should be object oriented.
• A single representation of a program could be executed on
multiple operating systems. (i.e. write once, run anywhere)
• It should fully support network programming.
• It should execute code from remote sources securely.
• It should be easy to use.

 Oak was renamed Java in 1995.

 Now Sun Microsystems is a subsidiary of Oracle Corporation.


Java Logo
Java Platforms
There are three main platforms for Java:

 Java SE (Java Platform, Standard Edition) – runs on desktops and


laptops.

 Java ME (Java Platform, Micro Edition) – runs on mobile devices such


as cell phones.

 Java EE (Java Platform, Enterprise Edition) – runs on servers.


Java Terminology

•Java Development Kit:


It contains one (or more) JRE's along with the various development tools like the
Java source compilers, bundling and deployment tools, debuggers, development
libraries, etc.

•Java Virtual Machine:


An abstract machine architecture specified by the Java Virtual Machine
Specification.

It interprets the byte code into the machine code depending upon the underlying OS
and hardware combination. JVM is platform dependent. (It uses the class libraries,
and other supporting files provided in JRE)
Java Terminology (contd…)

 Java Runtime Environment:


A runtime environment which implements Java Virtual Machine, and provides
all class libraries and other facilities necessary to execute Java programs. This
is the software on your computer that actually runs Java programs.

JRE = JVM + Java Packages Classes (like util, math, lang, awt, swing etc)
+runtime libraries.
Java Virtual Machine
 Class loader subsystem: A mechanism for loading types (classes and
interfaces) given fully qualified names.

 The Java virtual machine organizes the memory it needs to execute a


program into several runtime data areas.

 Each Java virtual machine also has an execution engine: a mechanism


responsible for executing the instructions contained in the methods of
loaded classes.
Difference b/w C++ & Java
Features of Java
 Simple
 Object Oriented
 Plateform Independent
 Compile, Interpreted and High Performance
 Portable
 Reliable
 Secure
 Multithreaded
 Dynamic
 Distributed
 Architecture-Neutral
Java Features
 Simple:
 Syntax is based on C++
 No pointers
 Automatic garbage collection
 Rich pre-defined class library

 Object Oriented : Object-oriented programming (OOPs) is a methodology that


simplifies software development and maintenance by providing some rules.
 Basic concepts of OOPs are:
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
Java Features
 Plateform Independent :
 Java code can be executed on multiple platforms, for example,
Windows, Linux, Sun Solaris, Mac/OS, etc.
 Java code is compiled by the compiler and converted into bytecode.
 This bytecode is a platform-independent code because it can be run on
multiple platforms, i.e., Write Once and Run Anywhere (WORA).
Java Features
 Compile, Interpreted and High Performance
• Java compiler generate byte-codes, not machine code
• The compiled byte-codes are platform-independent
• Java byte codes are translated on the fly to machine readable instructions in
runtime (Java Virtual Machine)
• Easy to translate directly into machine code by using a just-in-time compiler.
 Portable
• Same application runs on all platforms
• The sizes of the primitive data types are always the same
• The libraries define portable interfaces
Java Features
 Reliable/Robust
• Extensive compile-time and runtime error checking.
• No pointers but real arrays. Memory corruptions or unauthorized memory
accesses are impossible
• Automatic garbage collection tracks objects usage over time

 Secure

• Java’s robustness features makes java secure.


• Access restrictions are forced (private, public)
• No viruses can easily communicate.
• Byte Code verifier.
Java Features
 Multithreaded
• It supports multithreaded programming.
• Need not wait for the application to finish one task before beginning
another one.
 Dynamic
• Libraries can freely add new methods and instance variables without any
effect on their clients
• Interfaces promote flexibility and reusability in code by specifying a set of
methods an object can perform, but leaves open how these methods should
be implemented .
Java Features
 Distributed
• Java is designed for the distributed environment of the Internet, because
it handles TCP/IP protocols.
• Allows objects on two different computers to execute procedures
remotely by using package called Remote Method Invocation (RMI).

 Architecture-Neutral
• Goal of java designers is “write once; run anywhere, any time,
forever.”
Object Oriented Programming
Concepts
 Objects
 Classes
 Data abstraction and Encapsulation
 Inheritance
 Polymorphism
 Dynamic Binding
 A class is collection of objects of similar type or it is a template.
Ex: fruit mango;

class object
 Objects :are instances of the type class.

 Encapsulation :The wrapping up of data and functions into a single unit (


called class) is known as encapsulation. Data encapsulation is the most
striking features of a class.

 Abstraction: refers to the act of representing essential features without


including the background details or explanations.

 Inheritance: is the process by which objects of one class acquire the


properties of another class. The concept of inheritance provides the
reusability.
 Polymorphism: It allows the single method to perform different actions
based on the parameters.

 Dynamic Binding: When a method is called within a program, it associated


with the program at run time rather than at compile time is called dynamic
binding.
Benefits of OOP
 Through inheritance, we can eliminate redundant code and extend the use of
existing classes.

 The principle of data hiding helps the programmer to build secure programs.

 It is easy to partition the work in a project based on objects.

 Object oriented system easily upgraded from small to large systems.

 Software complexity can be easily managed.


Applications of OOP
 Real-time systems

 Object-oriented databases

 Neural networks and parallel programming

 Decision support and office automation systems

 CAD/CAM systems
 Java is a pure oop or not ?

 Java is not a pure object-oriented programming language because it


supports primitive data types and everything is not an object in Java.

• By default java is not pure object oriented language.

• Java is called as Hybrid language.

• Pure oop languages are “small talk”, ”ruby”, “Eiffel”.


Keywords
abstract continue goto package synchronized

assert default if private this

boolean do implements protected throw

break double import public throws

byte else instanceOf return transient

case extends int short try

catch final interface static void

char finally long strictfp volatile

class float native super while


const for new switch
Operators

 Arithmetic Operators
 Bitwise Operators
 Relational Operators
 Boolean Logical Operators
Arithmetic Operators(1)

Operator Result

+ Addition

– Subtraction

* Multiplication

/ Division

% Modulus
Arithmetic Operators(2)
Operator Result
++ Increment

+= Addition assignment

–= Subtraction assignment

*= Multiplication assignment

/= Division assignment

%= Modulus assignment

–– Decrement
Relational Operators
 The Relational operators determine the relationship that one operand has to
the other.
 They determine equality and ordering.

Operator Result
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
Bitwise Operators(1)
• Bitwise operators can be applied to the integer types, long, int, short,
byte and char.
• These operators act upon the individual bits of their operands.

Operator Result

~ Bitwise unary NOT


& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
>> Shift right
>>> Shift right zero fill
<< Shift left
Bitwise Operators(2)
Operator Result

&= Bitwise AND assignment

|= Bitwise OR assignment

^= Bitwise exclusive OR assignment

>>= Shift right assignment

>>>= Shift right zero fill assignment

<<= Shift left assignment


Boolean Logical Operators(1)
 The Boolean logical operators operate only on boolean operands.
 All of the binary logical operators combine two boolean values to form a
resultant boolean value.

Operator Result

& Logical AND


| Logical OR
^ Logical XOR (exclusive OR)
|| Short-circuit OR
&& Short-circuit AND
! Logical unary NOT
Operators in Java
Data Types
 Data types specify the different sizes and values that can be stored in
the variable. There are two types of data types in Java:

▪ Primitive data types: The primitive data types include boolean, char,
byte, short, int, long, float and double.

▪ Non-primitive data types: The non-primitive data types


include Classes, Interfaces and Arrays.
Variable
 A variable is a container which holds the value while the Java
program is executed. A variable is assigned with a data type.
 It is a combination of "vary + able" which means its value can be
changed.
 Variable is a name of memory location. There are three types of
variables in java:

1. Local Variable
2. Instance Variable
3. Static Variable
Syntax: Data_Type Variable name = Value it stores ;
int a = 10;
Local Variable
 A variable declared inside the body of the method is called local
variable. You can use this variable only within that method and the
other methods in the class aren't even aware that the variable exists.

 A local variable cannot be defined with "static" keyword.


Instance Variable
 A variable declared inside the class but outside the body of the method,
is called an instance variable.

 It is not declared as static.

 It is called an instance variable because its value is instance-specific


and is not shared among instances.
Static variable

 A variable that is declared as static is called a static variable.

 It cannot be local. Static variable are declared in a class, but outside a


method ,constructor or any block.

 You can create a single copy of the static variable and share it among
all the instances (objects) of the class.

 Memory allocation for static variables happens only once when the
class is loaded in the memory.
 Static variable belongs to class not an individual object.
Example
class Variable
{
static int a = 1; //static variable
int b = 99; //instance variable
public static void main(String[] args)
{
int c = 90; //local variable
Variable ref = new Variable ();
System.out.println(c);
System.out.println(a); // Variable.a //ref.a
System.out.println( ref.b );
}
}

OUTPUT: 90
1
99
Example
class Variable
{
static int a = 1; //static variable
int b = 99; //instance variable
}
class Variablemain
{
public static void main(String[] args)
{
int c = 90; //local variable
Variable ref = new Variable ();
System.out.println (c);
System.out.println (ref.a); // Variable.a
System.out.println (ref.b); OUTPUT: 90
} 1
99
}
Static Variable Access Using Class name
class StaticVariable1
{
public static void main(String args[])
{
Test.marks=80;
System.out.println("Roll no ="+ Test.rollno);
System.out.println("Marks ="+ Test.marks);
}
}
class Test
{
static int rollno=120;
static int marks; OUTPUT: Roll no =120
Marks = 80
}
Static Variable Access Using Object of Class
class StaticVariable2
{
public static void main(String args[])
{
Test ref= new Test();
ref.marks=80;
System.out.println("Roll no ="+ ref.rollno);
System.out.println("Marks ="+ ref.marks);
}
}
class Test
{
static int rollno=120;
static int marks; OUTPUT: Rollno =120;
} Marks =80;
Example
class StaticVariable4
{
public static void main(String args[])
{
Test ref1= new Test();
Test ref2= new Test();
ref1.marks=100;
ref2.marks=200;
System.out.println("Marks ="+ ref1.marks);
System.out.println("Marks ="+ ref2.marks);
}
}
class Test
{ OUTPUT: Marks = 200
static int marks; Marks = 200
}
Example
class Staticvariable3
{
static int a=10;
void fun()
{
int b=10;
System.out.println (a+" "+b);
a++;
b++;
}
public static void main(String[] args)
{
Staticvariable3 r = new Staticvariable3();
r.fun();
r.fun();
}}
OUTPUT: 10 10
11 10
Final Variable
 A final variable can be explicitly initialized only once.
 A reference variable declared final can never be reassigned to refer to a
different object.
 Ex:
class Main {
public static void main(String[] args)
{
final int AGE = 32;
AGE = 45;
System.out.println("Age: " + AGE);
}
}
Array
 An array is a collection of similar type of elements which has
contiguous memory location.

 Java array is an object which contains elements of a similar data type.


Additionally, The elements of an array are stored in a contiguous
memory location.

 Array in Java is index-based, the first element of the array is stored at


the 0th index, 2nd element is stored on 1st index and so on.
Array …
 Advantages
• Code Optimization: It makes the code optimized, we can retrieve or
sort the data efficiently.
• Random access: We can get any data located at an index position.

 Disadvantages
• Size Limit: We can store only the fixed size of elements in the array.
• It doesn't grow its size at runtime.
• To solve this problem, collection framework is used in Java which
grows automatically.
Types of Array in Java

 Single Dimensional Array


 Multidimensional Array

 Syntax to Declare an Array in Java :


dataType[] arr; (or)
dataType []arr; (or)
dataType arr[];
eg: int[] myArray;

 Syntax to Instantiation an Array


datatype []arrayName = new datatype [ size ]
eg: int []array = new int[5];
Note:
• Initialization is when you provide an initial value for a variable.
• Instantiation is where an object (class instance) is created.
Example of Array
//Java Program to illustrate how to declaration, instantiation and initialization
//and traverse the Java array.
class Traversarray{
public static void main(String args[]){
int a[]=new int[5];//declaration and instantiation
a[0]=10; //initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;
//traversing array
for(int i=0; i<a.length; i++)// length is the property of array
System.out.println(a[i]);
}}
Example of Array…
class Traversarray
{
public static void main(String args[])
{
int a[]={33,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0; i<a.length; i++)//length is the property of array
System.out.println(a[i]);
}
}
Methods
 A method is a block of code or collection of statements or a set of code
grouped together to perform a certain task or operation.

 Method is used to achieve the reusability of code. We write a method


once and use it many times. We do not require to write code again and
again.
 It also provides the easy modification and readability of code, just by
adding or removing a chunk of code. The method is executed only
when we call or invoke it.
Method Declaration
 The method declaration provides information about method attributes,
such as visibility, return-type, name, and arguments.
 Method Signature: Every method has a method signature. It is a part
of the method declaration. It includes the method
name and parameter list.
Method Declaration

 Access Specifier: It is the access type of the method. It specifies the


visibility of the method. Java provides four types of access specifier:

• Public: The method is accessible by all classes when we use public


specifier in our application.
• Private: When we use a private access specifier, the method is
accessible only in the classes in which it is defined.
• Protected: When we use protected access specifier, the method is
accessible within the same package or subclasses in a different package.
• Default: When we do not use any access specifier in the method
declaration, Java uses default access specifier by default. It is visible
only from the same package only.
Method Declaration

 Return Type: Return type is a data type that the method returns. It may
have a primitive data type, object, collection, void, etc. If the method
does not return anything, we use void keyword.
 Method Name: It is a unique name that is used to define the name of a
method. It must be corresponding to the functionality of the method.
Suppose, if we are creating a method for subtraction of two numbers,
the method name must be subtraction(). A method is invoked by its
name.
 Parameter List: It is the list of parameters separated by a comma and
enclosed in the pair of parentheses. It contains the data type and
variable name. If the method has no parameter, left the parentheses
blank.
 Method Body: It is a part of the method declaration. It contains all the
actions to be performed. It is enclosed within the pair of curly braces.
Types of Method

 There are two types of methods in Java:


• Predefined Method
• User-defined Method

 Predefined Method
• In Java, predefined methods are the method that is already defined in
the Java class libraries.
• It is also known as the standard library method or built-in method.
• We can directly use these methods just by calling them in the program
at any point. Some pre-defined methods are length(), equals(),
compareTo(), sqrt(), etc.
Types of Method…

 User-defined Method :
• This method written by the user or programmer.
• These methods are modified according to the requirement.

 Static Method:
• A method that has static keyword is known as static method.
• We can also create a static method by using the keyword static before
the method name.
• The main advantage of a static method is that we can call it without
creating an object.
• It can access static data members and also change the value of it. It is
invoked by using the class name.
• The best example of a static method is the main() method.
Types of Method…

 Instance Method :
• The method of the class is known as an instance method.
• It is a non-static method defined in the class.
• Before calling or invoking the instance method, it is necessary to create
an object of its class.

 Abstract Method :
• The method that does not has method body is known as abstract
method.
• It always declares in the abstract class. It means the class itself must
be abstract if it has abstract method.
• To create an abstract method, we use the keyword abstract.
Class in Java
 A class is a group of objects which have common properties. It is a
template or blueprint from which objects are created. It is a logical entity. It
can't be physical.
 A class in Java can contain:
• Fields
• Methods
• Constructors
• Blocks
• Nested class and interface

 Syntax to declare a class:


class <class_name>
{
field;
method;
}
Abstract Method
• A method that does not have its implementation or body is known as an
abstract method in java. An abstract method in java is declared inside
an abstract class.
• Abstract methods in java do not have an implementation, abstract
methods only have a method signature (declaration).
• The basic syntax of abstract method in java is:
abstract type method-name(parameter-list);
• If a class has an abstract method, then the class should be declared
abstract as well.
• An abstract class may or may not contain an abstract method in java but
an abstract class must be declared inside an abstract class.
• If concrete or regular class extends an abstract class, then the child class
must have to implement all the abstract methods of the parent abstract
class.
Example
abstract class Students
{
public abstract void Branch();
public void course()
{ System.out.println("Btech"); }
}
class CSE extends Students {
public void Branch() {
// The body of Branch() is provided here
System.out.println("Computer Science");
}}
class AbstractMain1 {
public static void main(String[] args) {
CSE obj = new CSE(); // Create a object
obj.course();
obj.Branch();
} OUTPUT: Btech
} Computer Science
Inheritance
 Inheritance in Java is a mechanism in which one object acquires all
the properties and behaviors of a parent object. It is an important part
of OOPs (Object Oriented programming system).

 Inheritance represents the IS-A relationship which is also known as


a parent-child relationship.

 We can inherit from an existing class, you can reuse methods and fields
of the parent class. Moreover, we can add new methods and fields in
your current class also.

 Suppose, there are two classes named Father and Child and we want
to inherit the properties of the Father class in the Child class. We can
achieve this by using the extends keyword.
Inheritance
 Why use inheritance in java
• For Method Overriding (so runtime polymorphism can be achieved).
• For Code Reusability.

 Terms used in Inheritance


 Class: A class is a group of objects which have common properties. It is a
template or blueprint from which objects are created.

 Sub Class/Child Class: Subclass is a class which inherits the other class. It
is also called a derived class, extended class, or child class.

 Super Class/Parent Class: Superclass is the class from where a subclass


inherits the features. It is also called a base class or a parent class.

 Reusability: Reuse the fields and methods of the existing class when you
create a new class.
Programmer salary is:40000.0 Bonus of programmer is:10000

Example of Inheritance
class Employee
{
float salary=40000;
}
class Programmer extends Employee
{
int bonus=10000;
public static void main(String args[])
{
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Output : Programmer salary is: 40000
Bonus of Programmer is:1000
Types of Inheritance
Types of Inheritance
Abstract class in Java

 Abstraction is a process of hiding the implementation details and


showing only functionality to the user.

 A class which is declared with the abstract keyword is known as an


abstract class in Java.

 It can have abstract and non-abstract methods (method with the


body).

 Ways to achieve Abstraction:


• Abstract class (0 to 100%)
• Interface (100%)
Points to Remember

 An abstract class must be declared with an abstract keyword.


 It can have abstract and non-abstract methods.
 It cannot be instantiated.
 It can have constructors and static methods also.
 It can have final methods which will force the subclass not to change
the body of the method.

 Example of abstract class


abstract class A{}
 Example of abstract method
abstract void printStatus();//no method body and abstract
Example
abstract class Bike
{
abstract void run();
}
class Honda4 extends Bike
{
void run(){System.out.println("running safely");}
public static void main(String args[])
{
Bike obj = new Honda4();
obj.run();
}
}
OUTPUT: running safely
interface A{
void a(); class Test5
void b();
{
public static void main(String args[])
void c();
{
void d(); A a=new M();
} a.a();
abstract class B implements A a.b();
{ a.c();
public void c(){System.out.println("I am c");}
a.d();
}}
}
class M extends B
{
OUTPUT: I am a
public void a(){System.out.println("I am a");}
I am b
public void b(){System.out.println("I am b");} I am c
public void d(){System.out.println("I am d");} I am d
}
Interface
 An interface in Java is a blueprint of a class. It has static constants and
abstract methods.

 The interface in Java is a mechanism to achieve abstraction.

 There can be only abstract methods in the Java interface, not method
body.

 It is used to achieve abstraction and multiple inheritance in Java .

 Java Interface also represents the IS-A relationship.


Interface
 Why use Java interface?

• It is used to achieve abstraction.


• By interface, we can support the functionality of multiple inheritance.

 Syntax
interface <interface_name>
{
// declare constant fields
// declare methods that abstract
// by default.
}
Internal addition by the compiler

The Java compiler adds public and abstract keywords before the interface
method. Moreover, it adds public, static and final keywords before data
members.
Example
interface print
{
void display();
}
class A implements print
{
public void display()
{
System.out.println("Hello");
}
public static void main(String args[])
{
A obj = new A(); // printable
obj.print();
}
} OUTPUT : Hello
/Interface declaration: by first user
interface Software
{
void design();
}
//Implementation: by second user
class Requirement implements Software{
public void design()
{System.out.println("Requirement of Software");}
}
class Testing implements Software{
public void design(){System.out.println("Testing of Software");}
}
//Using interface: by third user
class TestInterface1{
public static void main(String args[]){
Testing d=new Testing (); //Software d=new Testing ();
d.design(); Output : Testing of Software
}}
Multiple Inheritance in Interface
 Multiple inheritance is not supported in the case of class because of
ambiguity.
 It is supported in case of an interface because there is no ambiguity. It is
because its implementation is provided by the implementation class.
Example
interface Software{
void design();
•Software and
}
Hardware interface
interface Hardware{
have same methods
void design(); but its
void machine(); implementation is
} provided by class
class TestInterface2 implements Software,Hardware{ TestTnterface1, so
public void design(){System.out.println("Software Designe");} there is no
ambiguity.
public void machine(){System.out.println("Hrdware Machine");}

OUTPUT:
public static void main(String args[]){ SoftwareDesigne
TestInterface2 obj = new TestInterface2 (); •Hrdware Machine
obj.design();
obj.machine();
}
}
Interface inheritance
 A class implements an interface, but one interface extends another interface. Ex-
interface Programming{
void design();
}
interface Java extends Programming{
void database();
}
class TestInterface3 implements Java {
public void design(){System.out.println("Java Software Designing");}
public void database(){System.out.println("Java Database Connectivity");}
public static void main(String args[]){
TestInterface3 obj = new TestInterface3();
obj.design();
obj.database();
}
} Output: Java Software Designing
Java Database Connectivity
Nested Interface in Java

 An interface can have another interface which is known as a nested


interface. Ex-

interface Software
{
void development();
interface Java
{
void design();
}
}
Interface
 Since Java 8, we can have method body in interface. But we need to
make it
 default or
 static method
Difference between Abstract class and
Interface
Method Overloading in Java

 If a class has multiple methods having same name but different in


parameters, it is known as Method Overloading.

 Advantage of method overloading


• Method overloading increases the readability of the program.

 Different ways to overload the method: There are three ways to


overload the method in java

• Based on the number of parameters


• Based on the data type of the parameter
• Based on the sequence of data types in parameters
Method Overloading: changing no. of arguments
 In this example, we are creating static methods so that we don't need
to create instance for calling methods.

class Sum
{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1
{
public static void main(String[] args)
{
System.out.println(Sum.add(10,20));
System.out.println(Sum.add(10,20,30));
}}

Output: 30
60
Method Overloading: Based on the data type of
the parameter
class Sum{
static int add(int a, int b){return a+b;}
static double add(double a, double b){return a+b;}
}
class TestOverloading2
{
public static void main(String[] args)
{
System.out.println(Sum.add(10,20));
System.out.println(Sum.add(12.3,10.3));
}}
OUTPUT : 30
22.6
Method Overloading: Based on the sequence of
data types in parameters
class DispOvrload {
public void show(char ch, int numb)
{
System.out.println ("The 'show method' is defined."); }
public void show(int numb, char ch)
{
System.out.println ("The 'show method' is defined." ); } }
class Main
{ public static void main (String args[] )
{
DispOvrload o1 = new DispOvrload();
o1.show(‘A’, 20);
o1.show(40, ‘B');
}}

OUTPUT: The 'show method' is defined.


The 'show method' is defined.
Why Method Overloading is not possible by
changing the return type of method only?
 In java, method overloading is not possible by changing the return type of
the method only because of ambiguity.

class Sum{
static int add(int a,int b){return a+b;}
static double add(int a,int b){return a+b;}
}
class TestOverloading3{
public static void main(String[] args)
{
System.out.println(Sum.add(11,11));//ambiguity
}}
OUTPUT: Compile Time Error
Can we overload java main() method?

 Yes, by method overloading. You can have any number of main methods in a class
by method overloading. But JVM calls main() method which receives String
array [] as arguments only.
 EX:

class TestOverloading4
{
public static void main(String[] args)
{System.out.println ("main with String[]");}
public static void main(String args)
{System.out.println ("main with String");}
public static void main()
{System.out.println ("main without args");}}

OUTPUT: main with String[]


Method Overloading and Type
Promotion
 One type is promoted to another implicitly if no matching datatype is found.
 Example of Method Overloading with TypePromotion

class OverloadingCalculation1
{
void sum(int a,long b){System.out.println(a+b);}
void sum(int a,int b,int c){System.out.println(a+b+c);}

public static void main(String args[]){


OverloadingCalculation1 obj=new OverloadingCalculation1();
obj.sum(20,20);//now second int literal will be promoted to long
obj.sum(20,20,20);
} }
Output: 40
60
Example of Method Overloading with
Type Promotion if matching found
 If there are matching type arguments in the method, type promotion is not
performed.
class OverloadingCalculation2
{
void sum(int a,int b)
{System.out.println("int arg method invoked");}
void sum(long a,long b)
{System.out.println("long arg method invoked");}

public static void main(String args[])


{
OverloadingCalculation2 obj=new OverloadingCalculation2();
obj.sum(20,20);//now int arg sum() method gets invoked
}
}
OUTPUT: "int arg method invoked
Example of Method Overloading with
Type Promotion in case of ambiguity
 If there are no matching type arguments in the method, and each method
promotes similar number of arguments, there will be ambiguity.

class OverloadingCalculation3{
void sum(int a,long b)
{System.out.println("a method invoked");}
void sum(long a,int b)
{System.out.println("b method invoked");}

public static void main(String args[])


{
OverloadingCalculation3 obj=new OverloadingCalculation3();
obj.sum(20,20);//now ambiguity
}
}
Output:Compile Time Error
Advantages & Disadvantages of
Method Overloading
 Advantages of Method Overloading
• It is used to perform a task efficiently with smartness in programming.
• It increases the readability of the program.
• The Method overloading allows methods that perform proximately related
functions to be accessed using a common name with slight variation in
argument number or types.
• They can also be implemented on constructors allowing different ways to
initialize objects of a class.
 Disadvantages of Method Overloading
• It's esoteric. Not very easy for the beginner to opt this programming
technique and go with it.
• It requires more significant effort spent on designing the architecture (i.e.,
the arguments' type and number) to up front, at least if programmers' want to
avoid massive code from rewriting.
Method Overriding in Java

 If subclass (child class) has the same method as declared in the parent
class, it is known as method overriding in Java.
 If a subclass provides the specific implementation of the method that
has been declared by one of its parent class, it is known as method
overriding.

 Usage of Java Method Overriding

• Method overriding is used to provide the specific implementation of a


method which is already provided by its superclass.
• Method overriding is used for runtime polymorphism
Rules for Java Method Overriding

 The method must have the same name as in the parent class
 The method must have the same parameter as in the parent class.
 There must be an IS-A relationship (inheritance).
Example of method overriding
 In this example, we have defined the run method in the subclass as defined in the parent class
but it has some specific implementation.
 The name and parameter of the method are the same, and there is IS-A relationship between the
classes, so there is method overriding.

class Animal{
//defining a method
void speed(){System.out.println("Animals are running fast");}
}
//Creating a child class
class Cat extends Animal{
//defining the same method as in the parent class
void speed(){System.out.println("cat is running safely");}

public static void main(String args[]){


Cat obj = new Cat(); //creating object
obj.speed(); //calling method
}
} OUTPUT: Cat is running safely
Important Points
 Can we override static method?
• No, a static method cannot be overridden.

 Why can we not override static method?


• It is because the static method is bound with class whereas instance
method is bound with an object. Static belongs to the class area, and an
instance belongs to the heap area.

 Can we override java main method?


• No, because the main is a static method.
Example
 Java Method Overloading • Java Method Overriding
class Animal
{
class OverloadingExample
void eat()
{ {System.out.println("eating...");}
static int add(int a,int b) }
{return a+b;}
class Dog extends Animal{
static int add(int a,int b,int c)
void eat(){System.out.println("eating bread...");}
{return a+b+c;}
} }
Difference between method overloading
and method overriding in java
Polymorphism in Java

 Polymorphism in Java is a concept by which we can perform a single


action in different ways.
 Polymorphism is derived from 2 Greek words: poly and morphs. The
word "poly" means many and "morphs" means forms. So polymorphism
means many forms.
 There are two types of polymorphism in Java:
1. compile-time polymorphism (Static polymorphism)
2. runtime polymorphism. (Dynamic polymorphism)

• We can perform polymorphism in java by method overloading and


method overriding.
 If you overload a static method in Java, it is the example of compile time
polymorphism.
compile-time polymorphism
 Polymorphism that is resolved during compiler time is known as static
polymorphism.
 Method overloading is an example of compile time polymorphism.
class SimpleCalculator{
int add (int a, int b)
{ return a+b; }
int add (int a, int b, int c)
{ return a+b+c; }
}
public class Demo {
public static void main(String args[])
{
SimpleCalculator obj = new SimpleCalculator();
System.out.println(obj.add(10, 20));
System.out.println (obj.add(10, 20, 30));
}}
OUTPUT: 30
60
Runtime Polymorphism in Java

 Runtime polymorphism or Dynamic Method Dispatch is a process


in which a call to an overridden method is resolved at runtime rather
than compile-time.
 Method overriding is an example of Run time polymorphism.
 In this process, an overridden method is called through the reference
variable of a superclass. The determination of the method to be called is
based on the object being referred to by the reference variable.
String Handling

 String is a sequence of characters. But in java, string is an object.


 In java, string is basically an immutable object.
 String class is used to create string object.
 String Handling provides a lot of concepts that can be performed on a
string such as concatenating string, comparing string , substring etc.

 Ex: char[] ch={'j','a','v','a'};


String s=new String(ch);

 Ex: String s="java";


How to create a string object?

 There are two ways to create String object:


• By string literal
• By new keyword
String Literal

 Java String literal is created by using double quotes.


 Ex: String s="welcome";
 String objects are stored in a special memory area known as the
"string constant pool”.
 Each time you create a string literal, the JVM checks the "string
constant pool" first.
 If the string doesn't exist in the pool, a new string instance is created
and placed in the pool.
 If the string already exists in the pool, a reference to the pooled instance
is returned.
String Literal

 Example:
String s1="Welcome";
String s2="Welcome";//It doesn't create a new instance
String Literal

 In the given example, only one object will be created.

 Firstly, JVM will not find any string object with the value "Welcome"
in string constant pool that is why it will create a new object.

 After that it will find the string with the value "Welcome" in the pool, it
will not create a new object but will return the reference to the same
instance.

 To make Java more memory efficient (because no new objects are


created if it exists already in the string constant pool).
By new keyword

 String s=new String("Welcome");

 In such case, JVM will create a new string object in normal (non-pool) heap
memory.

 The literal "Welcome" will be placed in the string constant pool.

 The variable s will refer to the object in a heap (non-pool).


Example
public class StringExample
{
public static void main(String args[])
{
String s1="java";//creating string Java by string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating Java string by new keyword
System.out.println (s1);
System.out.println (s2);
System.out.println (s3);
}}
OUTPUT: java
strings
example
Immutable String in Java

 In Java, String objects are immutable. Immutable simply means


unmodifiable or unchangeable.

 A String is an unavoidable type of variable while writing any application


program. String references are used to store various attributes like username,
password, etc.

 Once String object is created its data or state can't be changed but a new String
object is created.
Example
class Testimmutablestring
{
public static void main(String args[])
{
String s="Sachin";
s.concat(" Tendulkar");//concat() method appends the string at the end
System.out.println(s);//will print Sachin because strings are immutable objects

} }

 OUTPUT: Sachin
Example
Ex 2:
class Testimmutablestring1
{
public static void main(String args[])
{
String s="Sachin";
s=s.concat(" Tendulkar");
System.out.println(s);
}
}
OUTPUT: Sachin Tendulkar
String comparison in JAVA

 We can compare String in Java on the basis of content and reference.

 It is used in authentication (by equals() method), sorting (by


compareTo() method), reference matching (by == operator) etc.

 There are three ways to compare String in Java:


• By Using equals() Method
• By Using == Operator
• By compareTo() Method
By Using equals() Method

 equals() method compares the original content of the string. It compares


values of string for equality. String class provides the following two
methods:

• public boolean equals(Object another) compares this string to the


specified object.
• public boolean equalsIgnoreCase(String another) compares this
string to another string, ignoring case.
By Using equals() Method

Teststringcomparison1.java Teststringcomparison2.java
class Teststringcomparison1{ class Teststringcomparison2{
public static void main(String args[]) public static void main(String args[]){
String s1="Sachin";
{
String s2="SACHIN";
String s1="Sachin";
String s2="Sachin"; System.out.println(s1.equals(s2));//false
String s3=new String("Sachin"); System.out.println(s1.equalsIgnoreCase(s2));//true
String s4="Saurav"; }
System.out.println(s1.equals(s2));//true }
System.out.println(s1.equals(s3));//true
OUTPUT: false
System.out.println(s1.equals(s4));//false
true
} }
OUTPUT: true
true
false
By Using == operator

 The == operator compares references not values.


 EX:
class Teststringcomparison3
{
public static void main(String args[])
{
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
System.out.println(s1==s2);//true (because both refer to same instance)
System.out.println(s1==s3);//false(because s3 refers to instance created in nonpool)
}
}
By Using compareTo() method

 The String class compareTo() method compares values


lexicographically and returns an integer value that describes if first
string is less than, equal to or greater than second string.

 Suppose s1 and s2 are two String objects. If:


• s1 == s2 : The method returns 0.
• s1 > s2 : The method returns a positive value.
• s1 < s2 : The method returns a negative value.
By Using compareTo() method
class Teststringcomparison4{
public static void main(String args[])
{
String s1="Sachin";
String s2="Sachin";
String s3="Ratan";
System.out.println(s1.compareTo(s2));//0
System.out.println(s1.compareTo(s3));//1(because s1>s3)
System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
}
}
Example
class Teststringcomparison4{
public static void main(String args[])
{
String s1="Sachin";
String s2="Sachin";
String s3="Sinchin";
String s4="Ajay";
System.out.println(s1.compareTo(s2));
System.out.println(s1.compareTo(s3));
System.out.println(s1.compareTo(s4));
System.out.println(s2.compareTo(s3));
System.out.println(s3.compareTo(s4));
OUTPUT: 0
System.out.println(s4.compareTo(s3)); -8
}} 18
-8
18
-18
String Concatenation in Java

 In Java, String concatenation forms a new String that is the


combination of multiple strings.

 There are two ways to concatenate strings in Java:


• By + (String concatenation) operator
• By concat() method
By + (String concatenation) operator

 Java String concatenation operator (+) is used to add strings. For


Example:

TestStringConcatenation1.java
class TestStringConcatenation1
{
public static void main(String args[])
{
String s="Sachin"+" Tendulkar";
System.out.println(s);//Sachin Tendulkar
}
}
Example
class TestStringConcatenation2
{
public static void main(String args[])
{
String s=50+30+"Sachin"+40+40;
System.out.println(s);
}
}

OUTPUT: 80Sachin4040

 After a string literal, all the + will be treated as string concatenation


operator.
By concat() method

Ex 2:
class Testimmutablestring1
{
public static void main(String args[])
{
String s="Sachin";
s=s.concat(" Tendulkar");
System.out.println(s);
}
}
OUTPUT: Sachin Tendulkar
Substring in Java

 A part of String is called substring. In other words, substring is a


subset of another String.
 We can get substring from the given String object by one of the two
methods:

1. public String substring(int startIndex):


2. public String substring(int startIndex, int endIndex):

 startIndex: inclusive
 endIndex: exclusive
Example
public class SubstringExample1 {
public static void main(String[] args) {
String s1="WEBTECHNOLOGY";
System.out.println(s1.substring(0));
String substr2 = s1.substring(2,11); // Starts from 5 and goes to 10
System.out.println(substr2);
String substr3 = s1.substring(5,15); // Returns Exception
}
}

OUTPUT: WEBTECHNOLOGY
BTECHNOLO
Exception in thread "main"
java.lang.StringIndexOutOfBoundsException: begin 5, end 15, length 13
Length of String
 The java string length() method finds the length of the string. It returns
count of total number of characters.
 EX:
public class LengthExample
{
public static void main(String args [])
{
String s1="Hello World";
System.out.println("string length is:" +s1.length());
}
}
OUTPUT: string length is: 11
Java String Methods

 String charAt()
 String replace()
 String concat()String contains()
 String endsWith()
 String equals()
 equalsIgnoreCase()
 String format()
 String getBytes()
 String getChars()
 String indexOf()
 String intern()
 String isEmpty()
 String join()
 String lastIndexOf()
Java String toUpperCase() and
toLowerCase() method
public class Stringoperation1
{
public static void main(String arg[])
{
String s="Sachin";
System.out.println(s.toUpperCase());
System.out.println(s.toLowerCase());
System.out.println(s);
}
}
OUTPUT: SACHIN
sachin
Sachin
Java String trim() method
 The String class trim() method eliminates white spaces before and after the
String. EX:

public class StringTrimExample


{
public static void main(String args[])
{
String s1=" hello string ";
System.out.println(s1);
System.out.println(s1.trim());
}
}

OUTPUT: hello string


hello string
Java String charAt()

 The Java String class charAt() method returns a char value at the
given index number.
 EX:
public class CharAtExample
{
public static void main(String args[])
{
String name="javateam";
char ch=name.charAt(4);//returns the char value at the 4th index
System.out.println(ch);
}}

OUTPUT: t
Java String replace()
 The Java String class replace() method returns a string replacing all the old
char or CharSequence to new char or CharSequence.
 Ex:
public class ReplaceExample1
{
public static void main(String args[])
{
String s1="java is a very good language";
String replaceString=s1.replace('a','e');//replaces all occurrences of 'a' to '
System.out.println(replaceString);
}}

 OUTPUT: jeve is e very good lenguege


Java StringBuffer Class

 Java StringBuffer class is used to create mutable (modifiable) String


objects.
 Important Constructors of StringBuffer Class:
• StringBuffer() : It creates an empty String buffer with the initial
capacity of 16.
• StringBuffer(String str): It creates a String buffer with the specified
string.
• StringBuffer(int capacity): It creates an empty String buffer with the
specified capacity as length.
Java StringBuffer
 This class contains public methods which are Synchronized.
 The public method that can’t be used at the same time or
simultaneously in different threads is known as Synchronized
Methods.
 when using the StringBuffer class, we can ensure the thread safety in
our system.
Important methods of StringBuffer
class
 append(String s):It is used to append the specified string with this
string. The append() method is overloaded like append(char),
append(boolean), append(int), append(float), append(double) etc.
 insert(int offset, String s):It is used to insert the specified string with
this string at the specified position. The insert() method is overloaded
like insert(int, char), insert(int, boolean), insert(int, int), insert(int,
float), insert(int, double) etc.
 replace(int startIndex, int endIndex, String str):It is used to replace
the string from specified startIndex and endIndex.
 delete(int startIndex, int endIndex):It is used to delete the string from
specified startIndex and endIndex.
 reverse():is used to reverse the string.
 capacity():It is used to return the current capacity.
Important methods of StringBuffer
class…
 ensureCapacity(int minimumCapacity):It is used to ensure the
capacity at least equal to the given minimum.
 charAt(int index):It is used to return the character at the specified
position.
 intlength():It is used to return the length of the string i.e. total number
of characters.
 Stringsubstring(int beginIndex):It is used to return the substring from
the specified beginIndex.
 Stringsubstring(int beginIndex, int endIndex):It is used to return the
substring from the specified beginIndex and endIndex.
StringBuffer Class append() Method
Example
class StringBufferExample{
public static void main(String args[])
{
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);
}
}

OUTPUT: Hello Java


Difference between String and
StringBuffer
Java StringBuilder Class

 Java StringBuilder class is used to create mutable (modifiable) String.


The Java StringBuilder class is same as StringBuffer class except that
it is non-synchronized.
 Important Constructors of StringBuilder class

• StringBuilder(): It creates an empty String Builder with the initial


capacity of 16.
• StringBuilder(String str): It creates a String Builder with the specified
string.
• StringBuilder(int length): It creates an empty String Builder with the
specified capacity as length.
Important methods of StringBuilder
class
 public StringBuilder append(String s): It is used to append the
specified string with this string. The append() method is overloaded like
append(char), append(boolean), append(int), append(float),
append(double) etc.
 public StringBuilder insert(int offset, String s):It is used to insert the
specified string with this string at the specified position. The insert()
method is overloaded like insert(int, char), insert(int, boolean),
insert(int, int), insert(int, float), insert(int, double) etc.
 public StringBuilder replace(int startIndex, int endIndex, String
str):It is used to replace the string from specified startIndex and
endIndex.
 public StringBuilder delete(int startIndex, int endIndex):It is used
to delete the string from specified startIndex and endIndex.
Important methods of StringBuilder
class
 public StringBuilder reverse()It is used to reverse the string.public int
capacity(). It is used to return the current capacity.
 public void ensureCapacity(int minimumCapacity): It is used to
ensure the capacity at least equal to the given minimum.
 public char charAt(int index): It is used to return the character at the
specified position.
 public int length(): It is used to return the length of the string i.e. total
number of characters.
 public String substring(int beginIndex): It is used to return the
substring from the specified beginIndex.
Java StringBuilder Examples

 StringBuilder append() method Ex:

class StringBuilderExample
{
public static void main(String args[])
{
StringBuilder sb=new StringBuilder("Hello ");
sb.append("Java");//now original string is changed
System.out.println(sb);
}
}

OUTPUT: Hello Java


Difference between String,StringBuffer
and StringBuilder
Package
 A java package is a group of similar types of classes, interfaces and
sub-packages.

 Package in java can be categorized in two form:-

1. Built-in package (java, lang, awt, javax, swing, net, io, util, sql etc.)
2. user-defined package.
Advantage of Java Package
 Java package is used to categorize the classes and interfaces so that they can
be easily maintained.
 Java package provides access protection.
 Java package removes naming collision.
Example of Java Package
 The package keyword is used to create a package in java.
 The -d is a switch that tells the compiler where to put the class file i.e. it
represents destination. The . represents the current folder.

//save as Simple.java
package mypack;
public class Simple
{
public static void main(String args[])
{
System.out.println("Welcome to package");
}
}

 Compile java package :- javac -d . Simple.java


 Run Java package :- java mypack.Simple
 Output :- Welcome to package
Package
 There are three ways to access the package from outside the package.

1. import package.*;
2. import package.classname;
3. fully qualified name.
Output:Hello

Using packagename.*

 If you use package.* then all the classes and interfaces of this package will
be accessible but not subpackages.
 The import keyword is used to make the classes and interface of another
package accessible to the current package.

//save by A.java //save by B.java


package pack; package mypack;
public class A import pack.*;
{ class B
public void msg() {
{ public static void main(String args[])
System.out.println("Hello"); {
} A obj = new A();
} obj.msg();
}
}
Output - Hello
Using packagename.classname

 If you import package.classname then only declared class of this package


will be accessible.

//save by A.java //save by B.java


package pack; package mypack;
public class A import pack.A;
{ class B
public void msg() {
{ public static void main(String args[])
System.out.println("Hello"); {
} A obj = new A();
} obj.msg();
}
}

Output - Hello
Using fully qualified name
 If you use fully qualified name then only declared class of this package will
be accessible.
 Now there is no need to import.
 But you need to use fully qualified name every time when you are
accessing the class or interface.
//save by B.java
//save by A.java
package mypack;
package pack;
class B
public class A{
{
public void msg()
public static void main(String args[])
{
{
System.out.println("Hello");
pack.A obj = new pack.A();//using fully qualified name
}
obj.msg();
}
}
}

Output - Hello
Exception Handling
▪ Exception
 Exception is an abnormal condition that arises at run time.
 Event that disrupts the normal flow of the program.
 It is an object which is thrown at runtime.

▪ Exception Handling
 Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException,
RemoteException, etc.
 Maintain the normal flow of the application.
 It is an object which is thrown at runtime.
 Exception Handling done with the exception object
Types of Errors
 Syntax Errors- arise because the rules of the language have not been
followed. They are detected by the compiler.

 Runtime Errors- occur while the program is running, if the


environment detects an operation that is impossible to carry out.

 Logic Errors- occur when a program doesn't perform the way it was
intended to.
Types of Java Exceptions

 The sun microsystem says there are three types of exceptions

1. Checked Exception- are checked at compile time


2. Unchecked – are not checked at compile –time rather they are
checked at run time .
3. Error
Exception Classes
Exception Handling Terms
 try - The "try" keyword is used to specify a block where we should
place an exception code. The try block must be followed by either catch
or finally.
 Catch - The "catch" block is used to handle the exception. It must be
preceded by try block which means we can't use catch block alone. It
can be followed by finally block later.
 finally - The "finally" block is used to execute the necessary code of
the program. It is executed whether an exception is handled or not.
 throw - The "throw" keyword is used to throw an exception.
 throws - The "throws" keyword is used to declare exceptions. It
specifies that there may occur an exception in the method. It doesn't
throw an exception. It is always used with method signature.
Example (try, catch)
public class JavaExceptionExample{
public static void main(String args[])
{ try{
//code that may raise exception
int data=10/0;
}
catch(ArithmeticException e)
{System.out.println(e);}
//rest code of the program
System.out.println("rest of the code...");
}
}
Output:-Exception in thread main java.lang.ArithmeticException:/ by zero
rest of the code...
Multi-catch block

 If more than one exception can occur, then we


use multiple catch blocks.

 When an exception is thrown, each catch


statement is inspected in order, and the first one
whose type matches that of the exception is
executed.

 After one catch statement executes,the others


are bypassed
try catch finally flowchart
Example try, catch and finally
class TestFinallyBlock {
public static void main(String args[]){
try{
//below code do not throw any exception
int data=25/5;
System.out.println(data);
}
//catch won't be executed Output: 5
catch(NullPointerException e) Finally block is always executed
{
rest of the code
System.out.println(e);
}
//executed regardless of exception occurred or not
finally {
System.out.println("finally block is always executed");

}
System.out.println("rest of the code...");
}
throw keyword
 The Java throw keyword is used to throw an exception explicitly.
 Syntax
throw new exception_class("error message");
eg.:- throw new IOException("sorry device error");

 throw either checked or unchecked exceptions in Java by throw


keyword. It is mainly used to throw a user defined or custom exception.
Example1: Throwing Unchecked Exception
public class TestThrow1
{ //function to check if person is eligible to vote or not
public static void validate(int age)
{
if(age<18)
{ //throw userdefined exception if not eligible to vote
throw new InvalidageException("Person is not eligible to vote");
}
else {
System.out.println("Person is eligible to vote!!");
}
}
//main method
public static void main(String args[])
{
//calling the function
validate(13);
System.out.println("rest of the code...");
}
}
throws keyword
 Java throws keyword is used to declare an exception
 It gives an information to the programmer that there may occur an
exception.
 it is better for the programmer to provide the exception handling code
so that the normal flow of the program can be maintained.

 Syntax of Java throws


return_type method_name() throws exception_ class_name
{
//method code
}
throw vs throws
Difference between final, finally and
finalize
Thank You

You might also like