Java UNIT-1
Java UNIT-1
In the structured programming C, the user can create his own user-defined
functions. The main function calls the other functions. It indicates the execution
of the program. When there is a function call, the control is passed to that
function. After completing the function, the control passes back to the main
program. Moreover, a variable inside a function is a local variable, and global
variables are accessible by all the functions.
Main Focus
Modification
Moreover, it is difficult to modify the structured programs while it is easier to
modify the Object Oriented programs.
Communication
In structured programming, the main method communicates with the functions
by calling those functions in the main program whereas, in object oriented
programming, the objects communicate with each other by passing messages.
Hence, this is an important difference between structured and object oriented
programming.
Access Specifiers
There are no access specifiers in structured programming while there are access
specifiers such as private, public and protected in Object Oriented Programming.
Thus, this is also an important difference between structured and object oriented
programming.
Security
Besides, data is not secure in structured programming, but it is secure in object
oriented programming.
Code Reusability
Also, it is difficult to reuse code in structured programming, whereas it is easier to
reuse code in object oriented programming.
A list of the most important features of the Java language is given below.
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10.Multithreaded
Simple
Java 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:
o Java syntax is based on C++ (so easier for programmers to learn it after C+
+).
o Java has removed many complicated and rarely-used features, for example,
explicit pointers, operator overloading, etc.
o There is no need to remove unreferenced objects because there is an
Automatic Garbage Collection in Java.
Object-oriented
1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
Prepard by K.Swathi Lakshmi Durga
Assistant Professor
Department of IT
Platform Independent
The Java platform differs from most other platforms in the sense that it is a
software-based platform that runs on top of other hardware-based platforms. It
has two components:
1. Runtime Environment
2. API(Application Programming Interface)
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).
Secured
o No explicit pointer
o Java Programs run inside a virtual machine sandbox
Java language provides these securities by default. Some security can also be
provided by an application developer explicitly through SSL, JAAS, Cryptography,
etc.
Robust
Architecture-neutral
Portable
Java is portable because it facilitates you to carry the Java bytecode to any
platform. It doesn't require any implementation.
High-performance
Distributed
Dynamic
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
Any entity that has state and behavior is known as an object. For example, a chair,
pen, table, keyboard, bike, etc. It can be physical or logical.
Example: A dog is an object because it has states like color, name, breed, etc. as
well as behaviors like wagging the tail, barking, eating, etc.
Class
A class can also be defined as a blueprint from which you can create an individual
object. Class doesn't consume any space.
Inheritance
Polymorphism
Another example can be to speak something; for example, a cat speaks meow,
dog barks woof, etc.
Abstraction
Binding (or wrapping) code and data together into a single unit are known as
encapsulation. For example, a 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.
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.
o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface
1. class <class_name>{
2. field;
3. method;
4. }
Using the new keyword is the most popular way to create an object or instance of
the class. When we create an instance of the class by using the new keyword, it
allocates memory (heap) for the newly created object and also returns
the reference of that object to that memory. The new keyword is also used to
create an array. The syntax for creating an object is:
1. By reference variable
2. By method
3. By constructor
1. class Student{
2. int id;
3. String name;
4. }
5. class TestStudent2{
6. public static void main(String args[]){
7. Student s1=new Student();
8. s1.id=101;
9. s1.name="Sonoo";
10. System.out.println(s1.id+" "+s1.name);//printing members with a white space
11. }
12.}
Test it Now
Output:
101 Sonoo
1. class Student{
2. int rollno;
3. String name;
4. void insertRecord(int r, String n){
5. rollno=r;
6. name=n;
7. }
8. void displayInformation(){System.out.println(rollno+" "+name);}
9. }
10.class TestStudent4{
11. public static void main(String args[]){
12. Student s1=new Student();
Prepard by K.Swathi Lakshmi Durga
Assistant Professor
Department of IT
13. Student s2=new Student();
14. s1.insertRecord(111,"Karan");
15. s2.insertRecord(222,"Aryan");
16. s1.displayInformation();
17. s2.displayInformation();
18. }
19.}
Test it Now
Output:
111 Karan
222 Aryan
As you can see in the above figure, object gets the memory in heap memory area.
The reference variable refers to the object allocated in the heap memory area.
Here, s1 and s2 both are reference variables that refer to the objects allocated in
memory.
1. class Employee{
2. int id;
Prepard by K.Swathi Lakshmi Durga
Assistant Professor
Department of IT
3. String name;
4. float salary;
5. void insert(int i, String n, float s) {
6. id=i;
7. name=n;
8. salary=s;
9. }
10. void display(){System.out.println(id+" "+name+" "+salary);}
11.}
12.public class TestEmployee {
13.public static void main(String[] args) {
14. Employee e1=new Employee();
15. Employee e2=new Employee();
16. Employee e3=new Employee();
17. e1.insert(101,"ajeet",45000);
18. e2.insert(102,"irfan",25000);
19. e3.insert(103,"nakul",55000);
20. e1.display();
21. e2.display();
22. e3.display();
23.}
24.}
Test it Now
Output:
Variable is a name of memory location. There are three types of variables in java:
local, instance and static.
There are two types of data types in Java: primitive and non-primitive.
Variable
Types of Variables
o local variable
o instance variable
o static variable
1) 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.
2) 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.
Prepard by K.Swathi Lakshmi Durga
Assistant Professor
Department of IT
It is called an instance variable because its value is instance-specific and is not
shared among instances.
3) Static variable
Instance Method
Method in Java
In Java, a method is like a function which is used to expose the behavior of an
object.
Advantage of Method
o Code Reusability
o Code Optimization
Method Declaration
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.
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 Java, Method Overloading is not possible by changing the return type of the
method only.
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.
Prepard by K.Swathi Lakshmi Durga
Assistant Professor
Department of IT
1. class Adder{
2. static int add(int a,int b){return a+b;}
3. static int add(int a,int b,int c){return a+b+c;}
4. }
5. class TestOverloading1{
6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11));
8. System.out.println(Adder.add(11,11,11));
9. }}
Test it Now
Output:
22
33
Constructors 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.
1. <class_name>(){}
2. class Bike1{
3. //creating a default constructor
4. Bike1(){System.out.println("Bike is created");}
5. //main method
Prepard by K.Swathi Lakshmi Durga
Assistant Professor
Department of IT
6. public static void main(String args[]){
7. //calling a default constructor
8. Bike1 b=new Bike1();
9. }
10.}
Test it Now
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.
In Java, a constructor is just like a method but without return type. It can also be
overloaded like Java methods.
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.
1111,"Karan 11 K’
222,"Aryan",25a
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).
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.
Prepard by K.Swathi Lakshmi Durga
Assistant Professor
Department of IT
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.
1. class Employee{
2. float salary=40000;
3. }
4. class Programmer extends Employee{
5. int bonus=10000;
6. public static void main(String args[]){
7. Programmer p=new Programmer();
8. System.out.println("Programmer salary is:"+p.salary);
9. System.out.println("Bonus of Programmer is:"+p.bonus);
10.}
11.}
Test it Now
Programmer salary is:40000.0
Bonus of programmer is:10000
Prepard by K.Swathi Lakshmi Durga
Assistant Professor
Department of IT
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.
When one class inherits multiple classes, it is known as multiple inheritance. For
Example:
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class TestInheritance{
8. public static void main(String args[]){
9. Dog d=new Dog();
10.d.bark();
11.d.eat();
12.}}
Output:
File: TestInheritance2.java
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class BabyDog extends Dog{
8. void weep(){System.out.println("weeping...");}
9. }
10.class TestInheritance2{
11.public static void main(String args[]){
12.BabyDog d=new BabyDog();
13.d.weep();
14.d.bark();
15.d.eat();
16.}}
Output:
weeping...
barking...
eating...
To reduce the complexity and simplify the language, multiple inheritance is not
supported in java.
Consider a scenario where A, B, and C are three classes. The C class inherits A and
B classes. If A and B classes have 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.
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.
Output:
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.
Compile-time Polymorphism
Compile-time polymorphism is also known as static polymorphism or early
binding. Compile-time polymorphism is a polymorphism that is resolved during
the compilation process. Overloading of methods is called through the reference
variable of a class. Compile-time polymorphism is achieved by method
overloading and operator overloading.
1. Method overloading
We can have one or more methods with the same name that are solely
distinguishable by argument numbers, type, or order.
Method Overloading occurs when a class has many methods with the same
name but different parameters. Two or more methods may have the same name
if they have other numbers of parameters, different data types, or different
numbers of parameters and different data types.
The this keyword can be used to refer current class instance variable. If there is
ambiguity between the instance variables and parameters, this keyword resolves
the problem of ambiguity.
Suggestion: If you are beginner to java, lookup only three usages of this keyword.
The this keyword can be used to refer current class instance variable. If there is
ambiguity between the instance variables and parameters, this keyword resolves
the problem of ambiguity.
1. class Student{
2. int rollno;
You may invoke the method of the current class by using the this keyword. If you
don't use the this keyword, compiler automatically adds this keyword while
invoking the method. Let's see the example
The this() constructor call can be used to invoke the current class constructor. It is
used to reuse the constructor. In other words, it is used for constructor chaining.
1. class Student{
2. int rollno;
3. String name,course;
4. float fee;
5. Student(int rollno,String name,String course){
6. this.rollno=rollno;
7. this.name=name;
8. this.course=course;
9. }
10.Student(int rollno,String name,String course,float fee){
11.this(rollno,name,course);//reusing constructor
12.this.fee=fee;
13.}
14.void display(){System.out.println(rollno+" "+name+" "+course+" "+fee);}
15.}
16.class TestThis7{
17.public static void main(String args[]){
18.Student s1=new Student(111,"ankit","java");
19.Student s2=new Student(112,"sumit","java",6000f);
20.s1.display();
21.s2.display();
22.}}
Test it Now
Output:
We can use super keyword to access the data member or field of parent class. It is
used if parent class and child class have same fields.
class Animal {
protected String type="animal";
}
class Main {
public static void main(String[] args) {
Dog dog1 = new Dog();
dog1.printType();
Prepard by K.Swathi Lakshmi Durga
Assistant Professor
Department of IT
}
}
Run Code
Output:
I am a mammal
I am an animal
The super keyword can also be used to invoke parent class method. It should be
used if subclass contains the same method as parent class. In other words, it is
used if method is overridden.
class Animal {
// overridden method
public void display(){
System.out.println("I am an animal");
}
}
// overriding method
@Override
public void display(){
System.out.println("I am a dog");
}
class Main {
public static void main(String[] args) {
Dog dog1 = new Dog();
dog1.printMessage();
}
}
Run Code
Output
I am a dog
I am an animal
The super keyword can also be used to invoke the parent class constructor.
class Animal {
System.out.println("I am a dog");
}
}
class Main {
public static void main(String[] args) {
Dog dog1 = new Dog();
}
}
Run Code
Output
I am an animal
I am a dog
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.
class Main {
public static void main(String[] args) {
class FinalDemo {
// create a final method
public final void display() {
System.out.println("This is a final method.");
}
}
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.
Output:
If you apply static keyword with any method, it is known as static method.
Prepard by K.Swathi Lakshmi Durga
Assistant Professor
Department of IT
o A static method belongs to the class rather than the object of a class.
o A static method can be invoked without the need for creating an instance
of a class.
o A static method can access static data member and can change the value of
it.
The role of an abstract class is to contain abstract methods. However, it may also
contain non-abstract methods. The method which is declared with abstract
keyword and doesn't have any implementation is known as an abstract method.
Syntax:-
Don'ts
Do's
Output:
Bike is running
Interface in Java
An interface in Java is a blueprint of a class. It has static constants and abstract
methods.
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.
Syntax:
1. interface <interface_name>{
2.
3. // declare constant fields
4. // declare methods that abstract
5. // by default.
6. }
The relationship between classes and interfaces
As shown in the figure given below, a class extends another class, an interface
extends another interface, but a class implements an interface.
In this example, the Printable interface has only one method, and its
implementation is provided in the A6 class.
1. interface printable{
2. void print();
3. }
4. class A6 implements printable{
5. public void print(){System.out.println("Hello");}
6.
7. public static void main(String args[]){
8. A6 obj = new A6();
9. obj.print();
10. }
11.}
Test it Now
Output:
Hello
1. interface Printable{
2. void print();
3. }
4. interface Showable{
5. void show();
6. }
7. class A7 implements Printable,Showable{
8. public void print(){System.out.println("Hello");}
9. public void show(){System.out.println("Welcome");}
10.
11.public static void main(String args[]){
12.A7 obj = new A7();
13.obj.print();
14.obj.show();
15. }
16.}
Test it Now
Output:Hello
Prepard by K.Swathi Lakshmi Durga
Assistant Professor
Department of IT
Welcome
We use inner classes to logically group classes and interfaces in one place to be
more readable and maintainable.
Additionally, it can access all the members of the outer class, including private
data members and methods.
There are three advantages of inner classes in Java. They are as follows:
Sometimes users need to program a class in such a way so that no other class can
access it. Therefore, it would be better if you include it within other classes.
If all the class objects are a part of the outer object then it is easier to nest that
class inside the outer class. That way all the outer class can access all the objects
of the inner class.
An inner class is a part of a nested class. Non-static nested classes are known as
inner classes.
There are two types of nested classes non-static and static nested classes. The
non-static nested classes are also known as inner classes.
Syntax:
1. class Outer{
2. //code
3. class Inner{
Prepard by K.Swathi Lakshmi Durga
Assistant Professor
Department of IT
4. //code
5. }
6. }
1. class TestMemberOuter1{
2. private int data=30;
3. class Inner{
4. void msg(){System.out.println("data is "+data);}
5. }
6. public static void main(String args[]){
7. TestMemberOuter1 obj=new TestMemberOuter1();
8. TestMemberOuter1.Inner in=obj.new Inner();
9. in.msg();
10. }
11.}
Test it Now
Output:
data is 30
The general form of syntax to create an object of the member inner class is as
follows:
Syntax:
1. OuterClassReference.new MemberInnerClassConstructor();
1. obj.new Inner();
Java anonymous inner class is an inner class without a name and for which only a
single object is created. An anonymous inner class can be useful when making an
instance of an object with certain "extras" such as overloading methods of a class
or interface, without having to actually subclass a class.
In simple words, a class that has no name is known as an anonymous inner class
in Java. It should be used if you have to override a method of class or interface.
Java Anonymous inner class can be created in two ways:
TestAnonymousInner.java
nice fruits
A class i.e., created inside a method, is called local inner class in java. Local Inner
Classes are the inner classes that are defined inside a block. Generally, this block
is a method body. Sometimes this block can be a for loop, or an if clause. Local
Inner classes are not a member of any enclosing classes. They belong to the block
they are defined within, due to which local inner classes cannot have any access
modifiers associated with them. However, they can be marked as final or abstract.
These classes have access to the fields of the class enclosing it.
If you want to invoke the methods of the local inner class, you must instantiate
this class inside the method.
LocalInner1.java
In such a case, the compiler creates a class named Simple$1Local that has the
reference of the outer class.
Java Package
A java package is a group of similar types of classes, interfaces and sub-packages.
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.
Here, we will have the detailed learning of creating and using user-defined
packages.
Advantage of Java Package
1) Java package is used to categorize the classes and interfaces so that they can
be easily maintained.
1. //save as Simple.java
2. package mypack;
3. public class Simple{
4. public static void main(String args[]){
5. System.out.println("Welcome to package");
6. }
7. }
How to compile java package
If you are not using any IDE, you need to follow the syntax given below:
1. javac -d . Simple.java
The -d switch specifies the destination where to put the generated class file. You
can use any directory name like /home (in case of Linux), d:/abc (in case of
windows) etc. If you want to keep the package within the same directory, you can
use . (dot).
You need to use fully qualified name e.g. mypack.Simple etc to run the class.
There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
1) 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.
Prepard by K.Swathi Lakshmi Durga
Assistant Professor
Department of IT
Example of package that import the packagename.*
1. //save by A.java
2. package pack;
3. public class A{
4. public void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. import pack.*;
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. obj.msg();
9. }
10.}
Output:Hello
2) Using packagename.classname
If you import package.classname then only declared class of this package will be
accessible.
If you use fully qualified name then only declared class of this package will be
accessible. Now there is no need to import. But you need to use fully qualified
name every time when you are accessing the class or interface.
It is generally used when two packages have same class name e.g. java.util and
java.sql packages contain Date class.