Fepj - 1
Fepj - 1
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
Object
Any entity that has state and behavior is known as an object. For example: chair, pen, table,
keyboard, bike etc. It can be physical and logical.
Inheritance
When one object acquires all the properties and behaviors of parent object i.e. known
as inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
Polymorphism
When one task is performed by different ways i.e. known as polymorphism. For
example: to convince the customer differently, to draw something e.g. shape or rectangle
etc. In java, we use method overloading and method overriding to achieve polymorphism. Another
example can be to speak something e.g. cat speaks meaw, dog barks woof etc.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For example:
phone call, we don't know the internal processing. In java, we use abstract class and interface to
achieve abstraction.
Encapsulation
Binding (or wrapping) code and data together into a single unit is known as
encapsulation. For example: capsule, it is wrapped with different medicines. A java class is
the example of encapsulation. Java bean is the fully encapsulated class because all the data
members are private here.
Benefits of Inheritance
One of the key benefits of inheritance is to minimize the amount of duplicate code in an
application by sharing common code amongst several subclasses. Where equivalent code
exists in two related classes, the hierarchy can usually be refactored to move the common
code up to a mutual superclass. This also tends to result in a better organization of code and
smaller, simpler compilation units. Inheritance can also make application code more
flexible to change because classes that inherit from a common superclass can be used
interchangeably. If the return type of a method is superclass
Reusability - facility to use public methods of base class without rewriting the same.
Extensibility - extending the base class logic as per business logic of the derived class.
Data hiding - base class can decide to keep some data private so that it cannot be altered by
the derived class.
Features of Java
There is given many features of java. They are also known as java buzzwords. The Java
Featuresgiven below are simple and easy to understand.
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Dynamic
9. Interpreted
11. Multithreaded
12. Distributed
Java Comments
The java comments are statements that are not executed by the compiler and interpreter.
The comments can be used to provide information or explanation about the variable,
method, class or any statement. It can also be used to hide program code for
specific time.
Example:
public class CommentExample1 {
}
Output: 10
Output: 10
Now, there will be HTML files created for your Calculator class in the current directory.
Open the HTMLfiles and see the explanation of Calculator class provided through documentation
comment.
Data Types
Data types represent the different values to be stored in the variable. In java, there are two types of data types:
1) Primitive data types 2) Non-primitive data types
Data Type Default Value Default size
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
local variable
instance variable
static variable
2) Instance Variable
A variable which is declared inside the class but outside the method, is called instance
variable . Itis
not declared as static.
3) Static variable
A variable that is declared as static is called static variable. It cannot be local.We will have
detailed
learning of these variables in next chapters.
Example to understand the types of variables in java
class A{
int data=50;//instance variable static int m=100;//static variablevoid method(){
int n=90;//local variable
}
}//end of class
Constants in Java
A constant is a variable which cannot have its value changed after declaration. It uses the 'final'
keyword.
Syntax
modifier final dataType variableName = value; //global constant
Instance variables
Instance variables are those that are defined within a class itself and not in any method
or constructor of the class. They are known as instance variables because every instance
of the class (object) contains a copy of these variables. The scope of instance variables
is determined by the access specifier that is applied to these variables. We have already
seen about it earlier. The lifetime of these variables is the same as the lifetime of the
object to which it belongs. Object once created do not exist for ever. They are
destroyed by the garbage collector of Java when there are no more reference to that
object. We shall see about Java's automatic garbage collector later on.
Argument variables
These are the variables that are defined in the header oaf constructor or a method. The
scope of these variables is the method or constructor in which they are defined. The
lifetime is limited to the time for which the method keeps executing. Once the method
finishes execution, these variables are destroyed.
Local variables
A local variable is the one that is declared within a method or a constructor (not in the
header). The scope and lifetime are limited to the method itself. One important
distinction between these three types of variables is that access specifiers can be
applied to instance variables only and not to argument or local variables. In addition to
the local variables defined in a method, we also have variables that are defined in bocks
life an if block and an else block. The scope and is the same as that of the blockitself.
Operator in java is a symbol that is used to perform operations. For example: +, -, *, / etc.
There are many types of operators in java which are given below:
Unary Operator,
Arithmetic Operator,
shift Operator,
Relational Operator,
Bitwise Operator,
Logical Operator,
Assignment Operator.
Operators Hierarchy
Types of Expressions
While an expression frequently produces a result, it doesn't always. There are three
types ofexpressions in Java:
Those that produce a value, i.e. the result of (1 + 1)
Those that have no result but might have a "side effect" because an expression can
include a wide range of elements such as method invocations or increment operators
that modify the state (i.e. memory) of a program.
For Example, in java the numeric data types are compatible with each other but no
automatic conversion is supported from numeric type to char or boolean. Also, char and
boolean are not compatible with each other.
This is useful for incompatible data types where automatic conversion cannot be done.
Java Enum
Enum in java is a data type that contains fixed set of constants.
It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY and SATURDAY) , directions (NORTH, SOUTH, EAST and
WEST) etc. The java enum constants are static and final implicitly. It is available from
JDK 1.5.Java Enums can be thought of as classes that have fixed set of constants.
class EnumExample1{
Output:
WINTER
SPRING
SUMMER
FALL
The “if” statement in Java works exactly like in most programming languages. With the
help of “if” you can choose to execute a specific block of code when a predefined condition
is met. Thestructure of the “if” statement in Java looks like this:
if (condition) {
// execute this code
}
JAVA PROGRAMMING Page 13
The condition is Boolean. Boolean means it may be true or false. For example you may put
amathematical equation as condition. Look at this full example:
Write a main method that runs your program. You can write this method anywhere. In this
example, I'll write my main method in a class called Main that has no other methods. For
example:
public class Main3.
{
public static void main(String[] args)
{
Game.play();
}
}
Make sure your code is compiled, and that you have tested it thoroughly. if you're using
Windows, you will need to set your path to include Java, if you haven't done so already.
This is a delicate operation. Open Explorer, and look inside C:\ProgramFiles\Java, and you
should see some version of the JDK. Open this folder, and then open the bin folder. Select
the complete path from the top of the Explorer window, andpress Ctrl-C to copy it.
cd Desktop
To change to the parent directory, type:
cd ..
Every time you change to a new directory, list the contents of that directory to see where to
gonext. Continue listing and changing directories until you reach the directory that contains
your .class files. If you compiled your program using Java 1.6, but plan to run it on a Mac,
you'll need torecompile your code from the command line, by typing:
Now we'll create a single JAR file containing all of the files needed to run your program.
Arrays
Java provides a data structure, the array, which stores a fixed-size sequential collection of
elements of the same type. An array is used to store a collection of data, but it is often more
useful to think of an array as a collection of variables of the same type. Instead of declaring
individual variables, such as number0, number1, ..., and number99, you declare one array
variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to
Example:
The following code snippets are examples of this syntax:
Declaring an array variable, creating an array, and assigning the reference of the array
to thevariable can be combined in one statement, as shown below:
The array elements are accessed through the index. Array indices are 0-based; that is,
they startfrom 0 to arrayRefVar.length-1.
Example:
Following statement declares an array variable, myList, creates an array of 10
elements ofdouble type and assigns its reference to myList:
Following picture represents array myList. Here, myList holds ten double values and the
indicesare from 0 to 9.
Example:
Here is a complete example of showing how to create, initialize and process arrays:
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5
public class TestArray {
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
for (double element: myList) {
System.out.println(element);
}}}
Constructors
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 datafor the object that is why it is known as constructor.
There are basically two rules defined for the constructor.
Constructor name must be same as its class name
Parameterized constructor
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked
atthe time of object creation.
class Bike1{
Bike1(){System.out.println("Bike is created");}
public static void main(String args[]){Bike1 b=new Bike1();
}}
JAVA PROGRAMMING Page 20
Example of parameterized constructor
In this example, we have created the constructor of Student class that have two parameters.
Wecan have any number of parameters in the constructor.
class Student4{
int id;
String name;
Output:
111 Karan
222 Aryan
Constructor overloading is a technique in Java in which a class can have any number of
constructors that differ in parameter lists.The compiler differentiates these constructors by
taking into account the number of parameters in the list and their type.
Output:
111 Karan 0
222 Aryan 25
There is no copy constructor in java. But, we can copy the values of one object to another
likecopy constructor in C++.
There are many ways to copy the values of one object into another in java. They are:
oBy constructor
In this example, we are going to copy the values of one object into another using java
constructor.
class Student6{
int id;
String name;
Student6(int i,String n){id = i;
name = n;
}
Output:
111 Karan
111 Karan
Now you will learn how to create your own methods with or without return values, invoke
a method with or without parameters, and apply method abstraction in the program design.
CreatingMethod
Syntax
Here,
a, b − formal parameters
Method definition consists of a method header and a method body. The same is shown
in thefollowing syntax −
Syntax
method body − The method body defines what the method does with
the statements.
There is only call by value in java, not call by reference. If we call a method passing a
value, it is known as call by value. The changes being done in the called method, is not
affected in the calling method.
In case of call by value original value is not changed. Let's take a simple example:
class Operation{
int data=50;
Output:before change 50
after change 50
}
In Java, parameters are always passed by value. For example, following program prints i =
10, j = 20.
// Test.javaclass Test {
// swap() doesn't swap i and j
public static void swap(Integer i, Integer j) {Integer temp = new Integer(i);
JAVA PROGRAMMING Page 27
i = j;
j = temp;
}
public static void main(String[] args) { Integer i = new Integer(10);
Integer j = new Integer(20);swap(i, j);
The static keyword in java is used for memory management mainly. We can apply java
static keyword with variables, methods, blocks and nested class. The static keyword
belongs to the classthan instance of the class.
3. block
4. nested class
o The static variable can be used to refer the common property of all objects
(that is not unique foreach object) e.g. company name of employees,college name of students etc.
o The static variable gets memory only once in class area at the time of class
loading.
1. class Student{
2. int rollno;
3. String name;
4. String college="ITS";5. }
class Student8{
int rollno;
s1.display();
s2.display();
}}
If you apply static keyword with any method, it is known as static method.
o static method can access static data member and can change the value
of it.
name = n;
s3.display();
Access Control
There are two types of modifiers in java: access modifiers and non-access modifiers.
2. default
3. protected
4. public
In this example, we have created two classes A and Simple. A class contains private data
member and private method. We are accessing these private members from outside the
class, so there is compile time error.
class A{
If you don't use any modifier, it is treated as default bydefault. The default modifier is
accessible only within package.
In this example, we have created two packages pack and mypack. We are accessing the A
class from outside its package, since A class is not public, so it cannot be accessed from
outside the package.
//save by A.javapackage pack; class A{
void msg(){System.out.println("Hello");}
public static void main(String args[]){ A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error } }
In the above example, the scope of class A and its method msg() is default so it cannot be
accessed from outside the package.
The protected access modifier is accessible within package and outside the package but
through inheritance only.
The protected access modifier can be applied on the data member, method and constructor.
It can'tbe applied on the class.
In this example, we have created the two packages pack and mypack. The A class of pack
package is public, so can be accessed from outside the package. But msg method of this
package is declared as protected, so it can be accessed from outside the class only through
inheritance.
}}
Output:Hello
The public access modifier is accessible everywhere. It has the widest scope among all
othermodifiers.
JAVA PROGRAMMING Page 37
JAVA PROGRAMMING Page 38
Example of public access modifier
}}
Output:Hello
Private Y N N N
Y Y N N
Default
Y Y Y N
Protected
Y Y Y Y
Public
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);}
}
class TestThis2{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
Output:
111 ankit 5000
112 sumit 6000
Constructor is used to initialize the state of an object. Method is used to expose behaviour
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 Method is not provided by compiler
don't have any constructor. any case.
Constructor name must be same as the class name. Method name may or may
be
Constructor overloading is a technique in Java in which a class can have any number of
constructors that differ in parameter lists.The compiler differentiates these constructors by
taking into account the number of parameters in the list and their type.
Output:
If a class has multiple methods having same name but different in parameters, it is
knownas Method Overloading.
If we have to perform only one operation, having same name of the methods
increases thereadability of the program.
In this example, we have created two methods, first add() method performs addition
of twonumbers and second add method performs addition of three numbers.
In this example, we are creating static methods so that we don't need to create instance for
callingmethods.
class Adder{
class TestOverloading1{
Output:
In this example, we have created two methods that differs in data type. The first add
method receives two integer arguments and second add method receives two double
arguments.
if (n == 1)return 1;else
return(n * factorial(n-1));
}}
Output:
To do so, we were using free() function in C language and delete() in C++. But, in
java it isperformed automatically. So, java provides better memory management.
gc() method
Java String
string is basically an object that represents sequence of char values. An array of characters
workssame as java string. For example:
1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. String s=new String(ch);ssame as:
1. String s="javatpoint";
CharSequence Interface
JAVA PROGRAMMING Page 37
JAVA PROGRAMMING Page 38
The CharSequence interface is used to represent sequence of characters. It is implemented by
String, StringBuffer and StringBuilder classes. It means, we can create string in java by using
these 3 classes.
The java String is immutable i.e. it cannot be changed. Whenever we change any string, a new
instance is created. For mutable string, you can use StringBuffer and StringBuilderclasses.
There are two ways to create String object:
1. By string literal
2. By new keyword
String Literal
1. String s="welcome";
Each time you create a string literal, the JVM checks the string constant pool first. If the string
already exists in the pool, a reference to the pooled instance is returned. If string doesn't exist
in the pool, a new string instance is created and placed in the pool. For example:
1. String s1="Welcome";
2. String s2="Welcome";//will not create new instance
By new keyword
1. String s=new String("Welcome");//creates two objects and one reference variable
In such case, JVM will create a new string object in normal (non pool) heap memory and the
literal "Welcome" will be placed in the string constant pool. The variable s will refer to the
object in heap (non pool).
Java
strings
example
The final keyword in java is used to restrict the user. The java final keyword can be used in many
context. Final can be:
1. variable
2. method
3. class
The final keyword can be applied with the variables, a final variable that have no value it is called
blank final variable or uninitialized final variable. It can be initialized in the constructor only. The
blank final variable can be static also which will be initialized in the static block only. We will
have detailed learning of these. Let's first learn the basics of final keyword.
If you make any variable as final, you cannot change the value of final variable(It will be
constant).
There is a final variable speedlimit, we are going to change the value of this variable, but It can't
be changed because final variable once assigned a value can never be changed.
If you want to prevent the members of superclass from being overridden in the subclasses
then declare them as final using the keyword final as a modifier.
Variable of a class can be declared as final indicating that the value of that particular
variable cannot be changed.
Ex: final int a =10;
Local variable cannot be declared as final variable.
Methods can be declared final indicating that they can be overridden in subclasses. It ensures
that the functionality defined in this method will never be altered in anyway.
Ex: final void display ()
{
Body of the display method
}
Garbage collection
Garbage collection in Java is the process by which Java programs perform automatic
memory management. Java programs compile to bytecode that can be run on a Java Virtual
Machine, or JVM for short. When Java programs run on the JVM, objects are created on the
heap, which is a portion of memory dedicated to the program. Eventually, some objects will no
longer be needed. The garbage collector finds these unused objects and deletes them to free up
memory.
In C/C++, a programmer is responsible for both the creation and destruction of objects.
Usually, programmer neglects the destruction of useless objects. Due to this negligence, at a
certain point, sufficient memory may not be available to create new objects, and the entire
program will terminate abnormally, causing OutOfMemoryErrors.
But in Java, the programmer need not care for all those objects which are no longer in use.
Garbage collector destroys these objects. The main objective of Garbage Collector is to free
heap memory by destroying unreachable objects. The garbage collector is the best example of
the Daemon thread as it is always running in the background.