SlideShare a Scribd company logo
1 of 137
CORE JAVA BASICS
BY
RAVIVARMA
varmarapolu@gmail.com
Java – Overview
– Java programming language was originally developed by Sun Microsystems
which was initiated by James Gosling and released in 1995 as core component
of Sun Microsystems' Java platform (Java 1.0 [J2SE]).
– The latest release of the Java Standard Edition is Java SE 8. With the
advancement of Java and its widespread popularity, multiple configurations
were built to suit various types of platforms. For example: J2EE for Enterprise
Applications, J2ME for Mobile Applications.
– The new J2 versions were renamed as Java SE, Java EE, and Java ME
respectively. Java is guaranteed to be Write Once, Run Anywhere.
Java is:
– Object Oriented: In Java, everything is an Object. Java can be easily extended
since it is based on the Object model.
– Platform Independent: Unlike many other programming languages including
C and C++, when Java is compiled, it is not compiled into platform specific
machine, rather into platform independent byte code. This byte code is
distributed over the web and interpreted by the Virtual Machine (JVM) on
whichever platform it is being run on.
– Simple: Java is designed to be easy to learn. If you understand the basic
concept of OOP Java, it would be easy to master.
– Architecture-neutral: Java compiler generates an architecture-neutral object file format, which makes the
compiled code executable on many processors, with the presence of Java runtime system.
– Portable: Being architecture-neutral and having no implementation dependent aspects of the specification makes
Java portable. Compiler in Java is written in ANSI C with a clean portability boundary, which is a POSIX subset.
– Robust: Java makes an effort to eliminate error prone situations by emphasizing mainly on compile time error
checking and runtime checking.
– Multithreaded: With Java's multithreaded feature it is possible to write programs that can perform many tasks
simultaneously. This design feature allows the developers to construct interactive applications that can run
smoothly.
– Interpreted: Java byte code is translated on the fly to native machine instructions and is not stored anywhere.
The development process is more rapid and analytical since the linking is an incremental and light-weight process.
– High Performance: With the use of Just-In-Time compilers, Java enables high performance.
– Distributed: Java is designed for the distributed environment of the internet.
– Dynamic: Java is considered to be more dynamic than C or C++ since it is
designed to adapt to an evolving environment. Java programs can carry
extensive amount of run-time information that can be used to verify and
resolve accesses to objects on run-time.
Java - Environment Setup
– Assuming you have installed Java in c:Program Filesjavajdk directory:
– Right-click on 'My Computer' and select 'Properties‘ Advanced System
Settings.
– Click the 'Environment variables' button under the 'Advanced' tab.
– Now, alter the 'Path' variable so that it also contains the path to the Java
executable.
– Example, if the path is currently set to 'C:WINDOWSSYSTEM32', then update
your path to read 'C:WINDOWSSYSTEM32;c:Program Filesjavajdkbin'.
Java – Basic Syntax
– When we consider a Java program, it can be defined as a collection of objects that
communicate via invoking each other's methods.
– Object - Objects have states and behaviors. Example: A dog has states - color, name,
breed as well as behavior such as wagging their tail, barking, eating. An object is an
instance of a class.
– Class - A class can be defined as a template/blueprint that describes the
behavior/state that the object of its type supports.
– Methods - A method is basically a behavior. A class can contain many methods. It is
in methods where the logics are written, data is manipulated and all the actions are
executed.
First Java Program
– Save the file as: MyFirstJavaProgram.java.
public class MyFirstJavaProgram {
/* This is my first java program.
* This will print 'Hello World' as the output
*/
public static void main(String []args) {
System.out.println("Hello World"); // prints Hello World
}
}
Program Execution
Compile Java Program From Command Prompt
– C:> javac MyFirstJavaProgram.java
– C:> java MyFirstJavaProgram
O/P: Hello World
Compilation and execution of a Java program is two step process. During
compilation phase Java compiler compiles the source code and generates
bytecode. This intermediate bytecode is saved in form of a .class file. In second
phase, Java virtual machine (JVM) also called Java interpreter takes the .class as
input and generates output by executing the bytecode
Difference between JDK, JRE and JVM
– JVM
– JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime
environment in which java bytecode can be executed.
– JVMs are available for many hardware and software platforms. JVM, JRE and JDK are platform
dependent because configuration of each OS differs. But, Java is platform independent.
– The JVM performs following main tasks:
– Loads code
– Verifies code
– Executes code
– Provides runtime environment
– JRE
– JRE is an acronym for Java Runtime Environment.It is used to provide runtime
environment.It is the implementation of JVM. It physically exists. It contains set
of libraries + other files that JVM uses at runtime.
– JDK
– JDK is an acronym for Java Development Kit.It physically exists.It contains JRE +
development tools.
Internal Architecture of JVM
Primitive Data types
– There are eight primitive data types supported by Java.
byte
– byte:
– This can hold whole number between -128 and 127. Mostly used to save
memory and when you are certain that the numbers would be in the limit
specified by byte data type.
Default size of this data type: 1 byte.
Default value: 0
– class JavaExample {
– public static void main(String[] args) {
–
– byte num;
– num = 113;
– System.out.println(num);
– }
– }
short
– short:
– This is greater than byte in terms of size and less than integer. Its range is -
32,768 to 32767.
Default size of this data type: 2 byte
– class JavaExample {
– public static void main(String[] args) {
–
– short num = 45678;;
– System.out.println(num);
– }
– }
int
– int: Used when short is not large enough to hold the number, it has a wider
range: -2,147,483,648 to 2,147,483,647
Default size: 4 byte
Default value: 0
Example:
– class JavaExample {
– public static void main(String[] args) {
–
– int num = 45678;;
– System.out.println(num);
– }
– }
long:
– Used when int is not large enough to hold the value, it has wider range than int
data type, ranging from -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807.
size: 8 bytes
Default value: 0
Example:
– class JavaExample {
– public static void main(String[] args) {
–
– long num = -12332252626L;
– System.out.println(num);
– }
– }
double
– double: Sufficient for holding 15 decimal digits
size: 8 bytes
Example:
– class JavaExample {
– public static void main(String[] args) {
– double num = 42937737.93;
– System.out.println(num);
– }
– }
float
– float: Sufficient for holding 6 to 7 decimal digits
size: 4 bytes
– class JavaExample {
– public static void main(String[] args) {
–
– float num = 19.98f;
– System.out.println(num);
– }
– }
boolean
– boolean: holds either true of false.
– class JavaExample {
– public static void main(String[] args) {
–
– boolean b = false;
– System.out.println(b);
– }
– }
char
– char: holds characters.
size: 2 bytes
– class JavaExample {
– public static void main(String[] args) {
–
– char ch = 'a';
– System.out.println(ch);
– }
– }
Numeric promotion
– byte->short->int->long->float->double
OOPs (Object Oriented
Programming System)
Object-oriented programming System(OOPs) is a programming paradigm
based on the concept of “objects” that contain data and methods. The primary purpose of object-
oriented programming is to increase the flexibility and maintainability of programs. Object oriented
programming brings together data and its behaviour(methods) in a single location(object) makes it
easier to understand how a program works. We will cover each and every feature of OOPs in detail
so that you won’t face any difficultly understanding OOPs Concepts.
OOPs Concepts
– What is an Object
– What is a class
– Constructor in Java
– Object Oriented Programming Features
I. Abstraction
II. Encapsulation
III. Inheritance
IV. Polymorphism
– Abstract Class and Methods
– Interfaces in Java
What is an Object
What is a class
– A class is a template or blueprint that is used to create objects.
– Class representation of objects and the sets of operations that can be applied to such objects.
– Class consists of Data members and methods.
– Primary purpose of a class is to held data/information. This is achieved with attributes which is also
known as data members.
– Example:
– A class in Java can contain:
1. fields
2. Constructors
3. static blocks
4. Methods
5. instances
Example of class
– public class MyFirstJavaExample{
– int a;
– int b;
–
– public int add() {
– //Write code here
– }
– public int sub() {
– //Write code here
– }
– ...
– ...
– }
Syntax to declare a class
class <class_name> {
field;
method;
}
Basic Syntax
– About Java programs, it is very important to keep in mind the following points.
– Case Sensitivity - Java is case sensitive, which means identifier Hello and hello would have different meaning in Java.
– Class Names - For all class names the first letter should be in Upper Case. If several words are used to form a name of the
class, each inner word's first letter should be in Upper Case.
– Example: class MyFirstJavaClass
– Method Names - All method names should start with a Lower Case letter. If several words are used to form the name of
the method, then each inner word's first letter should be in Upper Case.
– Example: public void myMethodName()
– Program File Name - Name of the program file should exactly match the class name. When saving the file, you should save
it using the class name (Remember Java is case sensitive) and append '.java' to the end of the name (if the file name and
the class name do not match, your program will not compile). Example: Assume 'MyFirstJavaProgram' is the class name.
Then the file should be saved as 'MyFirstJavaProgram.java'
Types of Variable
– There are three types of variables in java:
1. local variable
2. instance variable
3. static variable
– Local variables: Variables defined inside methods, constructors or blocks are
called local variables. The variable will be declared and initialized within the
method and the variable will be destroyed when the method has completed.
– Instance variables: Instance variables are variables within a class but outside
any method. These variables are initialized when the class is instantiated.
Instance variables can be accessed from inside any method, constructor or
blocks of that particular class.
– Class variables: Class variables are variables declared within a class, outside any
method, with the static keyword.
– class A{
– int data=50;//instance variable
– static int m=100;//static variable
– void method(){
– int n=90;//local variable
– }
– }//end of class
Java Language Keywords
– Here is a list of keywords in the Java programming language. You cannot use any
of the following as identifiers in your programs. The keywords const and goto
are reserved, even though they are not currently used. true, false, and null
might seem like keywords, but they are actually literals; you cannot use them as
identifiers in your programs.
abstract continue for new switch
assert*** default goto* package synchronized
boolean do if private this
break double implements protected throw
byte else import public throws
case enum**** instanceof return transient
catch extends int short try
char final interface static void
class finally long strictfp** volatile
const* float native super while
* not used
Constructor in Java
– Constructor in java is a special type of method that is used to initialize the
object.
– Java constructor is invoked at the time of object creation. It constructs the
values i.e. provides data for the object that is why it is known as constructor.
Rules for creating java constructor
– here are basically two rules defined for the constructor.
1. Constructor name must be same as its class name
2. Constructor must have no explicit return type
Types of java constructors
– There are two types of constructors:
1. Default constructor (no-arg constructor)
2. Parameterized constructor
– package com.corejava.examples;
– public class constructorExample {
– constructorExample(){
– System.out.println("inside 0 arg constroctor");
– }
– constructorExample(int i){
– System.out.println("inside 1 arg constroctor constroctor ::"+i);
– }
– }
– Example1(){
– this(10);
– System.out.println("in 0 argument constructor");
– }
– Example1(int a){
– System.out.println("in 1 argument constructor"+a);
– }
Difference between constructor
and method in java
Java Constructor Java Method
Constructor is used to initialize the state of
an object.
Method is used to expose behaviour of an
object.
Constructor must not have return type. Method must have return type.
Constructor is invoked implicitly. Method is invoked explicitly.
The java compiler provides a default
constructor if you don't have any
constructor.
Method is not provided by compiler in any
case.
Constructor name must be same as the class
name.
Method name may or may not be same as
class name.
Java – Static Class, Block,
Methods and Variables
– In a class we can have
1. static variables
2. static methods
3. static blocks of code.
static variables
– It is a variable which belongs to the class and not to object(instance)
– Static variables are initialized only once , at the start of the execution . These
variables will be initialized first, before the initialization of any instance
variables
– A single copy to be shared by all instances of the class
– A static variable can be accessed directly by the class name and doesn’t need
any object
– Syntax : <class-name>.<variable-name>
– public class StaticExample {
– static int num;
– static String mystr;
– static{
– num = 97;
– mystr = "Static keyword in Java";
– }
– public static void m1(){
– System.out.println("in m1 methode");
– }
Static block
– The static block, is a block of statement inside a Java class that will be executed
when a class is first loaded in to the JVM
– class Test{
– static {
– //Code goes here
– }
– }
– public class StaticExample {
– static int num;
– static String mystr;
– static{
– num = 97;
– mystr = "Static keyword in Java";
– }
– }
Multiple Static blocks
– class JavaExample2{
– static int num;
– static String mystr;
– //First Static block
– static{
– System.out.println("Static Block 1");
– num = 68;
– mystr = "Block1";
– }
– //Second static block
– static{
– System.out.println("Static Block 2");
– num = 98;
– mystr = "Block2";
– }
// System.out.println("Value of num: "+num); o/p :Static Block2,98,block2
// System.out.println("Value of mystr: "+mystr);
Different types of methods in java
1. static methods
2. Non-static methods/instance methods
Public Class StaticExp{
public static void add(){
}
}
Java Static Method
– It is a method which belongs to the class and not to the object(instance)
– A static method can access only static data. It can not access non-static data
(instance variables)
– A static method can call only other static methods and can not call a non-static
method from it.
– A static method can be accessed directly by the class name and doesn’t need
any object
– Syntax : <class-name>.<method-name>
– A static method cannot refer to "this" or "super" keywords in anyway
Instance methods
– Methods and variables that are not declared as static are known as instance
methods and instance variables. To refer to instance methods and variables, you
must instantiate the class first means you should create an object of that class
first.For static you don't need to instantiate the class u can access the methods and
variables with the class name
– Example
– Public Class Persion{
– Public void add(){
– }
– }
– Person person1 = new Person(); //instantiating
– person1.add(); //accessing non-static method.
Inheritance in Java
– Inheritance in java is a mechanism in which one object acquires all the
properties and behaviors of parent object.
– The idea behind inheritance in java is that you can create new classes that are
built upon existing classes. When you inherit from an existing class, you can
reuse methods and fields of parent class, and you can add new methods and
fields also.
– Inheritance represents the IS-A relationship, also known as parent-child
relationship
Types of Inheritance
– 1)Single
– 2)Multilevel
– 3)Hierarchical
– 4)Multiple
– 5)Hybrid
JAVA will not support
Multiple,Hybrid In inheritance
Syntax of Java Inheritance
– class Subclass-name extends Superclass-name
– {
– //methods and fields
– }
Why multiple inheritance is not
supported in java?
– To reduce the complexity and simplify the language, multiple inheritance is not
supported in java.
– Consider a scenario where A, B and C are three classes. The C class inherits A
and B classes. If A and B classes have same method and you call it from child
class object, there will be ambiguity to call method of A or B class.
– Since compile time errors are better than runtime errors, java renders compile
time error if you inherit 2 classes. So whether you have same method or
different, there will be compile time error now.
•class A{
•void msg(){System.out.println("Hello");}
•}
•class B{
•void msg(){System.out.println("Welcome");}
•}
class C extends A,B{//suppose if it were
•
• Public Static void main(String args[]){
• C obj=new C();
• obj.msg();//Now which msg() method would be invoked?
•}
•}
This keyword in java
– There can be a lot of usage of java this keyword. In java, this is a reference
variable that refers to the current object.
Usage of java this keyword
– Here is given the 6 usage of java this keyword.
– this can be used to refer current class instance variable.
– this can be used to invoke current class method (implicitly)
– this() can be used to invoke current class constructor.
– this can be passed as an argument in the method call.
– this can be passed as argument in the constructor call.
– this can be used to return the current class instance from the method.
this: to refer current class
instance variable
– The this keyword can be used to refer current class instance variable. If there is
ambiguity between the instance variables and parameters, this keyword
resolves the problem of ambiguity
Understanding the problem
without this keyword
– class Student{
– int rollno;
– String name;
– float fee;
– Student(int rollno,String name,float fee){
– rollno=rollno;
– name=name;
– fee=fee;
– }
– void display(){System.out.println(rollno+" "+name+" "+fee);}
– }
– class TestThis1{
– public static void main(String args[]){
– Student s1=new Student(111,"ankit",5000f);
– Student s2=new Student(112,"sumit",6000f);
– s1.display();
– s2.display();
– }}
Solution of the above problem
by this keyword
– class Student{
– int rollno;
– String name;
– float fee;
– Student(int rollno,String name,float fee){
– this.rollno=rollno;
– this.name=name;
– this.fee=fee;
– }
– void display(){System.out.println(rollno+" "+name+" "+fee);}
– }
this: to invoke current class
method
– You may invoke the method of the current class by using the this keyword. If
you don't use the this keyword, compiler automatically adds this keyword while
invoking the method. Let's see the example
– class A{
– void m(){System.out.println("hello m");}
– void n(){
– System.out.println("hello n");
– //m();//same as this.m()
– this.m();
– }
– }
this() : to invoke current class
constructor
– The this() constructor call can be used to invoke the current class constructor. It
is used to reuse the constructor. In other words, it is used for constructor
chaining.
– class A{
– A(){System.out.println("hello a");}
– A(int x){
– this();
– System.out.println(x);
– }
– }
– P s v main(String args[]){A a=new A(10); }
Call to this() must be the first
statement in constructor
– Student(){ //wrong example
– System.out.println(“in 0 args constructor”)
– }
– Student(int a){
– System.out.println(“in 0 args constructor”)
– this();//C.T.Error
– }
– Student(){ //correct example
– System.out.println(“in 0 args constructor”)
– }
– Student(int a){
– this(); //this should in first line
– System.out.println(“in 0 args constructor”)
–
– }
this keyword can be used to
return current class instance
– We can return this keyword as an statement from the method. In such case,
return type of the method must be the class type (non-primitive). Let's see the
example:
– return_type method_name(){
– return this;
– }
– public class Example2 {
– public Example2 xyz1(){
– System.out.println("from xyz1 methode "+this);
– return this;
– }
– }
– public class Test345 {
– public static void main(String[] args) {
– // TODO Auto-generated method stub
– Example2 example2=new Example2();
– System.out.println("------------->>>"+example2);
– example2. xyz1();
– }
super keyword in java
– The super keyword in java is a reference variable which is used to refer
immediate parent class object.
– Whenever you create the instance of subclass, an instance of parent class is
created implicitly which is referred by super reference variable.
Usage of java super Keyword
– super can be used to refer immediate parent class instance variable.
– super can be used to invoke immediate parent class method.
– super() can be used to invoke immediate parent class constructor.
super is used to refer immediate
parent class instance variable
– class A {
– String color="white";
– }
– class B extends A{
– String color="black";
– void printColor(){
– System.out.println(color);
– System.out.println(super.color);
– }
– }
super can be used to invoke parent
class method
– class A {
– void M1(){System.out.println("insuper M1..");}
– }
– class B extends A{
– void M1(){System.out.println(" in subM1..");}
– void M1(){System.out.println(" in subM2..");}
– void C(){
– super.m1();
–
– }
– }
– class TestSuper2{
– public static void main(String args[]){
– B b=new B();
– b.C();
– }}
super is used to invoke parent
class constructor
– class A {
– A(){System.out.println("in M1..");}
– }
– class B extends A{
– super();
– B() {System.out.println("in M1..");}
–
–
– }
– }
– class TestSuper2{
– public static void main(String args[]){
– B b=new B();
–
– }}
– super() is added in each class constructor automatically by compiler if there is
no super() or this().
Final Keyword In Java
– The final keyword in java is used to restrict the user. The java final keyword can
be used in many context. Final can be:
– variable
– method
– class
Java final variable example
– class A{
– final int a=90;//final variable
– void m1(){
– a=400;
– }
– public static void main(String args[]){
– A obj=new A();
– obj.m1();
– }
– }//end of class //compalation error
– If you make any variable as final, you cannot change the value of final variable(It
will be constant).
Java final method
– If you make any method as final, you cannot override it.
– class A{
– final public void m1()
– }
– class B extends A{
– public void m2()
– }
Java final class
– If you make any class as final, you cannot extend it
– final class A{
– final public void m1()
– }
– class B extends A{
– public void m2()
– } Output:Compile Time Error
Polymorphism
– Polymorphism is one of the OOPs feature that allows us to perform a single
action in different ways. For example, lets say we have a class Animal that has a
method sound(). Since this is a generic class so we can’t give it a
implementation like: Roar, Meow, Oink etc. We had to give a generic message
Method Overloading in Java
– If a class has multiple methods having same name but different in parameters,
it is known as Method Overloading.
– If we have to perform only one operation, having same name of the methods
increases the readability of the program.
– Suppose you have to perform addition of the given numbers but there can be
any number of arguments, if you write the method such as a(int,int) for two
parameters, and b(int,int,int) for three parameters then it may be difficult for
you as well as other programmers to understand the behavior of the method
because its name differs.
– So, we perform method overloading to figure out the program quickly.
Advantage of method
overloading
– Method overloading increases the readability of the program.
– Example
– void add(int a)
– void add(int a,int b)
– void add(int a,int b,int c)
Different ways to overload the
method
There are two ways to overload the method in java
– By changing number of arguments
– By changing the data type
– In java, Method Overloading is not possible by changing the return type of the
method only
Method Overloading: changing
no. of arguments
– class Add{
– 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(Add.add(11,11));
– System.out.println(Add.add(11,11,11));
– }}
Method Overloading: changing
data type of arguments
– class Add{
– static int add(int a, int b){return a+b;}
– static double add(double a, double b){return a+b;}
– }
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 Adder{
– static int add(int a,int b){return a+b;}
– static double add(int a,int b){return a+b;}
– }
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.
– In other words, If subclass provides the specific implementation of the method
that has been provided by one of its parent class, it is known as method
overriding.
Usage of Java Method
Overriding
– Method overriding is used to provide specific implementation of a method that
is already provided by its super class.
– Method overriding is used for runtime polymorphism
Rules for Java Method
Overriding
– method must have same name as in the parent class
– method must have same parameter as in the parent class.
– must be IS-A relationship (inheritance).
Example of method overriding
– class A {
– void m1(){System.out.println(“from class A m1 method");}
– }
– class B extends A{
– void m1 (){System.out.println(" from class B m1 method ");}
Encapsulation
– Encapsulation simply means binding object state(fields) and
behaviour(methods) together. If you are creating class, you are doing
encapsulation
What is encapsulation?
– The whole idea behind encapsulation is to hide the implementation details from
users. If a data member is private it means it can only be accessed within the
same class. No outside class can access private data member (variable) of other
class.
– However if we setup public getter and setter methods to update (for example
void setEmpId(int empId))and read (for example int getEmpId()) the private
data fields then the outside class can access those private data fields via public
methods.
Example of Encapsulation in
Java
– class EncapsulationDemo{
– private String empName;
– private int empAge;
– public String getEmpName(){
– return empName;
– }
– public String getEmpName(){
– return empName;
– }}
– public class EncapsTest{
– public static void main(String args[]){
– EncapsulationDemo obj = new EncapsulationDemo();
– obj.setEmpName(“xyz");
– obj.setEmpAge(10);
– System.out.println("Employee Name: " + obj.getEmpName());
– System.out.println("Employee Age: " + obj.getEmpAge());
– }
– }
Advantage of Encapsulation in
java
– By providing only setter or getter method, you can make the class read-only or
write-only
– It improves maintainability and flexibility and re-usability
– User would not be knowing what is going on behind the scene. They would only
be knowing that to update a field call set method and to read a field call get
method but what these set and get methods are doing is purely hidden from
them.
Simple example of encapsulation in
java
– package com.demo;
– public class Student{
– private String name;
–
– public String getName(){
– return name;
– }
– public void setName(String name){
– this.name=name
– }
– }
– //save as Test.java
– package com.demo;
– class Test{
– public static void main(String[] args){
– Student s=new Student();
– s.setName(“xyz");
– System.out.println(s.getName());
– }
– }
Abstraction
– Abstraction is a process of hiding the implementation details and showing only
functionality to the user.
– Another way, it shows only important things to the user and hides the internal
details for example sending sms, you just type the text and send the message.
You don't know the internal processing about the message delivery.
– Abstraction lets you focus on what the object does instead of how it does it.
– Ways to achieve Abstraction
– There are two ways to achieve abstraction in java
– Abstract class (0 to 100%)
– Interface (100%)
Interface
– Interface looks like a class but it is not a class. An interface can have methods
and variables just like the class but the methods declared in interface are by
default abstract (only method signature, no body). Also, the variables declared
in an interface are public, static & final by default
What is the use of interface in Java
– As mentioned above they are used for full abstraction. Since methods in
interfaces do not have body, they have to be implemented by the class before
you can access them. The class that implements interface must implement all
the methods of that interface. Also, java programming language does not allow
you to extend more than one class, However you can implement more than one
interfaces in your class
– Syntax:
– interface MyInterface
– {
– //All the methods are public abstract by default
–
– public void method1();
– public void method2();
– }
how a class implements an
interface
– It has to provide the body of all the methods that are declared in interface or in
other words you can say that class has to implement all the methods of
interface.
– interface MyInterface
– {
– public void method1();
– public void method2();
– }
– class Demo implements MyInterface
– {
– public void method1()
– { System.out.println("implementation of method1");
– }
– public void method2()
– {System.out.println("implementation of method2");
– }
– public static void main(String arg[])
– { MyInterface obj = new Demo();
– obj.method1(); } }
Variables declared in interface
are public, static and final by default
– interface MyInterface
– {
– int a=10;
– public void method1();
– }
– Interface variables must be initialized at the time of declaration otherwise
compiler will throw an error.
Advantages of interface in java:
– Without bothering about the implementation part, we can achieve the security
of implementation
– In java, multiple inheritance is not allowed, however you can use interface to
make use of it as you can implement more than one interface.
Abstract Class
– A class that is declared using “abstract” keyword is known as abstract class. It
can have abstract methods(methods without body) as well as concrete methods
(regular methods with body). A normal class(non-abstract class) cannot have
abstract methods
Abstract class declaration
– //Declaration using abstract keyword
– abstract class A{
– //This is abstract method
– abstract void myMethod();
– //This is concrete method with body
– void anotherMethod(){
– //Does something
– }
– }
– As we seen in the above example, there are cases when it is difficult or often
unnecessary to implement all the methods in parent class. In these cases, we
can declare the parent class as abstract, which makes it a special class which is
not complete on its own
– Abstract class cannot be instantiated which means you cannot create the object
of it. To use this class, you need to create another class that extends this this
class and provides the implementation of abstract methods, then you can use
the object of that child class to call non-abstract methods of parent class as well
as implemented methods(those that were abstract in parent but implemented
in child class).
– If a child does not implement all the abstract methods of abstract parent class,
then the child class must need to be declared abstract as well
Why can’t we create the object of
an abstract class?
– Because these classes are incomplete, they have abstract methods that have no
body
– so if java allows you to create object of this class then if someone calls the
abstract method using that object then What would happen?There would be no
actual implementation of the method to invoke.
Also because an object is concrete. An abstract class is like a template, so you
have to extend it and build on it before you can use it
Abstract class Example
– abstract class AbstractDemo{
– public void myMethod(){
– System.out.println("Hello");
– }
– abstract public void anotherMethod();
– }
– public class Demo extends AbstractDemo{
– public void anotherMethod() {
– System.out.print("Abstract method");
– }
– public static void main(String args[])
– {
– Demo obj = new Demo();
– obj.anotherMethod();
– }
Thank you

More Related Content

What's hot

Learn Java with Dr. Rifat Shahriyar
Learn Java with Dr. Rifat ShahriyarLearn Java with Dr. Rifat Shahriyar
Learn Java with Dr. Rifat ShahriyarAbir Mohammad
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsAnton Keks
 
Core Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsCore Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsMahika Tutorials
 
Fundamentals of JAVA
Fundamentals of JAVAFundamentals of JAVA
Fundamentals of JAVAKUNAL GADHIA
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in javakamal kotecha
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in javaNilesh Dalvi
 
Introduction to Java Programming Language
Introduction to Java Programming LanguageIntroduction to Java Programming Language
Introduction to Java Programming Languagejaimefrozr
 
Java variable types
Java variable typesJava variable types
Java variable typesSoba Arjun
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in JavaSpotle.ai
 
Introduction to java
Introduction to java Introduction to java
Introduction to java Java Lover
 
Spring boot
Spring bootSpring boot
Spring bootsdeeg
 

What's hot (20)

Core java
Core javaCore java
Core java
 
Learn Java with Dr. Rifat Shahriyar
Learn Java with Dr. Rifat ShahriyarLearn Java with Dr. Rifat Shahriyar
Learn Java with Dr. Rifat Shahriyar
 
Interface in java
Interface in javaInterface in java
Interface in java
 
Java Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and StreamsJava Course 8: I/O, Files and Streams
Java Course 8: I/O, Files and Streams
 
Core Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika TutorialsCore Java Tutorials by Mahika Tutorials
Core Java Tutorials by Mahika Tutorials
 
Java Basic Oops Concept
Java Basic Oops ConceptJava Basic Oops Concept
Java Basic Oops Concept
 
Fundamentals of JAVA
Fundamentals of JAVAFundamentals of JAVA
Fundamentals of JAVA
 
Java Programming
Java ProgrammingJava Programming
Java Programming
 
Core Java Tutorial
Core Java TutorialCore Java Tutorial
Core Java Tutorial
 
Introduction to class in java
Introduction to class in javaIntroduction to class in java
Introduction to class in java
 
9. Input Output in java
9. Input Output in java9. Input Output in java
9. Input Output in java
 
Java packages
Java packagesJava packages
Java packages
 
Introduction to Java Programming Language
Introduction to Java Programming LanguageIntroduction to Java Programming Language
Introduction to Java Programming Language
 
Introduction to java 8 stream api
Introduction to java 8 stream apiIntroduction to java 8 stream api
Introduction to java 8 stream api
 
JDK,JRE,JVM
JDK,JRE,JVMJDK,JRE,JVM
JDK,JRE,JVM
 
Java variable types
Java variable typesJava variable types
Java variable types
 
Class and Objects in Java
Class and Objects in JavaClass and Objects in Java
Class and Objects in Java
 
Introduction to java
Introduction to java Introduction to java
Introduction to java
 
Core Java
Core JavaCore Java
Core Java
 
Spring boot
Spring bootSpring boot
Spring boot
 

Similar to Core java

Similar to Core java (20)

Introduction java programming
Introduction java programmingIntroduction java programming
Introduction java programming
 
Java programming basics
Java programming basicsJava programming basics
Java programming basics
 
oop unit1.pptx
oop unit1.pptxoop unit1.pptx
oop unit1.pptx
 
CS8392 OOP
CS8392 OOPCS8392 OOP
CS8392 OOP
 
Java-1st.pptx about Java technology before oops
Java-1st.pptx about Java technology before oopsJava-1st.pptx about Java technology before oops
Java-1st.pptx about Java technology before oops
 
Java Programming concept
Java Programming concept Java Programming concept
Java Programming concept
 
Letest
LetestLetest
Letest
 
java slides
java slidesjava slides
java slides
 
UNIT 1.pptx
UNIT 1.pptxUNIT 1.pptx
UNIT 1.pptx
 
1.introduction to java
1.introduction to java1.introduction to java
1.introduction to java
 
Java lab-manual
Java lab-manualJava lab-manual
Java lab-manual
 
Mcs 024 assignment solution (2020-21)
Mcs 024 assignment solution (2020-21)Mcs 024 assignment solution (2020-21)
Mcs 024 assignment solution (2020-21)
 
java basic for begginers
java basic for begginersjava basic for begginers
java basic for begginers
 
Java notes
Java notesJava notes
Java notes
 
Java1
Java1Java1
Java1
 
Java
Java Java
Java
 
Programming in java ppt
Programming in java  pptProgramming in java  ppt
Programming in java ppt
 
Programming in java ppt
Programming in java  pptProgramming in java  ppt
Programming in java ppt
 
Introduction to Java Programming, Basic Structure, variables Data type, input...
Introduction to Java Programming, Basic Structure, variables Data type, input...Introduction to Java Programming, Basic Structure, variables Data type, input...
Introduction to Java Programming, Basic Structure, variables Data type, input...
 
Java introduction
Java introductionJava introduction
Java introduction
 

Recently uploaded

Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - Englishneillewis46
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxPooja Bhuva
 
Model Attribute _rec_name in the Odoo 17
Model Attribute _rec_name in the Odoo 17Model Attribute _rec_name in the Odoo 17
Model Attribute _rec_name in the Odoo 17Celine George
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsSandeep D Chaudhary
 
How to Manage Call for Tendor in Odoo 17
How to Manage Call for Tendor in Odoo 17How to Manage Call for Tendor in Odoo 17
How to Manage Call for Tendor in Odoo 17Celine George
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsMebane Rash
 
Play hard learn harder: The Serious Business of Play
Play hard learn harder:  The Serious Business of PlayPlay hard learn harder:  The Serious Business of Play
Play hard learn harder: The Serious Business of PlayPooky Knightsmith
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Pooja Bhuva
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxJisc
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxDr. Ravikiran H M Gowda
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxheathfieldcps1
 
21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptxJoelynRubio1
 
Tatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf artsTatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf artsNbelano25
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfFICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfPondicherry University
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxannathomasp01
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jisc
 
AIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptAIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptNishitharanjan Rout
 

Recently uploaded (20)

Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
Model Attribute _rec_name in the Odoo 17
Model Attribute _rec_name in the Odoo 17Model Attribute _rec_name in the Odoo 17
Model Attribute _rec_name in the Odoo 17
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & Systems
 
How to Manage Call for Tendor in Odoo 17
How to Manage Call for Tendor in Odoo 17How to Manage Call for Tendor in Odoo 17
How to Manage Call for Tendor in Odoo 17
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Play hard learn harder: The Serious Business of Play
Play hard learn harder:  The Serious Business of PlayPlay hard learn harder:  The Serious Business of Play
Play hard learn harder: The Serious Business of Play
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
Sensory_Experience_and_Emotional_Resonance_in_Gabriel_Okaras_The_Piano_and_Th...
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
The basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptxThe basics of sentences session 3pptx.pptx
The basics of sentences session 3pptx.pptx
 
Our Environment Class 10 Science Notes pdf
Our Environment Class 10 Science Notes pdfOur Environment Class 10 Science Notes pdf
Our Environment Class 10 Science Notes pdf
 
21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx
 
Tatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf artsTatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf arts
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfFICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 
AIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptAIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.ppt
 

Core java

  • 2. Java – Overview – Java programming language was originally developed by Sun Microsystems which was initiated by James Gosling and released in 1995 as core component of Sun Microsystems' Java platform (Java 1.0 [J2SE]). – The latest release of the Java Standard Edition is Java SE 8. With the advancement of Java and its widespread popularity, multiple configurations were built to suit various types of platforms. For example: J2EE for Enterprise Applications, J2ME for Mobile Applications. – The new J2 versions were renamed as Java SE, Java EE, and Java ME respectively. Java is guaranteed to be Write Once, Run Anywhere.
  • 3. Java is: – Object Oriented: In Java, everything is an Object. Java can be easily extended since it is based on the Object model. – Platform Independent: Unlike many other programming languages including C and C++, when Java is compiled, it is not compiled into platform specific machine, rather into platform independent byte code. This byte code is distributed over the web and interpreted by the Virtual Machine (JVM) on whichever platform it is being run on. – Simple: Java is designed to be easy to learn. If you understand the basic concept of OOP Java, it would be easy to master.
  • 4. – Architecture-neutral: Java compiler generates an architecture-neutral object file format, which makes the compiled code executable on many processors, with the presence of Java runtime system. – Portable: Being architecture-neutral and having no implementation dependent aspects of the specification makes Java portable. Compiler in Java is written in ANSI C with a clean portability boundary, which is a POSIX subset. – Robust: Java makes an effort to eliminate error prone situations by emphasizing mainly on compile time error checking and runtime checking. – Multithreaded: With Java's multithreaded feature it is possible to write programs that can perform many tasks simultaneously. This design feature allows the developers to construct interactive applications that can run smoothly. – Interpreted: Java byte code is translated on the fly to native machine instructions and is not stored anywhere. The development process is more rapid and analytical since the linking is an incremental and light-weight process. – High Performance: With the use of Just-In-Time compilers, Java enables high performance.
  • 5. – Distributed: Java is designed for the distributed environment of the internet. – Dynamic: Java is considered to be more dynamic than C or C++ since it is designed to adapt to an evolving environment. Java programs can carry extensive amount of run-time information that can be used to verify and resolve accesses to objects on run-time.
  • 6. Java - Environment Setup – Assuming you have installed Java in c:Program Filesjavajdk directory: – Right-click on 'My Computer' and select 'Properties‘ Advanced System Settings. – Click the 'Environment variables' button under the 'Advanced' tab. – Now, alter the 'Path' variable so that it also contains the path to the Java executable. – Example, if the path is currently set to 'C:WINDOWSSYSTEM32', then update your path to read 'C:WINDOWSSYSTEM32;c:Program Filesjavajdkbin'.
  • 7. Java – Basic Syntax – When we consider a Java program, it can be defined as a collection of objects that communicate via invoking each other's methods. – Object - Objects have states and behaviors. Example: A dog has states - color, name, breed as well as behavior such as wagging their tail, barking, eating. An object is an instance of a class. – Class - A class can be defined as a template/blueprint that describes the behavior/state that the object of its type supports. – Methods - A method is basically a behavior. A class can contain many methods. It is in methods where the logics are written, data is manipulated and all the actions are executed.
  • 8. First Java Program – Save the file as: MyFirstJavaProgram.java. public class MyFirstJavaProgram { /* This is my first java program. * This will print 'Hello World' as the output */ public static void main(String []args) { System.out.println("Hello World"); // prints Hello World } }
  • 9.
  • 10. Program Execution Compile Java Program From Command Prompt – C:> javac MyFirstJavaProgram.java – C:> java MyFirstJavaProgram O/P: Hello World Compilation and execution of a Java program is two step process. During compilation phase Java compiler compiles the source code and generates bytecode. This intermediate bytecode is saved in form of a .class file. In second phase, Java virtual machine (JVM) also called Java interpreter takes the .class as input and generates output by executing the bytecode
  • 11. Difference between JDK, JRE and JVM – JVM – JVM (Java Virtual Machine) is an abstract machine. It is a specification that provides runtime environment in which java bytecode can be executed. – JVMs are available for many hardware and software platforms. JVM, JRE and JDK are platform dependent because configuration of each OS differs. But, Java is platform independent. – The JVM performs following main tasks: – Loads code – Verifies code – Executes code – Provides runtime environment
  • 12. – JRE – JRE is an acronym for Java Runtime Environment.It is used to provide runtime environment.It is the implementation of JVM. It physically exists. It contains set of libraries + other files that JVM uses at runtime.
  • 13. – JDK – JDK is an acronym for Java Development Kit.It physically exists.It contains JRE + development tools.
  • 15. Primitive Data types – There are eight primitive data types supported by Java.
  • 16.
  • 17. byte – byte: – This can hold whole number between -128 and 127. Mostly used to save memory and when you are certain that the numbers would be in the limit specified by byte data type. Default size of this data type: 1 byte. Default value: 0
  • 18. – class JavaExample { – public static void main(String[] args) { – – byte num; – num = 113; – System.out.println(num); – } – }
  • 19. short – short: – This is greater than byte in terms of size and less than integer. Its range is - 32,768 to 32767. Default size of this data type: 2 byte
  • 20. – class JavaExample { – public static void main(String[] args) { – – short num = 45678;; – System.out.println(num); – } – }
  • 21. int – int: Used when short is not large enough to hold the number, it has a wider range: -2,147,483,648 to 2,147,483,647 Default size: 4 byte Default value: 0 Example:
  • 22. – class JavaExample { – public static void main(String[] args) { – – int num = 45678;; – System.out.println(num); – } – }
  • 23. long: – Used when int is not large enough to hold the value, it has wider range than int data type, ranging from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. size: 8 bytes Default value: 0 Example:
  • 24. – class JavaExample { – public static void main(String[] args) { – – long num = -12332252626L; – System.out.println(num); – } – }
  • 25. double – double: Sufficient for holding 15 decimal digits size: 8 bytes Example:
  • 26. – class JavaExample { – public static void main(String[] args) { – double num = 42937737.93; – System.out.println(num); – } – }
  • 27. float – float: Sufficient for holding 6 to 7 decimal digits size: 4 bytes
  • 28. – class JavaExample { – public static void main(String[] args) { – – float num = 19.98f; – System.out.println(num); – } – }
  • 29. boolean – boolean: holds either true of false. – class JavaExample { – public static void main(String[] args) { – – boolean b = false; – System.out.println(b); – } – }
  • 30. char – char: holds characters. size: 2 bytes – class JavaExample { – public static void main(String[] args) { – – char ch = 'a'; – System.out.println(ch); – } – }
  • 32. OOPs (Object Oriented Programming System) Object-oriented programming System(OOPs) is a programming paradigm based on the concept of “objects” that contain data and methods. The primary purpose of object- oriented programming is to increase the flexibility and maintainability of programs. Object oriented programming brings together data and its behaviour(methods) in a single location(object) makes it easier to understand how a program works. We will cover each and every feature of OOPs in detail so that you won’t face any difficultly understanding OOPs Concepts.
  • 33. OOPs Concepts – What is an Object – What is a class – Constructor in Java – Object Oriented Programming Features I. Abstraction II. Encapsulation III. Inheritance IV. Polymorphism – Abstract Class and Methods – Interfaces in Java
  • 34. What is an Object
  • 35.
  • 36. What is a class – A class is a template or blueprint that is used to create objects. – Class representation of objects and the sets of operations that can be applied to such objects. – Class consists of Data members and methods. – Primary purpose of a class is to held data/information. This is achieved with attributes which is also known as data members. – Example:
  • 37. – A class in Java can contain: 1. fields 2. Constructors 3. static blocks 4. Methods 5. instances
  • 38. Example of class – public class MyFirstJavaExample{ – int a; – int b; – – public int add() { – //Write code here – } – public int sub() { – //Write code here – } – ... – ... – }
  • 39. Syntax to declare a class class <class_name> { field; method; }
  • 40.
  • 41. Basic Syntax – About Java programs, it is very important to keep in mind the following points. – Case Sensitivity - Java is case sensitive, which means identifier Hello and hello would have different meaning in Java. – Class Names - For all class names the first letter should be in Upper Case. If several words are used to form a name of the class, each inner word's first letter should be in Upper Case. – Example: class MyFirstJavaClass – Method Names - All method names should start with a Lower Case letter. If several words are used to form the name of the method, then each inner word's first letter should be in Upper Case. – Example: public void myMethodName() – Program File Name - Name of the program file should exactly match the class name. When saving the file, you should save it using the class name (Remember Java is case sensitive) and append '.java' to the end of the name (if the file name and the class name do not match, your program will not compile). Example: Assume 'MyFirstJavaProgram' is the class name. Then the file should be saved as 'MyFirstJavaProgram.java'
  • 42. Types of Variable – There are three types of variables in java: 1. local variable 2. instance variable 3. static variable
  • 43. – Local variables: Variables defined inside methods, constructors or blocks are called local variables. The variable will be declared and initialized within the method and the variable will be destroyed when the method has completed. – Instance variables: Instance variables are variables within a class but outside any method. These variables are initialized when the class is instantiated. Instance variables can be accessed from inside any method, constructor or blocks of that particular class.
  • 44. – Class variables: Class variables are variables declared within a class, outside any method, with the static keyword. – class A{ – int data=50;//instance variable – static int m=100;//static variable – void method(){ – int n=90;//local variable – } – }//end of class
  • 45. Java Language Keywords – Here is a list of keywords in the Java programming language. You cannot use any of the following as identifiers in your programs. The keywords const and goto are reserved, even though they are not currently used. true, false, and null might seem like keywords, but they are actually literals; you cannot use them as identifiers in your programs.
  • 46. abstract continue for new switch assert*** default goto* package synchronized boolean do if private this break double implements protected throw byte else import public throws case enum**** instanceof return transient catch extends int short try char final interface static void class finally long strictfp** volatile const* float native super while * not used
  • 47. Constructor in Java – Constructor in java is a special type of method that is used to initialize the object. – Java constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the object that is why it is known as constructor.
  • 48. Rules for creating java constructor – here are basically two rules defined for the constructor. 1. Constructor name must be same as its class name 2. Constructor must have no explicit return type
  • 49. Types of java constructors – There are two types of constructors: 1. Default constructor (no-arg constructor) 2. Parameterized constructor
  • 50. – package com.corejava.examples; – public class constructorExample { – constructorExample(){ – System.out.println("inside 0 arg constroctor"); – } – constructorExample(int i){ – System.out.println("inside 1 arg constroctor constroctor ::"+i); – } – }
  • 51. – Example1(){ – this(10); – System.out.println("in 0 argument constructor"); – } – Example1(int a){ – System.out.println("in 1 argument constructor"+a); – }
  • 52. Difference between constructor and method in java Java Constructor Java Method Constructor is used to initialize the state of an object. Method is used to expose behaviour of an object. Constructor must not have return type. Method must have return type. Constructor is invoked implicitly. Method is invoked explicitly. The java compiler provides a default constructor if you don't have any constructor. Method is not provided by compiler in any case. Constructor name must be same as the class name. Method name may or may not be same as class name.
  • 53. Java – Static Class, Block, Methods and Variables – In a class we can have 1. static variables 2. static methods 3. static blocks of code.
  • 54. static variables – It is a variable which belongs to the class and not to object(instance) – Static variables are initialized only once , at the start of the execution . These variables will be initialized first, before the initialization of any instance variables – A single copy to be shared by all instances of the class – A static variable can be accessed directly by the class name and doesn’t need any object – Syntax : <class-name>.<variable-name>
  • 55. – public class StaticExample { – static int num; – static String mystr; – static{ – num = 97; – mystr = "Static keyword in Java"; – } – public static void m1(){ – System.out.println("in m1 methode"); – }
  • 56. Static block – The static block, is a block of statement inside a Java class that will be executed when a class is first loaded in to the JVM – class Test{ – static { – //Code goes here – } – }
  • 57. – public class StaticExample { – static int num; – static String mystr; – static{ – num = 97; – mystr = "Static keyword in Java"; – } – }
  • 58. Multiple Static blocks – class JavaExample2{ – static int num; – static String mystr; – //First Static block – static{ – System.out.println("Static Block 1"); – num = 68; – mystr = "Block1"; – }
  • 59. – //Second static block – static{ – System.out.println("Static Block 2"); – num = 98; – mystr = "Block2"; – } // System.out.println("Value of num: "+num); o/p :Static Block2,98,block2 // System.out.println("Value of mystr: "+mystr);
  • 60. Different types of methods in java 1. static methods 2. Non-static methods/instance methods Public Class StaticExp{ public static void add(){ } }
  • 61. Java Static Method – It is a method which belongs to the class and not to the object(instance) – A static method can access only static data. It can not access non-static data (instance variables) – A static method can call only other static methods and can not call a non-static method from it. – A static method can be accessed directly by the class name and doesn’t need any object – Syntax : <class-name>.<method-name> – A static method cannot refer to "this" or "super" keywords in anyway
  • 62. Instance methods – Methods and variables that are not declared as static are known as instance methods and instance variables. To refer to instance methods and variables, you must instantiate the class first means you should create an object of that class first.For static you don't need to instantiate the class u can access the methods and variables with the class name – Example – Public Class Persion{ – Public void add(){ – } – }
  • 63. – Person person1 = new Person(); //instantiating – person1.add(); //accessing non-static method.
  • 64. Inheritance in Java – Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object. – The idea behind inheritance in java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of parent class, and you can add new methods and fields also. – Inheritance represents the IS-A relationship, also known as parent-child relationship
  • 65. Types of Inheritance – 1)Single – 2)Multilevel – 3)Hierarchical – 4)Multiple – 5)Hybrid
  • 66.
  • 67. JAVA will not support Multiple,Hybrid In inheritance
  • 68. Syntax of Java Inheritance – class Subclass-name extends Superclass-name – { – //methods and fields – }
  • 69. Why multiple inheritance is not supported in java? – To reduce the complexity and simplify the language, multiple inheritance is not supported in java. – Consider a scenario where A, B and C are three classes. The C class inherits A and B classes. If A and B classes have same method and you call it from child class object, there will be ambiguity to call method of A or B class. – Since compile time errors are better than runtime errors, java renders compile time error if you inherit 2 classes. So whether you have same method or different, there will be compile time error now.
  • 70. •class A{ •void msg(){System.out.println("Hello");} •} •class B{ •void msg(){System.out.println("Welcome");} •}
  • 71. class C extends A,B{//suppose if it were • • Public Static void main(String args[]){ • C obj=new C(); • obj.msg();//Now which msg() method would be invoked? •} •}
  • 72. This keyword in java – There can be a lot of usage of java this keyword. In java, this is a reference variable that refers to the current object.
  • 73. Usage of java this keyword – Here is given the 6 usage of java this keyword. – this can be used to refer current class instance variable. – this can be used to invoke current class method (implicitly) – this() can be used to invoke current class constructor. – this can be passed as an argument in the method call. – this can be passed as argument in the constructor call. – this can be used to return the current class instance from the method.
  • 74. this: to refer current class instance variable – The this keyword can be used to refer current class instance variable. If there is ambiguity between the instance variables and parameters, this keyword resolves the problem of ambiguity
  • 75. Understanding the problem without this keyword – class Student{ – int rollno; – String name; – float fee; – Student(int rollno,String name,float fee){ – rollno=rollno; – name=name; – fee=fee; – }
  • 76. – void display(){System.out.println(rollno+" "+name+" "+fee);} – } – class TestThis1{ – public static void main(String args[]){ – Student s1=new Student(111,"ankit",5000f); – Student s2=new Student(112,"sumit",6000f); – s1.display(); – s2.display(); – }}
  • 77. Solution of the above problem by this keyword – class Student{ – int rollno; – String name; – float fee; – Student(int rollno,String name,float fee){ – this.rollno=rollno; – this.name=name; – this.fee=fee; – } – void display(){System.out.println(rollno+" "+name+" "+fee);} – }
  • 78. this: to invoke current class method – You may invoke the method of the current class by using the this keyword. If you don't use the this keyword, compiler automatically adds this keyword while invoking the method. Let's see the example
  • 79. – class A{ – void m(){System.out.println("hello m");} – void n(){ – System.out.println("hello n"); – //m();//same as this.m() – this.m(); – } – }
  • 80. this() : to invoke current class constructor – The this() constructor call can be used to invoke the current class constructor. It is used to reuse the constructor. In other words, it is used for constructor chaining.
  • 81. – class A{ – A(){System.out.println("hello a");} – A(int x){ – this(); – System.out.println(x); – } – } – P s v main(String args[]){A a=new A(10); }
  • 82. Call to this() must be the first statement in constructor – Student(){ //wrong example – System.out.println(“in 0 args constructor”) – } – Student(int a){ – System.out.println(“in 0 args constructor”) – this();//C.T.Error – }
  • 83. – Student(){ //correct example – System.out.println(“in 0 args constructor”) – } – Student(int a){ – this(); //this should in first line – System.out.println(“in 0 args constructor”) – – }
  • 84. this keyword can be used to return current class instance – We can return this keyword as an statement from the method. In such case, return type of the method must be the class type (non-primitive). Let's see the example: – return_type method_name(){ – return this; – }
  • 85. – public class Example2 { – public Example2 xyz1(){ – System.out.println("from xyz1 methode "+this); – return this; – } – }
  • 86. – public class Test345 { – public static void main(String[] args) { – // TODO Auto-generated method stub – Example2 example2=new Example2(); – System.out.println("------------->>>"+example2); – example2. xyz1(); – }
  • 87. super keyword in java – The super keyword in java is a reference variable which is used to refer immediate parent class object. – Whenever you create the instance of subclass, an instance of parent class is created implicitly which is referred by super reference variable.
  • 88. Usage of java super Keyword – super can be used to refer immediate parent class instance variable. – super can be used to invoke immediate parent class method. – super() can be used to invoke immediate parent class constructor.
  • 89. super is used to refer immediate parent class instance variable – class A { – String color="white"; – } – class B extends A{ – String color="black"; – void printColor(){ – System.out.println(color); – System.out.println(super.color); – } – }
  • 90. super can be used to invoke parent class method – class A { – void M1(){System.out.println("insuper M1..");} – } – class B extends A{ – void M1(){System.out.println(" in subM1..");} – void M1(){System.out.println(" in subM2..");} – void C(){ – super.m1(); – – } – }
  • 91. – class TestSuper2{ – public static void main(String args[]){ – B b=new B(); – b.C(); – }}
  • 92. super is used to invoke parent class constructor – class A { – A(){System.out.println("in M1..");} – } – class B extends A{ – super(); – B() {System.out.println("in M1..");} – – – } – }
  • 93. – class TestSuper2{ – public static void main(String args[]){ – B b=new B(); – – }} – super() is added in each class constructor automatically by compiler if there is no super() or this().
  • 94. Final Keyword In Java – The final keyword in java is used to restrict the user. The java final keyword can be used in many context. Final can be: – variable – method – class
  • 95. Java final variable example – class A{ – final int a=90;//final variable – void m1(){ – a=400; – } – public static void main(String args[]){ – A obj=new A(); – obj.m1(); – } – }//end of class //compalation error
  • 96. – If you make any variable as final, you cannot change the value of final variable(It will be constant).
  • 97. Java final method – If you make any method as final, you cannot override it. – class A{ – final public void m1() – } – class B extends A{ – public void m2() – }
  • 98. Java final class – If you make any class as final, you cannot extend it – final class A{ – final public void m1() – } – class B extends A{ – public void m2() – } Output:Compile Time Error
  • 99. Polymorphism – Polymorphism is one of the OOPs feature that allows us to perform a single action in different ways. For example, lets say we have a class Animal that has a method sound(). Since this is a generic class so we can’t give it a implementation like: Roar, Meow, Oink etc. We had to give a generic message
  • 100. Method Overloading in Java – If a class has multiple methods having same name but different in parameters, it is known as Method Overloading.
  • 101. – If we have to perform only one operation, having same name of the methods increases the readability of the program. – Suppose you have to perform addition of the given numbers but there can be any number of arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for three parameters then it may be difficult for you as well as other programmers to understand the behavior of the method because its name differs. – So, we perform method overloading to figure out the program quickly.
  • 102. Advantage of method overloading – Method overloading increases the readability of the program. – Example – void add(int a) – void add(int a,int b) – void add(int a,int b,int c)
  • 103. Different ways to overload the method There are two ways to overload the method in java – By changing number of arguments – By changing the data type – In java, Method Overloading is not possible by changing the return type of the method only
  • 104. Method Overloading: changing no. of arguments – class Add{ – 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(Add.add(11,11)); – System.out.println(Add.add(11,11,11)); – }}
  • 105. Method Overloading: changing data type of arguments – class Add{ – static int add(int a, int b){return a+b;} – static double add(double a, double b){return a+b;} – }
  • 106. 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
  • 107. – class Adder{ – static int add(int a,int b){return a+b;} – static double add(int a,int b){return a+b;} – }
  • 108. 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. – In other words, If subclass provides the specific implementation of the method that has been provided by one of its parent class, it is known as method overriding.
  • 109. Usage of Java Method Overriding – Method overriding is used to provide specific implementation of a method that is already provided by its super class. – Method overriding is used for runtime polymorphism
  • 110. Rules for Java Method Overriding – method must have same name as in the parent class – method must have same parameter as in the parent class. – must be IS-A relationship (inheritance).
  • 111. Example of method overriding – class A { – void m1(){System.out.println(“from class A m1 method");} – } – class B extends A{ – void m1 (){System.out.println(" from class B m1 method ");}
  • 112. Encapsulation – Encapsulation simply means binding object state(fields) and behaviour(methods) together. If you are creating class, you are doing encapsulation
  • 113. What is encapsulation? – The whole idea behind encapsulation is to hide the implementation details from users. If a data member is private it means it can only be accessed within the same class. No outside class can access private data member (variable) of other class. – However if we setup public getter and setter methods to update (for example void setEmpId(int empId))and read (for example int getEmpId()) the private data fields then the outside class can access those private data fields via public methods.
  • 114. Example of Encapsulation in Java – class EncapsulationDemo{ – private String empName; – private int empAge; – public String getEmpName(){ – return empName; – } – public String getEmpName(){ – return empName; – }}
  • 115. – public class EncapsTest{ – public static void main(String args[]){ – EncapsulationDemo obj = new EncapsulationDemo(); – obj.setEmpName(“xyz"); – obj.setEmpAge(10); – System.out.println("Employee Name: " + obj.getEmpName()); – System.out.println("Employee Age: " + obj.getEmpAge()); – } – }
  • 116. Advantage of Encapsulation in java – By providing only setter or getter method, you can make the class read-only or write-only – It improves maintainability and flexibility and re-usability – User would not be knowing what is going on behind the scene. They would only be knowing that to update a field call set method and to read a field call get method but what these set and get methods are doing is purely hidden from them.
  • 117. Simple example of encapsulation in java – package com.demo; – public class Student{ – private String name; – – public String getName(){ – return name; – } – public void setName(String name){ – this.name=name – } – }
  • 118. – //save as Test.java – package com.demo; – class Test{ – public static void main(String[] args){ – Student s=new Student(); – s.setName(“xyz"); – System.out.println(s.getName()); – } – }
  • 119.
  • 120. Abstraction – Abstraction is a process of hiding the implementation details and showing only functionality to the user. – Another way, it shows only important things to the user and hides the internal details for example sending sms, you just type the text and send the message. You don't know the internal processing about the message delivery. – Abstraction lets you focus on what the object does instead of how it does it.
  • 121. – Ways to achieve Abstraction – There are two ways to achieve abstraction in java – Abstract class (0 to 100%) – Interface (100%)
  • 122. Interface – Interface looks like a class but it is not a class. An interface can have methods and variables just like the class but the methods declared in interface are by default abstract (only method signature, no body). Also, the variables declared in an interface are public, static & final by default
  • 123. What is the use of interface in Java – As mentioned above they are used for full abstraction. Since methods in interfaces do not have body, they have to be implemented by the class before you can access them. The class that implements interface must implement all the methods of that interface. Also, java programming language does not allow you to extend more than one class, However you can implement more than one interfaces in your class
  • 124. – Syntax: – interface MyInterface – { – //All the methods are public abstract by default – – public void method1(); – public void method2(); – }
  • 125. how a class implements an interface – It has to provide the body of all the methods that are declared in interface or in other words you can say that class has to implement all the methods of interface.
  • 126. – interface MyInterface – { – public void method1(); – public void method2(); – }
  • 127. – class Demo implements MyInterface – { – public void method1() – { System.out.println("implementation of method1"); – } – public void method2() – {System.out.println("implementation of method2"); – } – public static void main(String arg[]) – { MyInterface obj = new Demo(); – obj.method1(); } }
  • 128. Variables declared in interface are public, static and final by default – interface MyInterface – { – int a=10; – public void method1(); – } – Interface variables must be initialized at the time of declaration otherwise compiler will throw an error.
  • 129. Advantages of interface in java: – Without bothering about the implementation part, we can achieve the security of implementation – In java, multiple inheritance is not allowed, however you can use interface to make use of it as you can implement more than one interface.
  • 130. Abstract Class – A class that is declared using “abstract” keyword is known as abstract class. It can have abstract methods(methods without body) as well as concrete methods (regular methods with body). A normal class(non-abstract class) cannot have abstract methods
  • 131. Abstract class declaration – //Declaration using abstract keyword – abstract class A{ – //This is abstract method – abstract void myMethod(); – //This is concrete method with body – void anotherMethod(){ – //Does something – } – }
  • 132. – As we seen in the above example, there are cases when it is difficult or often unnecessary to implement all the methods in parent class. In these cases, we can declare the parent class as abstract, which makes it a special class which is not complete on its own – Abstract class cannot be instantiated which means you cannot create the object of it. To use this class, you need to create another class that extends this this class and provides the implementation of abstract methods, then you can use the object of that child class to call non-abstract methods of parent class as well as implemented methods(those that were abstract in parent but implemented in child class).
  • 133. – If a child does not implement all the abstract methods of abstract parent class, then the child class must need to be declared abstract as well
  • 134. Why can’t we create the object of an abstract class? – Because these classes are incomplete, they have abstract methods that have no body – so if java allows you to create object of this class then if someone calls the abstract method using that object then What would happen?There would be no actual implementation of the method to invoke. Also because an object is concrete. An abstract class is like a template, so you have to extend it and build on it before you can use it
  • 135. Abstract class Example – abstract class AbstractDemo{ – public void myMethod(){ – System.out.println("Hello"); – } – abstract public void anotherMethod(); – } – public class Demo extends AbstractDemo{ – public void anotherMethod() { – System.out.print("Abstract method"); – }
  • 136. – public static void main(String args[]) – { – Demo obj = new Demo(); – obj.anotherMethod(); – }