Java Unit Ii
Java Unit Ii
UNIT II
INTRODUCTION TO JAVA
HISTORY OF JAVA
The history of Java is very interesting. Java was originally designed for interactive television, but it
was too advanced technology for the digital cable television industry at the time. The history of Java
starts with the Green Team. Java team members (also known as Green Team), initiated this project
to develop a language for digital devices such as set-top boxes, televisions, etc. However, it was suited
for internet programming. Later, Java technology was incorporated by Netscape.
The principles for creating Java programming were "Simple, Robust, Portable, Platform-independent,
Secured, High Performance, Multithreaded, Architecture Neutral, Object-Oriented, Interpreted, and
Dynamic". Java was developed by James Gosling, who is known as the father of Java, in 1995. James
Gosling and his team members started the project in the early '90s.
Currently, Java is used in internet programming, mobile devices, games, e-business solutions, etc.
There are given significant points that describe the history of Java.
1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June
1991. The small team of sun engineers called Green Team.
2) Initially designed for small, embedded systems in electronic appliances like set-top boxes.
3) Firstly, it was called "Greentalk" by James Gosling, and the file extension was .gt.
4) After that, it was called Oak and was developed as a part of the Green project.
5) Why Oak? Oak is a symbol of strength and chosen as a national tree of many countries like the
U.S.A., France, Germany, Romania, etc.
6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak Technologies.
7) Why had they chosen java name for Java language? The team gathered to choose a new name.
The suggested words were "dynamic", "revolutionary", "Silk", "jolt", "DNA", etc. They wanted
something that reflected the essence of the technology: revolutionary, dynamic, lively, cool, unique,
and easy to spell and fun to say.
According to James Gosling, "Java was one of the top choices along with Silk". Since Java was so
unique, most of the team members preferred Java than other names.
1
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING
8) Java is an island of Indonesia where the first coffee was produced (called java coffee). It is a kind
of espresso bean. Java name was chosen by James Gosling while having coffee near his office.
10) Initially developed by James Gosling at Sun Microsystems (which is now a subsidiary of Oracle
Corporation) and released in 1995.
11) In 1995, Time magazine called Java one of the Ten Best Products of 1995.
12) JDK 1.0 released in(January 23, 1996). After the first release of Java, there have been many
additional features added to the language. Now Java is being used in Windows applications, Web
applications, enterprise applications, mobile applications, cards, etc. Each new version adds the new
features in Java.
Many java versions have been released till now. The current stable release of Java is Java SE 10.
What is JVM?
Java Virtual Machine (JVM) is a engine that provides runtime environment to drive the Java Code
or applications. It converts Java bytecode into machines language. JVM is a part of Java Run
Environment (JRE). In other programming languages, the compiler produces machine code for a
particular system. However, Java compiler produces code for a Virtual Machine known as Java Virtual
Machine.
2
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING
First, Java code is complied into bytecode. This bytecode gets interpreted on different machines
Between host system and Java source, Bytecode is an intermediary language. JVM is responsible for
allocating memory space.
JVM Architecture
Let's understand the Architecture of JVM. It contains classloader, memory area, execution engine etc.
1) ClassLoader
The class loader is a subsystem used for loading class files. It performs three major functions viz.
Loading, Linking, and Initialization.
2) Method Area
JVM Method Area stores class structures like metadata, the constant runtime pool, and the code for
methods.
3) Heap
All the Objects, their related instance variables, and arrays are stored in the heap. This memory is
common and shared across multiple threads.
Java language Stacks store local variables, and it’s partial results. Each thread has its own JVM stack,
created simultaneously as the thread is created. A new frame is created whenever a method is invoked,
3
5) PC Registers
PC register store the address of the Java virtual machine instruction which is currently executing. In
Java, each thread has its separate PC register.
Native method stacks hold the instruction of native code depends on the native library. It is written in
another language instead of Java.
7) Execution Engine
It is a type of software used to test hardware, software, or complete systems. The test execution engine
never carries any information about the tested product.
The Native Method Interface is a programming framework. It allows Java code which is running in a
JVM to call by libraries and native applications.
Native Libraries is a collection of the Native Libraries(C, C++) which are needed by the Execution
Engine.
A compiler is a program which converts a program from one level of language to another. Example
conversion of C++ program into machine code.
The java compiler converts high-level java code into bytecode (which is also a type of machine code).
An interpreter is a program which converts a program at one level to another programming language
at the same level. Example conversion of Java program into C++
In Java, the Just In Time Code generator converts the bytecode into the native machine code which
are at the same programming levels.
C++ VS JAVA
There are many differences and similarities between the C++ programming language and Java. A list
of top differences between C++ and Java are given below:
Mainly used for C++ is mainly used for system Java is mainly used for application
programming. programming. It is widely used in
window, web-based, enterprise and
mobile applications.
Design Goal C++ was designed for systems Java was designed and created as an
and applications programming. interpreter for printing systems but
It was an extension of C later extended as a support network
programming language. computing. It was designed with a goal
of being easy to use and accessible to a
broader audience.
Compiler and C++ uses compiler only. C++ Java uses compiler and interpreter
Interpreter is compiled and run using the both. Java source code is converted
compiler which converts into bytecode at compilation time. The
source code into machine code interpreter executes this bytecode at
so, C++ is platform dependent. runtime and produces output. Java is
interpreted that is why it is platform
independent.
5
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING
Call by Value C++ supports both call by Java supports call by value only. There
and Call by value and call by reference. is no call by reference in java.
reference
Structure and C++ supports structures and Java doesn't support structures and
Union unions. unions.
Thread Support C++ doesn't have built-in Java has built-in thread support.
support for threads. It relies on
third-party libraries for thread
support.
Virtual Keyword C++ supports virtual keyword Java has no virtual keyword. We can
so that we can decide whether override all non-static methods by
or not override a function. default. In other words, non-static
methods are virtual by default.
unsigned right C++ doesn't support >>> Java supports unsigned right shift >>>
shift >>> operator. operator that fills zero at the top for the
negative numbers. For positive
numbers, it works same like >>
operator.
Inheritance Tree C++ creates a new inheritance Java uses a single inheritance tree
tree always. always because all classes are the child
of Object class in java. The object
class is the root of the inheritance tree
in java.
Note
o Java doesn't support default arguments like C++.
o Java does not support header files like C++. Java uses the import keyword to include different
6
class Simple{
public static void main(String args[]){
System.out.println("Hello Java");
}
}
Compilation Flow:
When we compile Java program using javac tool, java compiler converts the source code into byte
code.
Let's see what is the meaning of class, public, static, void, main, String[], System.out.println().
Primitive data types - includes byte, short, int, long, float, double, boolean and char
Non-primitive data types - such as String, Arrays and Classes
A primitive data type specifies the size and type of variable values, and it has no additional methods.
float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits
double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal digits
Numbers
Integer types stores whole numbers, positive or negative (such as 123 or -456), without decimals.
Valid types are byte, short, int and long. Which type you should use, depends on the numeric value.
Floating point types represents numbers with a fractional part, containing one or more decimals.
There are two types: float and double.
8
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING
Integer Types
Byte
The byte data type can store whole numbers from -128 to 127. This can be used instead of int or other
integer types to save memory when you are certain that the value will be within -128 and 127:
Example
System.out.println(myNum);
Short
The short data type can store whole numbers from -32768 to 32767:
Example
System.out.println(myNum);
Int
The int data type can store whole numbers from -2147483648 to 2147483647. In general, and in our
tutorial, the int data type is the preferred data type when we create variables with a numeric value.
Example
System.out.println(myNum);
Long
The long data type can store whole numbers from -9223372036854775808 to 9223372036854775807.
This is used when int is not large enough to store the value. Note that you should end the value with
an "L":
Example
System.out.println(myNum);
You should use a floating point type whenever you need a number with a decimal, such as 9.99 or
9
3.14515.
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING
Float
The float data type can store fractional numbers from 3.4e−038 to 3.4e+038. Note that you should end
the value with an "f":
Example
System.out.println(myNum);
Double
The double data type can store fractional numbers from 1.7e−308 to 1.7e+308. Note that you should
end the value with a "d":
Example
System.out.println(myNum);
Scientific Numbers
A floating point number can also be a scientific number with an "e" to indicate the power of 10:
Example
float f1 = 35e3f;
double d1 = 12E4d;
System.out.println(f1);
System.out.println(d1);
Booleans
A boolean data type is declared with the boolean keyword and can only take the values true or false:
Example
Boolean values are mostly used for conditional testing, which you will learn more about in a later
chapter.
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING
Characters
The char data type is used to store a single character. The character must be surrounded by single
quotes, like 'A' or 'c':
Example
System.out.println(myGrade);
Example
System.out.println(a);
System.out.println(b);
System.out.println(c);
Strings
The String data type is used to store a sequence of characters (text). String values must be surrounded
by double quotes:
Example
System.out.println(greeting);
Non-primitive data types are called reference types because they refer to objects.
The main difference between primitive and non-primitive data types are:
Primitive types are predefined (already defined) in Java. Non-primitive types are created by
the programmer and is not defined by Java (except for String).
Non-primitive types can be used to call methods to perform certain operations, while primitive
types cannot.
A primitive type has always a value, while non-primitive types can be null.
A primitive type starts with a lowercase letter, while non-primitive types starts with an
uppercase letter.
11
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING
The size of a primitive type depends on the data type, while non-primitive types have all the
same size.
JAVA COMMENTS
Comments can be used to explain Java code, and to make it more readable. It can also be used to
prevent execution when testing alternative code.
Any text between // and the end of the line is ignored by Java (will not be executed).This example uses
a single-line comment before a line of code:
Example
// This is a comment
System.out.println("Hello World");
Any text between /* and */ will be ignored by Java.This example uses a multi-line comment (a
comment block) to explain the code:
Example
System.out.println("Hello World");
JAVA VARIABLES
Variables are containers for storing data values.In Java, there are different types of variables, for
example:
String - stores text, such as "Hello". String values are surrounded by double quotes
int - stores integers (whole numbers), without decimals, such as 123 or -123
float - stores floating point numbers, with decimals, such as 19.99 or -19.99
char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes
boolean - stores values with two states: true or false
To create a variable, you must specify the type and assign it a value:
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING
Syntax
Where type is one of Java's types (such as int or String), and variable is the name of the variable (such
as x or name). The equal sign is used to assign values to the variable.
To create a variable that should store text, look at the following example:
Example
Create a variable called name of type String and assign it the value "John":
System.out.println(name);
Display Variables
Example
KEYWORDS
Keywords are predefined, reserved words used in Java programming that have special meanings to the
compiler. For example:
int score;
Here, int is a keyword. It indicates that the variable score is of integer type (32-bit signed two's
complement integer).
You cannot use keywords like int, for, class, etc as variable name (or identifiers) as they are part of
the Java programming language syntax. Here's the complete list of all keywords in Java programming.
Beside these keywords, you cannot also use true, false and null as identifiers. It is because they are
literals.
JAVA IDENTIFIERS
Identifiers are the name given to variables, classes, methods, etc. Consider the above code;
int score;
Here, score is a variable (an identifier). You cannot use keywords as variable names. It's because
keywords have predefined meanings.
Rules for Naming an Identifier
1. Identifiers cannot be a keyword.
2. Identifiers are case-sensitive.
3. It can have a sequence of letters and digits. However, it must begin with a letter, $ or _.
The first letter of an identifier cannot be a digit.
4. It's a convention to start an identifier with a letter rather and $ or _.
5. Whitespaces are not allowed.
6. Similarly, you cannot use symbols such as @, #, and so on.
1. score
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING
2. level
3. highestScore
4. number1
5. convertToString
Here are some invalid identifiers:
1. class
2. float
3. 1number
4. highest Score
5. @pple
LITERALS IN JAVA
Literal : Any constant value which can be assigned to the variable is called as literal/constant.
// Here 100 is a constant/literal.
int x = 100;
Integral literals
For Integral data types (byte, short, int, long), we can specify literals in 4 ways:-
1. Decimal literals (Base 10) : In this form the allowed digits are 0-9.
int x = 101;
2. Octal literals (Base 8) : In this form the allowed digits are 0-7.
// The octal number should be prefix with 0.
int x = 0146;
3. Hexa-decimal literals (Base 16) : In this form the allowed digits are 0-9 and characters are a-f.
We can use both uppercase and lowercase characters. As we know that java is a case-sensitive
programming language but here java is not case-sensitive.
// The hexa-decimal number should be prefix
// with 0X or 0x.
int x = 0X123Face;
15
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING
4. Binary literals : From 1.7 onward we can specify literals value even in binary form also, allowed
digits are 0 and 1. Literals value should be prefixed with 0b or 0B.
int x = 0b1111;
JAVA OPERATORS
Operators are used to perform operations on variables and values. In the example below, we use
the + operator to add together two values:
Example
Example
int sum1 = 100 + 50; // 150 (100 + 50)
int sum2 = sum1 + 250; // 400 (150 + 250)
int sum3 = sum2 + sum2; // 800 (400 + 400)
1. Arithmetic operators
2. Assignment operators
3. Comparison operators
4. Logical operators
5. Bitwise operators
Arithmetic Operators
Assignment operators are used to assign values to variables. In the example below, we use
the assignment operator (=) to assign the value 10 to a variable called x:
Example
int x = 10;
Example
int x = 10;
x += 5;
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3
|= x |= 3 x=x|3
^= x ^= 3 x=x^3
== Equal to x == y
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING
!= Not equal x != y
Logical operators are used to determine the logic between variables or values:
&& Logical and Returns true if both statements are true x < 5 && x < 10
! Logical not Reverse the result, returns false if the result !(x < 5 && x <
is true 10)
Bitwise operators are used to perform binary logic with the bits of an integer or long integer.
& AND - Sets each bit to 1 if both bits are 5&1 0101 & 0001 1
1 0001
| OR - Sets each bit to 1 if any of the two 5|1 0101 | 0001 0101 5
bits is 1
^ XOR - Sets each bit to 1 if only one of 5^1 0101 ^ 0001 0100 4
the two bits is 1
<< Zero-fill left shift - Shift left by pushing 9 << 1 1001 << 1 0010 2
zeroes in from the right and letting the
leftmost bits fall off
>> Signed right shift - Shift right by pushing 9 >> 1 1001 >> 1 1100 12
copies of the leftmost bit in from the left
and letting the rightmost bits fall off
>>> Zero-fill right shift - Shift right by 9 >>> 1 1001 >>> 1 0100 4
pushing zeroes in from the left and
18
Type casting is when you assign a value of one primitive data type to another type.In Java, there are
two types of casting:
Widening Casting
Widening casting is done automatically when passing a smaller size type to a larger size type:
Example
int myInt = 9;
System.out.println(myInt); // Outputs 9
Narrowing Casting
Narrowing casting must be done manually by placing the type in parentheses in front of the value:
Example
System.out.println(myInt); // Outputs 9
19
}
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING
JAVA ARRAYS
Arrays are used to store multiple values in a single variable, instead of declaring separate variables for
each value.
String[] cars;
We have now declared a variable that holds an array of strings. To insert values to it, we can
use an array literal - place the values in a comma-separated list, inside curly braces:
You access an array element by referring to the index number. This statement accesses the value of
the first element in cars:
Example
System.out.println(cars[0]);
// Outputs Volvo
Example
cars[0] = "Opel";
Example
cars[0] = "Opel";
System.out.println(cars[0]);
20
Array Length
To find out how many elements an array has, use the length property:
Example
System.out.println(cars.length);
// Outputs 4
You can loop through the array elements with the for loop, and use the length property to specify how
many times the loop should run.
Example
System.out.println(cars[i]);
There is also a "for-each" loop, which is used exclusively to loop through elements in arrays:
Syntax
...
The following example outputs all elements in the cars array, using a "for-each" loop:
Example
System.out.println(i);
MULTIDIMENSIONAL ARRAYS
Example
myNumbers is now an array with two arrays as its elements.To access the elements of
the myNumbers array, specify two indexes: one for the array, and one for the element inside that
array. This example accesses the third element (2) in the second array (1) of myNumbers:
Example
int x = myNumbers[1][2];
System.out.println(x); // Outputs 7
We can also use a for loop inside another for loop to get the elements of a two-dimensional array (we
still have to point to the two indexes):
Example
System.out.println(myNumbers[i][j]);
}
}
}
22
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING
JAVA METHODS
A method is a block of code which only runs when it is called.You can pass data, known as
parameters, into a method.Methods are used to perform certain actions, and they are also known
as functions..
Create a Method
A method must be declared within a class. It is defined with the name of the method, followed by
parentheses (). Java provides some pre-defined methods, such as System.out.println(), but you can also
create your own methods to perform certain actions:
Example
void myMethod() {
// code to be executed
Example Explained
Call a Method
To call a method in Java, write the method's name followed by two parentheses () and a semicolon;
In the following example, myMethod() is used to print a text (the action), when it is called:
Example
Example
void myMethod() {
myMethod();
myMethod();
myMethod();
Information can be passed to methods as parameter. Parameters act as variables inside the
method.Parameters are specified after the method name, inside the parentheses. You can add as many
parameters as you want, just separate them with a comma.
The following example has a method that takes a String called fname as parameter. When the method
is called, we pass along a first name, which is used inside the method to print the full name:
Example
myMethod("Liam");
myMethod("Jenny");
myMethod("Anja");
// Liam Refsnes
// Jenny Refsnes
// Anja Refsnes
Return Values
The void keyword, used in the examples above, indicates that the method should not return a value. If
you want the method to return a value, you can use a primitive data type (such as int, char, etc.) instead
of void, and use the return keyword inside the method:
Example
int myMethod(int x) {
return 5 + x;
System.out.println(myMethod(3));
// Outputs 8 (5 + 3)
25
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING
Create a Class
MyClass.java
In Java, an object is created from a class. We have already created the class named MyClass, so now
we can use this to create objects.
To create an object of MyClass, specify the class name, followed by the object name, and use the
keyword new:
Example
int x = 5;
System.out.println(myObj.x);
JAVA CONSTRUCTORS
A constructor in Java is a special method that is used to initialize objects. The constructor is called
when an object of a class is created. It can be used to set initial values for object attributes:
26
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING
Example
Create a constructor:
MyClass() {
MyClass myObj = new MyClass(); // Create an object of class MyClass (This will call the
constructor)
// Outputs 5
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.
In this example, we have created two methods, first add() method performs addition of two numbers
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 calling
methods.
class Adder{
int add(int a,int b){return a+b;}
int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}
CONSTRUCTOR OVERLOADING IN JAVA
Like methods, constructors can also be overloaded. In this guide we will see Constructor overloading
with the help of examples. Before we proceed further let’s understand what is constructor overloading
and why we do it.Constructor overloading is a concept of having more than one constructor with
different parameters list, in such a way so that each constructor performs a different task. For
e.g. Vector class has 4 types of constructors. If you do not want to specify the initial capacity and
capacity increment then you can simply use default constructor of Vector class like this Vector v =
new Vector(); however if you need to specify the capacity and increment then you call the
parameterized constructor of Vector class with two int arguments like this: Vector v= new Vector(10,
5);
28
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING
Here we are creating two objects of class StudentData. One is with default constructor and another
one using parameterized constructor. Both the constructors have different initialization code, similarly
you can create any number of constructors with different-2 initialization codes for different-2
purposes.
StudentData.java
class StudentData
{
private int stuID;
private String stuName;
private int stuAge;
StudentData()
{
//Default constructor
stuID = 100;
stuName = "New Student";
stuAge = 18;
}
StudentData(int num1, String str, int num2)
{
//Parameterized constructor
stuID = num1;
stuName = str;
stuAge = num2;
}
//Getter and setter methods
public int getStuID() {
return stuID;
}
public void setStuID(int stuID) {
this.stuID = stuID;
}
public String getStuName() {
return stuName;
}
public void setStuName(String stuName) {
this.stuName = stuName;
}
public int getStuAge() {
return stuAge;
}
29
o The static variable can be used to refer to the common property of all objects (which is not
unique for each object), for example, the company name of employees, college name of
students, etc.
o The static variable gets memory only once in the class area at the time of class loading.
Advantages of static variable
It makes your program memory efficient (i.e., it saves memory).
Understanding the problem without static variable
class Student{
int rollno;
String name;
String college="ITS";
}
Suppose there are 500 students in my college, now all instance data members will get memory each
time when the object is created. All students have its unique rollno and name, so instance data member
is good in such case. Here, "college" refers to the common property of all objects. If we make it static,
this field will get the memory only once.
}
}
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING
1. A static method belongs to the class rather than the object of a class.
2. A static method can be invoked without the need for creating an instance of a class.
3. A static method can access static data member and can change the value of it.
class Student{
int rollno;
String name;
static String college = "ITS";
//static method to change the value of static variable
static void change(){
college = "BBDIT";
}
//constructor to initialize the variable
Student(int r, String n){
rollno = r;
name = n;
}
//method to display values
void display(){System.out.println(rollno+" "+name+" "+college);}
}
//Test class to create and display the values of object
public class TestStaticMethod{
public static void main(String args[]){
Student.change();//calling change method
//creating objects
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
Student s3 = new Student(333,"Sonoo");
//calling display method
s1.display();
s2.display();
s3.display();
}
}
There can be a lot of usage of java this keyword. In java, this is a reference variable that refers to
the current object.
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.
33
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING
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.
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class
Output:Compile Time Error
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 a subclass provides the specific implementation of the method that has been declared
by one of its parent class, it is known as method overriding.
Let's understand the problem that we may face in the program if we don't use method overriding.
In this example, we have defined the run method in the subclass as defined in the parent class but it
has some specific implementation. The name and parameter of the method are the same, and there is
IS-A relationship between the classes, so there is method overriding.
Java inner class or nested class is a class which is declared inside the class or interface.We use inner
classes to logically group classes and interfaces in one place so that it can be more readable and
maintainable.Additionally, it can access all the members of outer class including private data members
and methods.
//code
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING
class Java_Inner_class{
//code
}
}
Advantage of java inner classes
There are basically three advantages of inner classes in java. They are as follows:
1) Nested classes represent a special type of relationship that is it can access all the members
(data members and methods) of outer class including private.
2) Nested classes are used to develop more readable and maintainable code because it
logically group classes and interfaces in one place only.
JAVA INHERITANCE
Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of
a parent object. It is an important part of OOPs (Object Oriented programming system).
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 the parent class.
Moreover, you can add new methods and fields in your current class also.
Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
The extends keyword indicates that you are making a new class that derives from an existing class.
The meaning of "extends" is to increase the functionality.
38
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING
In the terminology of Java, a class which is inherited is called a parent or superclass, and the new class
is called child or subclass.
As displayed in the above figure, Programmer is the subclass and Employee is the superclass.
The relationship between the two classes is Programmer IS-A Employee. It means that Programmer
is a type of Employee.
class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Programmer salary is:40000.0
Bonus of programmer is:10000
In the above example, Programmer object can access the field of own class as well as of Employee
class i.e. code reusability.
On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only. We will
learn about interfaces later.
39
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING
When one class inherits multiple classes, it is known as multiple inheritance. For Example:
When a class inherits another class, it is known as a single inheritance. In the example given below,
Dog class inherits the Animal class, so there is the single inheritance.
File: TestInheritance.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
40
}
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
Output:
barking...
eating...
When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the
example given below, BabyDog class inherits the Dog class which again inherits the Animal class, so
there is a multilevel inheritance.
File: TestInheritance2.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}
41
Output:
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING
weeping...
barking...
eating...
When two or more classes inherits a single class, it is known as hierarchical inheritance. In the
example given below, Dog and Cat classes inherits the Animal class, so there is hierarchical
inheritance.
File: TestInheritance3.java
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}
Output:
meowing...
eating...
To reduce the complexity and simplify the language, multiple inheritance is not supported in
42
java.Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING
A and B classes have the same method and you call it from child class object, there will be ambiguity
to call the 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.
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?
}
}
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.
A class which is declared with the abstract keyword is known as an abstract class in Java. It can have
abstract and non-abstract methods (method with the body).Before learning the Java abstract class, let's
understand the abstraction in Java first.
ABSTRACTION IN JAVA
Abstraction is a process of hiding the implementation details and showing only functionality to the
43
user.Another way, it shows only essential things to the user and hides the internal details, for example,
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING
sending SMS where you 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.
1. Abstract class
2. Interface
A class which is declared as abstract is known as an abstract class. It can have abstract and non-
abstract methods. It needs to be extended and its method implemented. It cannot be instantiated.
Points to Remember
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the body of the method.
A method which is declared as abstract and does not have implementation is known as an abstract
method.
In this example, Bike is an abstract class that contains only one abstract method run. Its implementation
is provided by the Honda class.
An interface in Java is a blueprint of a class. It has static constants and abstract methods.The interface
in Java is a mechanism to achieve abstraction. There can be only abstract methods in the Java
interface, not method body. It is used to achieve abstraction and multiple inheritance in Java.
In other words, you can say that interfaces can have abstract methods and variables. It cannot have a
method body.
There are mainly three reasons to use interface. They are given below.
An interface is declared by using the interface keyword. It provides total abstraction; means all the
methods in an interface are declared with the empty body, and all the fields are public, static and final
by default. A class that implements an interface must implement all the methods declared in the
interface.
Syntax:
interface <interface_name>{
Abstract class and interface both are used to achieve abstraction where we can declare the abstract
45
But there are many differences between abstract class and interface that are given below.
1) Abstract class can have abstract and Interface can have only abstract methods. Since
non-abstract methods. Java 8, it can have default and static
methods also.
3) Abstract class can have final, non-final, Interface has only static and final variables.
static and non-static variables.
4) Abstract class can provide the Interface can't provide the implementation of
implementation of interface. abstract class.
5) The abstract keyword is used to declare The interface keyword is used to declare
abstract class. interface.
6) An abstract class can extend another Java An interface can extend another Java interface
class and implement multiple Java interfaces. only.
7) An abstract class can be extended using An interface can be implemented using keyword
keyword "extends". "implements".
8) A Java abstract class can have class Members of a Java interface are public by default.
members like private, protected, etc.
9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
}
A package in Java is used to group related classes. Think of it as a folder in a file directory. We use
packages to avoid name conflicts, and to write a better maintainable code. Packages are divided into
two categories:
Built-in Packages
46
Page
BCA - JAVA
YUVAKSHETRA INSTITUTE OF MANAGEMENT STUDIES BCA 2017 ONWARS BATCH
PRORAMMING
The Java API is a library of prewritten classes, that are free to use, included in the Java Development
Environment.
The library is divided into packages and classes. Meaning you can either import a single class (along
with its methods and attributes), or a whole package that contain all the classes that belong to the
specified package.
To use a class or a package from the library, you need to use the import keyword:
Syntax
import package.name.Class;
Example
import java.util.Scanner;
User-defined Packages
package mypack;
*********************************
47
Page