Java Unit 1
Java Unit 1
The intention of using this language is to give relief to the developers from writing codes for
every platform. The term WORA, write once and run everywhere is often associated with this
language. It means whenever we compile a Java code, we get the byte code (.class file), and that
can be executed (without compiling it again) on different platforms provided they support Java.
In the year 1995, Java language was developed. It is mainly used to develop web, desktop, and
mobile devices. The Java language is known for its robustness, security, and simplicity features.
James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language
project in June 1991. The small team of sun engineers called Green Team.
Initially it was designed for small, embedded systems in electronic appliances like set-top
boxes.
Firstly, it was called "Greentalk" by James Gosling, and the file extension was .gt.
After that, it was called Oak and was developed as a part of the Green project.
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.
In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies.
Initially developed by James Gosling at Sun Microsystems (which is now a subsidiary of
Oracle Corporation) and released in 1995.
1
11. Java SE 9 (21st Sep 2017)
Features of Java
1. Simple : ava is very easy to learn, and its syntax is simple, clean and easy to understand.
According to Sun Microsystem, Java language is a simple programming language
because:
Java syntax is based on C++ (so easier for programmers to learn it after C++).
Java has removed many complicated and rarely-used features, for example, explicit
pointers, operator overloading, etc.
2
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
3. Portable: Java is portable because it facilitates you to carry the Java bytecode to any
platform. It doesn't require any implementation.
4. Platform independent: Java code can be executed on multiple platforms, for example,
Windows, Linux, Sun Solaris, Mac/OS, etc. Java code is compiled by the compiler and
converted into bytecode. This bytecode is a platform-independent code because it can be
run on multiple platforms, i.e., Write Once and Run Anywhere (WORA).
5. Secured: Java is best known for its security. With Java, we can develop virus-free
systems. Java is secured because:
o No explicit pointer
3
C++ vs Java
Mainly used for C++ is mainly used for system Java is mainly used for application
programming. programming. It is widely used in Windows-
based, web-based, enterprise, and mobile
applications.
Pointers C++ supports pointers. You can Restricted pointer support in java.
write a pointer program in C++.
Compiler and C++ uses compiler only. C++ is Java uses both compiler and interpreter. Java
Interpreter compiled and run using the source code is converted into bytecode at
compiler which converts source compilation time. The interpreter executes
code into machine code so, C++ this bytecode at runtime and produces output.
is platform dependent. Java is interpreted that is why it is platform-
independent.
Call by Value C++ supports both call by value Java supports call by value only. There is no
and Call by and call by reference. call by reference in java.
reference
Structure and C++ supports structures and Java doesn't support structures and unions.
Union 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.
4
JVM (Java Virtual Machine): JVM is the specification that facilitates the runtime environment
in which the execution of the Java bytecode takes place. Whenever one uses the
command java, an instance of the JVM is created. JVM facilitates the definition of the
memory area, register set, class file format, and fatal error reporting. Note that the JVM is
platform dependent.
Java Development Kit (JDK): It is the complete Java Development Kit that encompasses
everything, including JRE(Java Runtime Environment), compiler, java docs, debuggers, etc. JDK
must be installed on the computer for the creation, compilation, and execution of a Java program.
Java Runtime Environment (JRE): JRE is part of the JDK. If a system has only JRE installed,
then the user can only run the program. In other words, only the java command works. The
compilation of a Java program will not be possible (the javac command will not work).
The Java program can be written using a Text Editor (Notepad++ or NotePad or other editors
will also do the job.) or IDE (Eclipse, NetBeans, etc.).
FileName: TestClass.java
Write the above code and save the file with the name TestClass. The file should have
the .java extension.
Open the command prompt, and type javac TestClass.java. javac is the command that makes the
Java compiler come to action to compile the Java program. After the command, we must put the
name of the file that needs to be compiled. In our case, it is TestClass.java. After typing, press
the enter button. If everything goes well, a TestClass.class file will be generated that contains the
byte code. If there is some error in the program, the compiler will point it out,
and TestClass.class will not be created.
5
After the .class file is created, type java TestClass to run the program. The output of the program
will be shown on the console, which is mentioned below.
main() method: The most important method of the program where the execution begins.
Therefore, all the logic must reside in the main method. If the main() method is not containing
the logic, then it will be there in some other method, but that method must be invoked from the
main() method directly or indirectly.
class: The keyword class is used for declaring class in the Java language.
void: it means that the function or method will not be returning anything.
String argvs[]: It is a command line argument that is used for taking input.
public: It is an access specifier keyword. When it is applied to a method, then that method is
visible to all. Other access specifier keywords are, private, protected, and default.
import java.io.*: It means that all of the classes present in the package java.io is imported. The
java.io package facilitates the output and input streams for writing and reading data to files. *
means all. If one wants to import only a specific class, then replace the * with the name of the
class.
System.in: It is the input stream that is utilized for reading characters from the input-giving
device, which is usually a keyboard in our case.
static void main(): The static keyword tells that the method can be accessed without doing the
instantiation of the class.
System.out: As System.in is used for reading the characters, System.out is used to give the result
of the program on an output device such as the computer screen.
double, int: The different data types, int for the integers, double for double. Other data types are
char, boolean, float, etc.
println(): The method shows the texts on the console. The method prints the text to the screen
and then moves to the next line. For the next line, ln is used. If we do not want the cursor to
move to the next line, use the method print().
6
Introduction of Object Oriented Programming
Object-Oriented Programming or OOPs refers to languages that use objects in programming.
Object-oriented programming aims to implement real-world entities like inheritance, hiding,
polymorphism, etc in programming. The main aim of OOP is to bind together the data and the
functions that operate on them so that no other part of the code can access this data except that
function.
OOPs Concepts:
Class
Objects
Polymorphism
Inheritance
Encapsulation
Abstraction
1. Class
A class is a user-defined data type. It represents the set of properties or methods that are
common to all objects of one type. A class is like a blueprint for an object.
For Example: Consider the Class of Cars. There may be many cars with different names and
brands but all of them will share some common properties like all of them will have 4 wheels,
Speed Limit, Mileage range, etc. So here, Car is the class, and wheels, speed limits, mileage
are their properties.
2. Object:
It is a basic unit of Object-Oriented Programming and represents the real-life entities. An
Object is an instance of a Class. When a class is defined, no memory is allocated but when it
is instantiated (i.e. an object is created) memory is allocated. An object has an identity, state,
and behavior. Each object contains data and code to manipulate the data.
For example “Dog” is a real-life Object, which has some characteristics like color, Breed,
Bark, Sleep, and Eats.
3. Polymorphism:
The word polymorphism means having many forms. In simple words, we can define
polymorphism as the ability of a message to be displayed in more than one form. For
example, A person at the same time can have different characteristics. Like a man at the same
time is a father, a husband, an employee. So the same person posses different behavior in
different situations. This is called polymorphism.
7
4. Inheritance:
The capability of a class to derive properties and characteristics from another class is called
Inheritance. When we write a class, we inherit properties from other classes. So when we
create a class, we do not need to write all the properties and functions again and again, as
these can be inherited from another class that possesses it. Inheritance allows the user to reuse
the code whenever possible and reduce its redundancy.
8
5. Encapsulation:
Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism
that binds together code and the data it manipulates, so it is also known as data-hiding.
6. Data Abstraction:
Data abstraction refers to providing only essential information about the data to the
outside world, hiding the background details or implementation.
Consider a real-life example of a man driving a car. The man only knows that pressing
the accelerators will increase the speed of the car or applying brakes will stop the car,
but he does not know about how on pressing the accelerator the speed is increasing, he
does not know about the inner mechanism of the car or the implementation of the
accelerator, brakes, etc in the car.
A class can also be called a logical template to create the objects that share common properties
and methods.
For example, an Employee class may contain all the employee details in the form of variables
and methods. If the class is instantiated i.e. if an object of the class is created (say e1), we can
access all the methods or properties of the class.
Java provides a reserved keyword class to define a class. The keyword must be followed by the
class name. Inside the class, we declare methods and variables.
9
2. class keyword: The class keyword is used to create a class.
3. Class name: The name must begin with an initial letter (capitalized by convention).
4. Superclass (if any): The name of the class's parent (superclass), if any, preceded by the
keyword extends. A class can only extend (subclass) one parent.
Example 1:
Let's consider the following example to understand how to define a class in Java and implement
it with the object of class.
Calculate.java
// class definition
public class Calculate {
// instance variables
int a;
int b;
// constructor to instantiate
public Calculate (int x, int y) {
this.a = x;
this.b = y;
}
// method to add numbers
public int add () {
int res = a + b;
return res;
}
10
// method to subtract numbers
public int subtract () {
int res = a - b;
return res;
}
// method to multiply numbers
public int multiply () {
int res = a * b;
return res;
}
// method to divide numbers
public int divide () {
int res = a / b;
return res;
}
// main method
public static void main(String[] args) {
// creating object of Class
Calculate c1 = new Calculate(45, 4);
11
Constructors in Java
In Java, a constructor is a block of codes similar to the method. It is called when an instance of
the class is created. At the time of calling constructor, memory for the object is allocated in the
memory.
Every time an object is created using the new() keyword, at least one constructor is called.
2. Parameterized constructor
12
//Java Program to create and call a default constructor
class Bike1
{
//creating a default constructor
Bike1()
{
System.out.println("Bike is created");
}
//main method
public static void main(String args[])
{
//calling a default constructor
Bike1 b=new Bike1();
}
}
Output: Bike is created
In this example, we have created the constructor of Student class that have two parameters. We
can have any number of parameters in the constructor.
13
name = n;
}
//method to display the values
void display(){System.out.println(id+" "+name);}
In Java, a constructor is just like a method but without return type. It can also be overloaded like
Java methods.
Constructor overloading in Java is a technique of having more than one constructor with
different parameter lists. They are arranged in a way that each constructor performs a different
task. They are differentiated by the compiler by the number of parameters in the list and their
types.
14
//creating two arg constructor
Student5(int i,String n){
id = i;
name = n;
}
//creating three arg constructor
Student5(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}
Output
111 Karan 0
222 Aryan 25
15
Method
A method is a block of code or collection of statements or a set of code grouped together to
perform a certain task or operation
Method Signature: Every method has a method signature. It is a part of the method declaration.
It includes the method name and parameter list.
Access Specifier
1. Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default.
3. Protected: The access level of a protected modifier is within the package and outside the
package through child class. If you do not make the child class, it cannot be accessed
from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.
Return Type: Return type is a data type that the method returns
16
.
Method Name: It is a unique name that is used to define the name of a method name.
Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of
parentheses.
Method Body: It is a part of the method declaration. It contains all the actions to be performed.
It is enclosed within the pair of curly braces.
Types of Method
o Predefined Method
o User-defined Method
Predefined Method
In Java, predefined methods are the method that is already defined in the Java class libraries is
known as predefined methods. It is also known as the standard library method or built-in
method. We can directly use these methods just by calling them in the program at any point.
Some pre-defined methods are length(), equals(), compareTo(), sqrt(), etc. When we call any
of the predefined methods in our program, a series of codes related to the corresponding method
runs in the background that is already stored in the library.
User-defined Method
The method written by the user or programmer is known as a user-defined method. These
methods are modified according to the requirement.
The static keyword in Java is mainly used for memory management. The static keyword in Java
is used to share the same variable or method of a given class. The users can apply static
keywords with variables, methods, blocks, and nested classes.
Note: To create a static member (block, variable, method, nested class), precede its declaration
with the keyword static.
17
Characteristics of static keyword:
Shared memory allocation: Static variables and methods are allocated memory space only
once during the execution of the program.
Accessible without object instantiation: Static members can be accessed without the need to
create an instance of the class
Associated with class, not objects: Static members are associated with the class, not with
individual objects.
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.
class Student
{
int rollno;
String name;
static String college ="ITS";//static variable
//constructor
Student(int r, String n)
{
rollno = r;
name = n;
}
void display ()
{
System.out.println(rollno+" "+name+" "+college);
}
}
18
{
public static void main(String args[])
{
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
//we can change the college of all objects by the single line of code
//Student.college="BBDIT";
s1.display();
s2.display();
}
}
When a member is declared static, it can be accessed before any objects of its class are created,
and without reference to any object. For example, in the below java program, we are accessing
static method m1() without creating any object of the Test class.
class Test
{
// static method
static void m1()
{
System.out.println("from m1");
}
public static void main(String[] args)
{
// calling m1 without creating any object of class Test
m1();
}
}
19
Output:
From m1
final Keyword in Java
The final method in Java is used as a non-access modifier applicable only to a variable,
a method, or a class. It is used to restrict a user in Java.
Final variables: When a variable is declared as final, its value cannot be changed once it has
been initialized.
Initialization: Final variables must be initialized either at the time of declaration or in the
constructor of the class.
class Main {
AGE = 45;
20
}
OUTPUT:
ERROR!
AGE = 45;
1 error
Single-line Comments
Example:
// This is a comment
System.out.println("Hello World");
Example
System.out.println("Hello World");
21
DL – 64 Bits
Java Variables
A variable is a container which holds the value while the Java program is executed. A variable is
assigned with a data type.
How to Initialize Variables in Java?
It can be perceived with the help of 3 components that are as follows:
datatype: Type of data that can be stored in this variable.
variable_name: Name given to the variable.
value: It is the initial value stored in the variable.
Variable is a name of memory location. There are three types of variables in java: local, instance
and static.
Local Variable
A variable declared inside the body of the method is called local variable. You can use this
variable only within that method and the other methods in the class aren't even aware that the
variable exists.
Instance Variable
A variable declared inside the class but outside the body of the method, is called an instance
variable. It is not declared as static.
Static variable
22
Operators in Java
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:
o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Assignment Operator.
additive +-
equality == !=
23
Bitwise bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
logical OR ||
Ternary ternary ?:
24
Java Control Statements | Control Flow in Java
o if statements
o switch statement
2. Loop statements
o do while loop
o while loop
o for loop
o for-each loop
3. Jump statements
o break statement
o continue statement
If Statement:
1. Simple if statement
2. if-else statement
3. if-else-if ladder
4. Nested if-statement
25
1. Simple if statement:
It is the most basic statement among all control flow statements in Java. It evaluates a Boolean
expression and enables the program to enter a block of code if the expression evaluates to true.
Output:
x + y is greater than 20
2. if-else statement
The if-else statement is an extension to the if-statement, which uses another block of code, i.e.,
else block. The else block is executed if the condition of the if-block is evaluated as false.
public class Student {
public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y < 10) {
System.out.println("x + y is less than 10");
} else {
System.out.println("x + y is greater than 20");
}
}
}
26
3. if-else-if ladder:
public class Student {
public static void main(String[] args) {
String city = "Delhi";
if(city == "Meerut") {
System.out.println("city is meerut");
}else if (city == "Noida") {
System.out.println("city is noida");
}else if(city == "Agra") {
System.out.println("city is agra");
}else {
System.out.println(city);
} } }
Output:
Delhi
4. Nested if-statement
In nested if-statements, the if statement can contain a if or if-else statement inside another if or
else-if statement.
27
}
}else {
System.out.println("You are not living in India");
} } }
Switch Statement:
In Java, Switch statements are similar to if-else-if statements. The switch statement contains
multiple blocks of code called cases and a single case is executed based on the variable which is
being switched. The switch statement is easier to use instead of if-else-if statements. It also
enhances the readability of the program.
Syntax
switch (expression){
case value1:
statement1;
break;
.
.
.
case valueN:
statementN;
break;
default:
default statement;
}
Example
28
case 0:
System.out.println("number is 0");
break;
case 1:
System.out.println("number is 1");
break;
default:
System.out.println(num);
} } }
Output: 2
Loop Statements
In Java, we have three types of loops that execute similarly. However, there are differences in
their syntax and condition checking time.
1. for loop
2. while loop
3. do-while loop
for loop
for(initialization, condition, increment/decrement) {
//block of statements
}
29
public static void main(String[] args) {
// TODO Auto-generated method stub
int sum = 0;
for(int j = 1; j<=10; j++) {
sum = sum + j;
}
System.out.println("The sum of first 10 natural numbers is " + sum);
}
}
Output:
for-each loop
Java provides an enhanced for loop to traverse the data structures like array or collection. In the
for-each loop, we don't need to update the loop variable. The syntax to use the for-each loop in
java is given below.
30
Output:
Printing the content of the array names:
Java
C
C++
Python
JavaScript
while loop
1. while(condition){
2. //looping statements
3. }
Example:
0
2
4
6
8
10
31
do-while loop
public class Calculation {
public static void main(String[] args) {
// TODO Auto-generated method stub
int i = 0;
System.out.println("Printing the list of first 10 even numbers \n");
do {
System.out.println(i);
i = i + 2;
}while(i<=10);
}}
Output:
Printing the list of first 10 even numbers
0
2
4
6
8
10
As the name suggests, the break statement is used to break the current flow of the program and
transfer the control to the next statement outside a loop or switch statement. However, it breaks
only the inner loop in the case of the nested loop.
The break statement cannot be used independently in the Java program, i.e., it can only be
written inside the loop or switch statement.
32
System.out.println(i);
if(i==6) {
break;
} } } }
Output:
0
1
2
3
4
5
6
continue statement
nlike break statement, the continue statement doesn't break the loop, whereas, it skips the
specific part of the loop and jumps to the next iteration of the loop immediately.
Consider the following example to understand the functioning of the continue statement in Java.
33
5
1
2
3
5
2
3
5
object
An entity that has state and behavior is known as an object e.g., chair, bike, marker, pen, table,
car, etc. It can be physical or logical (tangible and intangible). The example of an intangible
object is the banking system.
An object has three characteristics:
o Identity: An object identity is typically implemented via a unique ID. The value of the
ID is not visible to the external user. However, it is used internally by the JVM to identify
each object uniquely.
An object is an instance of a class. A class is a template or blueprint from which objects are
created. So, an object is the instance(result) of a class.
class
A class is a group of objects which have common properties. It is a template or blueprint from
which objects are created. It is a logical entity. It can't be physical.
Fields
Methods
Constructors
Blocks
Nested class and interface
34
Method in Java
In Java, a method is like a function which is used to expose the behavior of an object.
35
Output:
0
Null
Output:
55
45
36
Inheritance in Java
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).
o Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called
a derived class, extended class, or child class.
o Super Class/Parent Class: Superclass is the class from where a subclass inherits the
features. It is also called a base class or a parent class.
37
Bonus of programmer is:10000
class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}
Output
barking...
eating...
38
Multilevel Inheritance Example
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.
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();
}}
Output
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.
class Animal{
void eat(){System.out.println("eating...");}
39
}
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
java.
onsider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If 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.
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
40
public static void main(String args[]){
C obj=new C();
obj.msg();//Now which msg() method would be invoked?
}
}
Output
Compile time error
The concept of inheritance, which enables classes to adopt features and attributes from other
classes, is fundamental to object-oriented programming. Due to Java's support for single
inheritance, a class can only descend from one superclass. However, Java offers a method for
achieving multiple inheritances through interfaces, enabling a class to implement many
interfaces. We will examine the idea of multiple inheritance in Java, how it is implemented using
interfaces, and use examples to help us understand.
Consider a case where class B extends class A and Class C and both class A and C have the same
method display().
Now java compiler cannot decide, which display method it should inherit. To prevent such
situation, multiple inheritances is not allowed in java.
Java interfaces
A Java interface is a group of abstract methods that specify the behavior that implementing
classes must follow.
interface Character {
void attack();
}
41
interface Weapon {
void use();
}
class Warrior implements Character, Weapon {
public void attack() {
System.out.println("Warrior attacks with a sword.");
}
public void use() {
System.out.println("Warrior uses a sword.");
}
}
class Mage implements Character, Weapon {
public void attack() {
System.out.println("Mage attacks with a wand.");
}
public void use() {
System.out.println("Mage uses a wand.");
}
}
public class MultipleInheritance {
public static void main(String[] args) {
Warrior warrior = new Warrior();
Mage mage = new Mage();
42
}
Output:
Explanation: The interfaces "Character" and "Weapon" in the example above specify the
behaviour that classes that implement them must have. As a result of the classes "Warrior" and
"Mage" implementing both interfaces, the necessary behaviors may be inherited and shown. The
main method shows how to instantiate these classes' objects and call their corresponding
behaviors.
If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading.
If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in Java.
1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
Example
class Vehicle{
void run(){System.out.println("Vehicle is running");}
43
}
class Bike2 extends Vehicle{
void run(){System.out.println("Bike is running safely");}
The super keyword in Java is a reference variable which is used to refer immediate parent class
object.
super.run();
}
public static void main(String args[])
{
Bike2 obj = new Bike2();
obj.run();
}
}
class Vehicle
44
{
void run()
{
System.out.println("Vehicle is running");
}
Encapsulation in Java
Encapsulation in Java is a process of wrapping code and data together into a single unit, for
example, a capsule which is mixed of several medicines.
We can create a fully encapsulated class in Java by making all the data members of the class
private. Now we can use setter and getter methods to set and get the data in it.
By providing only a setter or getter method, you can make the class read-only or write-only.
Polymorphism in Java
Polymorphism in Java is a concept by which we can perform a single action in different ways.
Polymorphism is derived from 2 Greek words: poly and morphs. The word "poly" means many
and "morphs" means forms. So polymorphism means many forms.
In this example, we are creating two classes Bike and Splendor. Splendor class extends Bike
class and overrides its run() method. We are calling the run method by the reference variable of
45
Parent class. Since it refers to the subclass object and subclass method overrides the Parent class
method, the subclass method is invoked at runtime.
class Bike{
void run(){System.out.println("running");}
}
class Splendor extends Bike{
void run(){System.out.println("running safely with 60km");}
Output:
Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality to
the user.
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).
2. Interface (100%)
46
Points to Remember
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.
Java Package
Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
47
2) Java package provides access protection.
There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but not
subpackages.
The import keyword is used to make the classes and interface of another package accessible to
the current package.
48
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
How to run java package program
To Compile: javac -d . B.java
To Run: java mypack.B
CLASSPATH:
CLASSPATH is an environment variable which is used by Application ClassLoader to locate
and load the .class files. The CLASSPATH defines the path, to find third-party and user-defined
classes that are not extensions or part of Java platform. Include all the directories which contain
.class files and JAR files when setting the CLASSPATH.
You need to load a class that is not present in the current directory or any sub-directories.
49
There are two ways to ways to set CLASSPATH: through Command Prompt or by
setting Environment Variable.
Step 1: Click on the Windows button and choose Control Panel. Select System.
Step2: System
Step5: If the CLASSPATH already exists in System Variables, click on the Edit button then put
a semicolon (;) at the end. Paste the Path of MySQL-Connector Java.jar file.
If the CLASSPATH doesn't exist in System Variables, then click on the New button and type
Variable name as CLASSPATH and Variable value as C:\Program Files\Java\jre1.8\MySQL-
Connector Java.jar;.;
The jar (Java Archive) tool of JDK provides the facility to create the executable jar file. An
executable jar file calls the main method of the class if you double click it.
To create the executable jar file, you need to create .mf file, also known as manifest file.
To create manifest file, you need to write Main-Class, then colon, then space, then classname
then enter. For example:
myfile.mf
Main-Class: First
As you can see, the mf file starts with Main-Class colon space class name. Here, class name is
First.
50
Creating executable jar file using jar tool
The jar tool provides many switches, some of them are as follows:
2. -v generates verbose output. It displays the included or extracted resource on the standard
output.
Now, let's write the code to generated the executable jar using mf file.
You need to write jar then swiches then mf_file then jar_file then .classfile as given below:
Now it will create the executable jar file. If you double click on it, it will call the main method of
the First class.
We are assuming that you have created any window based application using AWT or SWING. If
you don't, you can use the code given below:
First.java
import javax.swing.*;
public class First{
51
First(){
JFrame f=new JFrame();
f.add(b);
f.setSize(300,400);
f.setLayout(null);
f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String[] args) {
new First();
}
}
52
Java Create Jar Files
In Java, JAR stands for Java ARchive, The JAR files format is mainly used to aggregate a
collection of files into a single one. It is a single cross-platform archive format that handles
images, audio, and class files.
We can either download the JAR files from the browser or can write our own JAR files
using Eclipse IDE.
The steps to bundle the source code, i.e., .java files, into a JAR are given below. In this section,
we only understand how we can create JAR files using eclipse IDE. In the following steps, we
don't cover how we can create an executable JAR in Java.
1. In the first step, we will open Eclipse IDE and select the Export option from
the File When we select the Export option, the Jar File wizard opens with the following
screen:
53
2. From the open wizard, we select the Java JAR file and click on the Next The Next button
opens JAR Export for JAR File Specification.
3. Now, from the JAR File Specification page, we select the resources needed for exporting
in the Select the resources to export After that, we enter the JAR file name and folder.
By default, the Export generated class files and resources checkbox is checked. We
also check the Export Java source files and resources checkbox to export the source
code.
54
4. If there are other Java files or resources which we want to include and which are
available in the open project, browse to their location and ensure the file or resource is
checked in the window on the right.
5. On the same page, there are three more checkboxes, i.e., Compress the content of the
JAR file, Add directory entries, and Overwrite existing files without warning. By
default, the Compress content of the JAR file checkbox is checked.
6. Now, we have two options for proceeding next, i.e., Finish and Next. If we click on
the Next, it will immediately create a JAR file to that location which we defined in
the Select the export destination. If we click on the Next button, it will open the
Jar Packaging Option wizard for creating a JAR description, setting the advance option,
or changing the default manifest.
55
7. For now, we skip the Next and click on the Finish button.
8. Now, we go to the specified location, which we defined in the Select the export
destination, to ensure that the JAR file is created successfully or not.
The static import feature of Java 5 facilitate the java programmer to access any static member of
a class directly. There is no need to qualify it by the class name.
o Less coding is required if you have access any static member of a class oftenly.
o If you overuse the static import feature, it makes the program unreadable and
unmaintainable.
System.out.println("num="+num);
System.out.println("Square root of 25 is "+value);
}
}
56
Output:
num=1000.0
The import allows the java programmer to access classes of a package without package
qualification whereas the static import feature allows to access the static members of a class
without the class qualification.
The import provides accessibility to classes and interface whereas static import provides
accessibility to static members of the class.
57