Core Java.pptx
Core Java.pptx
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.
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…)
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.
⚫ Object Oriented
⚫ Focus on the data (objects) and methods manipulating the data
⚫ All methods are associated with objects
⚫ Potentially better code organization and reuse
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)
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.
⚫ The principle of data hiding helps the programmer to build secure programs.
⚫ Object-oriented databases
⚫ 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
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 OR assignment
^= Bitwise exclusive OR
assignment
Operator Result
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
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
▪ Primitive data types: The primitive data types include boolean, char,
byte, short, int, long, float and double.
1. Local Variable
2. Instance Variable
3. Static Variable
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.
⚫ It cannot be local.
⚫ You can create a single copy of the static variable and share it among
all the instances of the class.
⚫ Memory allocation for static variables happens only once when the
class is loaded in the memory.
Example
public class A
{
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
public static void main(String args[])
{
int data=50;//instance variable
}
}//end of class
Array
⚫ An array is a collection of similar type of elements which has
contiguous memory location.
⚫ 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
⚫ 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
⚫ 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
used to create an instance method. 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
⚫ 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.
⚫ 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.
⚫ 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
Interface
⚫ An interface in Java is a blueprint of a class. It has static constants and
abstract methods.
⚫ 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 printable
{
void print();
}
class A implements printable
{
public void print()
{
System.out.println("Hello");
}
public static void main(String args[])
{
A obj = new A();
obj.print();
}
} OUTPUT : Hello
/Interface declaration: by first user
interface Drawable{
void draw();
}
//Implementation: by second user
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class Circle implements Drawable{
public void draw(){System.out.println("drawing circle");}
}
//Using interface: by third user
class TestInterface1{
public static void main(String args[]){
Drawable d=new Circle();
d.draw();
}} Output:drawing circle
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 Printable
•Printable and Showable interface have
{
same methods but its implementation is
void print(); } provided by class TestTnterface1, so there
interface Showable is no ambiguity.
{ • OUTPUT: Hello
void show(); } Welcome
class TestInterface implements Printable,Showable
{
public void print(){System.out.println("Hello");}
public void show(){System.out.println("Welcome");}
public static void main(String args[])
{
TestInterface obj = new TestInterface();
obj.print();
obj.show();
} }
Interface inheritance
⚫ A class implements an interface, but one interface extends another interface.
Ex-
interface Printable{
void print(); }
interface Showable extends Printable{
void show(); }
interface printable
{
void print();
interface MessagePrintable
{
void msg();
}
}
Java 8 Default Method in Interface
⚫ Since Java 8, we can have method body in interface. But we need to make it default or
static method. Ex-
interface Drawable{
void draw();
default void msg()
{ System.out.println("default method");
}}
class Rectangle implements Drawable
{
public void draw(){System.out.println("drawing rectangle");}
}
class TestInterfaceDefault
{
public static void main(String args[]){
Drawable d=new Rectangle();
d.draw();
d.msg();
}} OUTPUT: drawing rectangle
default method
Java 8 Static Method in Interface
interface Drawable{
void draw();
static int cube(int x)
{return x*x*x;}
}
class Rectangle implements Drawable{
public void draw(){System.out.println("drawing rectangle");}
}
class TestInterfaceStatic
{
public static void main(String args[]){
Drawable d=new Rectangle();
d.draw();
System.out.println(Drawable.cube(3)); OUTPUT:drawing rectagle
}} 27
marker or tagged interface
class Adder{
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(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}} OUTPUT:22
33
Method Overloading: Based on the
data type of the parameter
class Adder{
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(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}
OUTPUT : 22
24.9
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 for the first time."); }
public void show(int numb, char ch)
{
System.out.println ("The 'show method' is defined for the second time." ); } }
class Main
{ public static void main (String args[] )
{
DispOvrload o1 = new DispOvrload();
o1.show('G', 62);
o1.show(46, 'S');
}}
class Adder{
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(Adder.add(11,11));//ambiguity
}}
OUTPUT: Compile Time Error: method add(int,int) is already
defined in class Adder
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);}
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");}
⚫ 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.
class Vehicle
{
void run(){System.out.println("Vehicle is running");} //defining a method
}
class Bike2 extends Vehicle //Creating a child class
{
void run(){System.out.println("Bike is running safely"); //defining the same method
}
public static void main(String args[]){
Bike2 obj = new Bike2(); //creating object
obj.run(); //calling method
}
}
OUTPUT: Bike is running safely
Point to be remember
⚫ Can we override static method?
• No, a static method cannot be overridden.
⚫ Example:
String s1="Welcome";
String s2="Welcome";//It doesn't create a new instance
String Literal
⚫ 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.
⚫ In such case, JVM will create a new string object in normal (non-pool) heap
memory.
⚫ 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
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
System.out.println(s1.equals(s4));//false OUTPUT: false
true
} }
OUTPUT: true
true
false
By Using == operator
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
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
⚫ startIndex: inclusive
⚫ endIndex: exclusive
Example
public class TestSubstring{
public static void main(String args[])
{
String s="SachinTendulkar";
System.out.println("Original String: " + s);
System.out.println("Substring starting from index 6: " +s.substring(6));
System.out.println("Substring starting from index 0 to 6: "+s.substring(0,6));
}
}
OUTPUT: Tendulkr
Sachin
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:
⚫ 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);
}}
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);
}
}
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");
}
}
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.
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.
⚫ Logic Errors- occur when a program doesn't perform the way it was
intended to.
Types of Java Exceptions