Unit 1 Core Java - 240510 - 125907
Unit 1 Core Java - 240510 - 125907
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.
Secure
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
CAD/CAM systems
Java is a pure oop or not ?
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 OR assignment
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
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.
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.
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
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
Abstract class in Java
There can be only abstract methods in the Java interface, not method
body.
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
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
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');
}}
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");}}
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.
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");}
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
OUTPUT: false
System.out.println(s1.equals(s4));//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 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:
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
}
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");