Unit 1 (Complete)
Unit 1 (Complete)
Unit-1
Introduction: Why Java, History of Java, JVM, JRE, Java Environment, Java Source File
Structure, and Compilation.
Fundamental, Programming Structures in Java: Defining Classes in Java, Constructors,
Methods, Access Specifies, Static Members, Final Members, Comments, Data types,
Variables, Operators, Control Flow, Arrays & String.
Object Oriented Programming: Class, Object, Inheritance Super Class, Sub Class,
Overriding, Overloading, Encapsulation, Polymorphism, Abstraction, Interfaces, and
Abstract Class.
Packages: Defining Package, CLASSPATH Setting for Packages, Making JAR Files for
Library Packages, Import and Static Import Naming Convention For Packages
1
❑ Introduction To Java
❑ History
❑ Applications
• Java applications are compiled to byte code that can run on any JVM.
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) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak Technologies.
6) In 1995, Time magazine called Java one of the Ten Best Products of 1995.
4) JavaFX
It is used to develop rich internet applications.
It uses a light-weight user interface API. 6
JAVA VERSIONS
Versions of Java released till date: Version Year
JDK Alpha and Beta 1995
JDK 1.0 1996
JDK 1.1 1997
J2SE 1.2 1998
J2SE 1.3 2000
J2SE 1.4 2002
J2SE 5.0 2004
Java SE 6 2006
Java SE 7 2011
Java SE 8 2014
Java SE 9 2017
Java SE 10 2018
7
FEATURES OF JAVA
8
Cont…
1. Object-Oriented: Everything in Java is an object. OO means we organize our software as a
combination of different types of objects that incorporates both data and behavior.
2. Simple: very easy to learn, simple syntax, clean and easy to understand. Removed many
complicated and rarely-used features: pointers, operator overloading, etc.
3. Portable: It facilitates us to carry Java bytecode to any platform. Doesn't require any implementation.
4. Secured
we can develop virus-free systems. Java is secured because:
• No explicit pointer
• Java Programs run inside a virtual machine sandbox
5) Platform independent: Java code can be run on multiple platforms(i.e., Write Once and Run
Anywhere(WORA). Ex. Windows, Linux, Sun Solaris, Mac/OS, etc
6) Robust(means strong)
Strong memory management.
• No pointers that avoids security problems.
• Automatic garbage
•Exception handling & the type checking mechanism 9
JAVA ARCHITECTURE
10
First Java Program | Hello World Example
class First{
public static void main(String args[]){
System.out.println("Hello Java");
}
}
save this file as First.java
11
JDK, JRE and JVM
JRE = JVM + libraries to run Java application.
JDK = JRE + tools to develop Java Application.
❑ DATA TYPES
❑ OPERATORS
❑ KEYWORDS
13
VARIABLE
• A variable is a container which holds the value.
• It is name of reserved area allocated in memory.
• It is a combination of "vary + able" i.e. its value can be changed.
• It is assigned with a data type.
• There are 3 types of variables in java: local, instance and static.
14
Example to understand the types of variables ➔
Types of Variables
class A{
a) Local variables: int data=50; //instance variable
static int m=100; //static variable
• Tied to method
void method(){
• Its scope is within the method. int n=90; //local variable
• It cannot be defined with "static" keyword. }
} //end of class
b) Instance variable:
• variable declared inside the class but outside the body of the method.
• It is not declared as static.
• Its value is instance specific and is not shared among instances, ie. Scope is whole class
c) Static variable:
• Variable declared is as static.
• Cannot be local.
• Its single copy is created and shared among all the instances of the class.
• Its memory allocation happens only once when class is loaded in memory.
15
Example: (Static variable , Instance variable, local variable)
public class VarEx {
static int stVar = 10;
int instVar = 20;
public void exMethod() {
int locVar = 30;
System.out.println("Static Variable: " + stVar);
System.out.println("Instance Variable: " + instVar);
System.out.println("Local Variable: " + locVar); }
1.Primitive data types: It include boolean, char, byte, short, int, long, float & double.
21
Data Types, Size, Minimum and Maximum Range along with Default Value
Types of operators:
Operator Type Category Precedence
>> is used to move left operands value to right by the no. of bits specified by the right operand.
26
Bitwise &(AND) Operator Example:
27
Bitwise ^(exclusive OR) Operator Example:
Example:
class TrnyOpr {
public static void main(String[] args) {
29
Java Comments
• Statements that are not executed by the compiler and interpreter.
• Used to provide information or explanation about the variable, method, class or any statement
Types of Java Comments: 1. Single Line Comment (//) 2. Multi Line Comment(/* */)
31
Scanner and BufferedReader
• Two classes that have been used for reading files for a very long time.
Scanner import java.util.Scanner;
- java.util.Scanner class is a simple text
class scannerEx {
scanner which can parse primitive types
and strings. public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
• A user can read numbers from
System.out.println("Enter a String:");
System.in by using Scanner class.
String a = sc.nextLine();
1. A scanner is a much more powerful utility than BufferedReader. It can parse the user input and
read an int, short, byte, float, long and double apart from String. On the other
hand, BufferedReader can only read String in Java.
2. BuffredReader has a significantly large buffer (8KB) than Scanner (1KB), which means if
you are reading long String from a file, you should use BufferedReader but for short input and
input other than String, you can use Scanner class.
3. BufferedReader is older than Scanner. It's present in Java from JDK 1.1 onward but
Scanner is only introduced in JDK 1.5 release.
4. BufferedReader is synchronized while Scanner is not. This means, you cannot share
Scanner between multiple threads but you can share the BufferedReader object.
34
Command-line Arguments
• CLA is the information that is passed to the program when it is executed.
• There is no restriction on the number of java command line arguments.
• Information is passed as Strings. They are captured into the String args of the main method.
• Information directly follows the program’s name on the command line when it is running.
Example:
While running a class Demo, you can specify command line arguments as
java Demo arg1 arg2 arg3 …
class Demo{
public static void main(String b[]){
System.out.println("Argument one = "+b[0]);
System.out.println("Argument two = "+b[1]);
}
}
35
# PARSE #
PARSE : It is a method which take a string(input) as an argument and convert in other formats as
like :
Integer
Float
Double
36
// Without Parse Method Example (With Parse ) :
class A
{ class A
public static void main(String args[])
{ {
System.out.println(“WITHOUT PARSING!!!!!!”); public static void main(String args[])
System.out.println(args[0]+1);
System.out.println(args[1]+1); {
int a=Integer.parseInt(args[0]);
}}
int b=Integer.parseInt(args[1]);
System.out.println(a+1);
Compile : Javac A.java
Execution : Java A 10 20 System.out.println(b+1);
}
Output :
}
WITHOUT PARSING!!!!!!
Compile : Javac A.java
Output : 101 201 Execution : Java A 10 20
Output : 11 21
37
Arrays
38
ARRAYS
Objects that help us organize large amounts of information
It is an ordered list of values
Each value has a numeric index
The entire array
has a single name 0 1 2 3 4 5 6 7 8 9
79 87 94 82 67 98 87 81 74 91
scores
An array of size N is indexed from zero to N-1 This array holds 10 values that are indexed from 0 to 9
Value in an array is referenced by the array name followed by the index in brackets.
For example, scores[2]: refers to the value 94 (the 3rd value in the array)
Syntax to declare:
1.dataType[][] arrayRefVar; (or) Instantiation:
2.dataType arrayRefVar[][]; (or)
3.dataType []arrayRefVar[]; int[][] arr=new int[3][3]; //3 row,3 column
//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println(); } }} 41
STRING HANDLING
42
String
• In Java, String is basically an object that represents sequence of char values. An array of
characters works same as Java string. For example:
char[] ch={'j','a','v','a','t','p',’r',’o',’g',’r’,’a’,’m’};
String s=new String(ch);
is same as: String s="javatprogram";
• String class methods: Used to perform operations on strings such as compare(), concat(),
equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.
• The StringBuffer and StringBuilder classes have the same methods with one
47
String class methods
• By the help of these methods, we can perform operations on string such as trimming, concatenating,
converting, comparing, replacing strings etc.
3 ways:
• public boolean equals(Object another) compares this string to the specified object.
50
Example:
It compares the content of the strings. It will return true if string matches, else returns false.(But match the case)
class Teststringcomparison1{
public static void main(String args[]){
String s1="Krishna";
String s2="Krishna";
String s3=new String("Krishna");
String s4="Abhineet";
System.out.println("s1.equals(s2)=>>"+s1.equals(s2));
System.out.println("s1.equals(s3)=>>"+s1.equals(s3));
System.out.println("s1.equals(s4)=>>"+s1.equals(s4)); } }
Example: It compares the content of the strings. It will return true if string matches, else returns false.(But match the
case). To ignore the case, use “equalsIgnoreCase())
class Teststringcomparison2{
public static void main(String args[]){
String s1="Kunj";
String s2="KUNJ";
System.out.println("s1.equals(s2)=>>"+s1.equals(s2));//false
System.out.println("s1.equalsIgnoreCase(s2)=>>"+s1.equalsIgnoreCase(s2));//true
} }
51
(B-2) Using == operator
compares two object references to check whether they refer to same instance.
This also, will return true on successful match else returns false.
class Test3{
public static void main(String args[]){
String s1="Kunj";
String s2="Kunj";
String s3=new String("Kunj");
System.out.println("s1==s2=>>"+(s1==s2));//true (because both refer to same instance)
System.out.println("s1==s3=>>"+(s1==s3));//false(because s3 refers to instance created in nonpool)
} }
We can get substring from the given string object by one of the two methods:
Example :
public class TestSubstring{
public static void main(String args[]){
String s="Aviral Maitrey";
System.out.println(s.substring(7)); //Maitrey
System.out.println(s.substring(0,6)); // Aviral
}
} 53
(D) String toUpperCase() and toLowerCase() method
toUpperCase() : converts given string into uppercase letter
toLowerCase() : converts given string into lowercase letter.
Example: public class TestCase{
public static void main(String args[]){
String s="Abhineet";
System.out.println("s.toUpperCase()=>>"+s.toUpperCase()); //ABHINEET
System.out.println("s.toLowerCase()=>>"+s.toLowerCase()); //abhineet
System.out.println("Original String=>>"+s); //Abhineet(no change in
original)
} }
(E) String trim() method
eliminates white spaces before and after string
Example:
public class TestTrim
{
public static void main(String args[]){
String s=" Abhineet";
System.out.println("Actual string=>>"+s); // Abhineet(with whitespace)
System.out.println("Using trim=>>"+s.trim()); //Abhineet(no whitespace)
}
}
54
(F) startsWith() and endsWith() method
startsWith(): check whether the given string starts with given prefix or not and returns true when prefix matches the string else it returns
false.
endsWith(): check whether the string ends with the given suffix or not and returns true when suffix matches the string else it returns false.
Example: public class TestStartEnd{
public static void main(String args[]){
String s="Abhineet";
System.out.println("Given String is=>"+s);
System.out.println(s.startsWith("Se")); //false
System.out.println(s.endsWith("t")); //true
System.out.println(s.startsWith("Ab")); //true
System.out.println(s.startsWith("ab")); //false
System.out.println(s.endsWith("T")); //false
} }
Example:
58
(M) toCharArray() method
converts this string into character array.
It returns a newly created character array, its length is similar to this string and its contents are initialized with the characters of this string.
59
CLASS AND OBJECT
60
Classes and objects are the two main aspects of OOP
61
a) object
• An entity that has state and behavior is known as an object
e.g., chair, bike, marker, pen, table, car, etc.
A class is a template or blueprint from which objects are created. So, an object is the
instance(result) of a class.
62
b) 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. Syntax to declare a class:
class <class_name>{
▪ A class in Java can contain:
field;
▪ Fields method;
▪ Methods }
▪ Constructors
▪ Blocks
▪ Nested class and interface
Create an Object
An object is created from a class.
To create an object, specify the class name, followed by the object name, and use keyword new:
class Student.
A simple class example {
Suppose, Student is a class and student's name, roll number, age are its String name;
fields and info() is a method. Then class will look like below. int rollno;
int age;
void info(){
// some code
}
} 64
Ex: Create Student class
Student class has two data members id and name.
We are creating the object of the Student class by new keyword and printing the object's value.
67
A method is a block of code grouped together to perform a certain task or operation.
68
Method Declaration
The method declaration provides information about method attributes, such as visibility,
return-type, name, and arguments. It has six components that are known as method header
(1) Predefined Method: Methods that is already defined in the Java class libraries.
• 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.
70
Example of the predefined method
public class Demo
{
public static void main(String[] args)
{
// using the max() method of Math class
System.out.print(“Maximum number is: " + Math.max(9,7));
}
Output:
Ex: Create and call user defined method(findEvenOdd) that checks the number is even or odd:
import java.util.Scanner;
public class EvenOdd {
} 72
Call by Value and Call by Reference in Java
1) call-by-value :
In this approach copy of an argument value is pass to a method.
Changes made to the argument value inside the method will have no
effect on the arguments.
2) call-by-reference :
Java does not support call by reference directly. However, we can
achieve similar behavior by passing objects as arguments since object
references are passed by value. 73
original value is not changed, because a copy of the argument is passed to the
method, and modifications to the parameter inside the method do not affect the original
argument.)
76
Method overloading
• Allows to declare multiple methods with same name but different parameters in the same
class.
• Java supports method overloading and always occur in the same class(unlike method
overriding).
• Method overloading is one of the ways through which java supports polymorphism.
• Polymorphism is a concept of OOPg that deal with multiple forms.
• Method overloading can be done by changing number of arguments or by changing the
data type of arguments.
79
Overloading main Method
In Java, we can overload the main() method using different number and types of
parameter but the JVM only understand the original main() method.
81
To access class members, we must first create an instance of the class. If we
want to access class members without creating an instance of the class, we
need to declare the class members static.
• The static keyword in java is used for memory management mainly.
• Can be applied with variables, methods, blocks and nested class.
• Belongs to the class than instance of the class.
The static can be:
variable (also known as class variable)
1. method (also known as class method)
2. block
3. nested class
82
Static variable
• If any variable declared as static, it is known static variable.
• Static variable can be used to refer the common property of all objects e.g. company
name of employees, college, name of students etc.
• Gets memory only once in class area at the time of class loading.
Advantage of static variable
• It makes your program memory efficient (i.e it saves memory).
class Student{
Example: int rollno; String name; static String college =“KIET";
Student(int r,String n)
{ rollno = r; name = n;
}
void display (){
System.out.println(rollno+" "+name+" "+college);}
public static void main(String args[])
{ Student s1 = new Student(111,"KIran");
Student s2 = new Student(222,"Aryan");
s1.display();
s2.display(); } }
83
Static method
• It is applying a static keyword with any method.
• Belongs to the class rather than object of a class.
• Can be invoked without the need for creating an instance of a class.
• Can access static data member and can change the value of it.
Example: Changing the common property of all objects(static field)
class Student { int rollno; String name;
static String college = “KIET";
static void change()
{ college = “KRISHNA"; }
Student(int r, String n)
{ rollno = r; name = n; }
void display ()
{System.out.println(rollno+" "+name+" "+college);}
public static void main(String args[])
{ Student.change();
Student s1 = new Student (111,"Kiran"); Student s2 = new Student (222,"Aryan");
Student s3 = new Student (333,“Avi");
s1.display(); s2.display(); s3.display(); } }
84
Static block
86
1) final Variable
• We cannot change the value of a final
variable. For example,
In the program, we have created a
class Main { final variable named AGE. And we
public static void main(String[] args) { have tried to change the value of the
final variable.
// create a final variable
final int AGE = 32; When we run the program, we will
get a compilation error with the
// try to change the final variable following message.
AGE = 45;
System.out.println("Age: " + AGE);
}
} 87
2) final method
• the final method cannot be overridden by the child class. For
example,
class FinalDemo {
We have created a final method named display()
// create a final method inside the FinalDemo class. Here, the Main class
public final void display() { inherits the FinalDemo class.
System.out.println("This is a final method.");
} }
We have tried to override the final method in the
class Main extends FinalDemo { Main class. When we run the program, we will get a
// try to override final method compilation error with the following message.
public final void display() {
System.out.println("The final method is
overridden."); }
// create a final class We have created a final class named FinalClass. Here,
final class FinalClass { we have tried to inherit the final class by the Main
public void display() { class.
System.out.println("This is a final method."); } }
When we run the program, we will get a compilation
// try to extend the final class error with the following message.
class Main extends FinalClass {
public void display() {
System.out.println("The final method is
overridden."); }
89
Constructors
90
Constructors
Constructor is a special type of method that is used to initialize the object.
• It is invoked at the time of object creation.
• It constructs the values i.e. provides data for the object that is why it is known as
constructor.
class Book{
Example:
Book()
{
System.out.println("Book is published");
}
public static void main(String args[])
{
Book b=new Book();
}} Output: Book is published
92
Another Example:
class AddDemo1 {
AddDemo1() {
int a=10;
int b=5;
int c;
c=a+b;
System.out.println("*****Default Constructor*****");
System.out.println("Total of 10 + 5 = "+c); }
class Student{
int id; String name; int age;
Example: Student(int i,String n){
id = i;
name = n; }
Student(int i,String n,int a){ Output:
id = i;
name = n; age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}
class ChainingDemo1 {
public static void main(String as[])
{
abc obj = new abc(); }}
96
** Used when we want to perform multiple tasks by creating a single object of the class.
Difference between constructor and method
Constructor Method
compiler provides a default constructor if not specified. not provided by compiler in any case.
name must be same as the class name. may or may not be same as class name.
97
INHERITANCE IN JAVA
98
INHERITANCE IN JAVA
It is a mechanism in which one object acquires all the properties and behaviors of a parent
object.
• It is an important part of OOPs
• Idea behind inheritance: We can create new classes that are built upon existing classes.
• When existing class gets inherited, we can reuse methods and fields of the parent class.
• Moreover, we can add new methods and fields in our current class also.
• Represents the IS-A relationship which is also known as a parent-child relationship.
Usefulness of Inheritance:
99
Terms used in Inheritance
•Class: group of objects which have common properties. A blueprint from which objects are created.
•Sub Class/Child Class: class which inherits other class. Also called a derived class or extended class.
•Super Class/Parent Class: class from where a subclass inherits the features. Also called a base class
•Reusability: Able to use the same fields and methods already defined in previous class by a new class
Syntax of Inheritance:
class Subclass-name extends Superclass-name
{
//methods and fields
}
The extends keyword used to make a class that derives from an existing class.
The meaning of "extends" is to increase the functionality.
class which is inherited is called a superclass, and the new class is called
subclass.
100
Example:
• In this 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=80000;
}
class Programmer extends Employee{
int bonus=25000; Output:
public static void main(String args[]){
Programmer p=new Programmer(); Programmer salary is:80000.0
System.out.println("Programmer salary is:"+p.salary); Bonus of programmer is:25000
System.out.println("Bonus of Programmer is:"+p.bonus);
} }
In this example:
Programmer object can access its own field as well as of Employee class i.e. code reusability.
101
Types of Inheritance
1) Single Inheritance: One class inherits from one parent class. (One parent, one
children)
102
Ex. of Single Inheritance
class A{
String bookname=“WEB TECH”;
void show() {
System.out.println(" Book Name = "+ bookname);
}
}
public class B extends A{
int price=250;
void display()
{
System.out.println(" Book Price= "+ price);
}
public static void main(String[] args) {
B b = new B();
b.show();
b.display();
}
} 104
Ex. of Multilevel Inheritance
class A{
String bookname=“Java”;
void show() {
System.out.println(" Book Name = "+ bookname);
} }
class B extends A{
int price=700;
void display() {
System.out.println(" Book Price= "+ price); }
public class C extends B{
void print() {
System.out.println(" I am using the book !!!”); }
class B extends A{
int edition=2;
void display() {
System.out.println(" Book Edition= "+ edition);
}}
class C extends A{
String publisher="TMH";
void print() {
System.out.println(" Book Publisher="+publisher);}}
class D{
public static void main(String[] args) {
B b=new B(); b.show(); b.display() ;
C c = new C(); c. show(); c.print();
} } 106
Encapsulation
Definition: hiding the internal details of a class and only allowing access
through public methods.
Encapsulation = Data + Methods bundled together and make variables
private, use getters and setters to access them.
Encapsulation = Private Data + Public Access Methods
Key Points:
Use private for variables (to hide data)
Use public methods to get and set the values.
It's like a capsule that keeps data safe inside
Benefits:
Protects data (no direct access)
Provides control over what is stored
Easy to maintain and modify
Prevents invalid data
107
Example: simple encapsulation program that includes age with validation.
class Student {
public class AgeValidationExample {
private int age;
public static void main(String[] args) {
// Setter with validation
Student s = new Student();
public void setAge(int newAge) {
s.setAge(15); // valid age
if (newAge > 0 && newAge <= 120) {
age = newAge; System.out.println("Student Age: " +
s.getAge());
} else {
System.out.println("Invalid age! s.setAge(-3); // invalid age
Please enter a value between 1 and 120."); System.out.println("Student Age: " +
} } s.getAge()); // will still show previous valid
// Getter method age
class Animal {
void sound() {
System.out.println("Animal makes a sound"); } }
s1.area();
s2.area();
s3.area();
Benefit: You treat all objects the same (as Shape), but
they behave differently! 114
Key Difference:
115
Abstraction
116
Abstraction
Definition: Abstraction means hiding unnecessary details and showing only
essential features to the user.
Real-Life Example:
When you drive a car, you just: turn the steering press accelerator.
But do you care how the engine works inside?
That’s abstraction — you use features, not internal code.
117
Abstract Class
• A class which is declared using abstract keyword.
• It can have abstract and non-abstract methods.
• Cannot create object of abstract class(Can’t be instantiated) but
they can be subclassed.
• Used to achieve abstraction but it does not provide 100% abstraction
because it can have concrete methods.
118
Abstract method
Output:
Area of Circle: 78.5
Area of Rectangle: 50
122
Abstract class with non-abstract method
Abstract classes can also have non abstract methods along with abstract methods.
But, while extending the class, provide definition for the abstract method.
abstract class A {
abstract void ROI();
public void show() {
System.out.println("this is non-abstract method");
}
}
class B extends A {
void ROI() {
System.out.println("Calling parent... Rate of Interest!!!!"); }
public static void main(String[] args) {
B b = new B();
b.ROI();
b.show(); } }
123
INTERFACE
124
INTERFACE
is a blueprint of a class. It has static constants and abstract methods.
• It is used to achieve abstraction and multiple inheritance in Java.
• There can be only abstract methods in the java interface not method body.
• Java Interface also represents IS-A relationship.
• It cannot be instantiated just like abstract class.
• Declare an interface: 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 methods declared in
interface.
interface <interface_name>{
Syntax: // declare constant fields
// declare methods that abstract by default.
}
125
• Java compiler adds public & abstract keywords before the interface method.
• Also adds public, static and final keywords before data members.
• Thus, Interface fields are public, static and final by default, and the methods are public
and abstract.
but
class abc{
public static void main(String args[]){
Bank ob1 = new SBI();
Bank ob2 = new BOB();
System.out.println("Hello");
System.out.println("ROI of SBI=>>"+ob1.printROI());
System.out.println("ROI of BOB=>>"+ob2.printROI()); } } 130
Multiple inheritance in Java by Interface:
If a class implements multiple interfaces, or an interface extends multiple
interfaces, it is known as multiple inheritance.
Example:
interface emp{
void print(); }
interface dept
void print(); }
class MyInterface implements emp, dept{
public void print(){
System.out.println("Hello");}
emp and dept interface have same methods but its implementation is provided by
class MyInterface1, so there is no ambiguity. 131
Why Interfaces required?
• Interface allows us to implement common behaviour in two different
classes.
• Interfaces allows us to apply behaviours beyond classes and class
hierarchy.
• Consistent specification among unrelated classes.
• Reduce coupling between software component
• Two or more classes may not achieve same functionality.(No duplicity
of class)
• Create richer classes.
133
Abstract class Interface
a class which contain one or more abstract Interface is a Java Object containing method
methods, which has to be implemented by declaration but no implementation. The
its sub classes. classes which implement the Interfaces must
provide the method definition for all the
methods.
Abstract class is a class prefix with an Interface is a pure abstract class which starts
abstract keyword followed by class with interface keyword.
definition.
Abstract class can also contain concrete Interface contains all abstract methods and
methods. final variable declarations.
Abstract classes are useful in a situation that Interfaces are useful in a situation that all
Some general methods should be properties should be implemented.
implemented and specialization behavior
should be implemented by child classes.
134
❑Access Specifiers
❑Packages
135
Modifiers in java
Modifiers are specific keywords using which we can make changes to the characteristics of a
variable, method, or class and limit its scope.
Types of modifiers in java: Access modifiers and non-access modifiers.
1. private
-The access modifiers/specifiers— a very important OOP
2. default
concept for data protection, security, and encapsulation.
3. protected
specifies accessibility (scope) of a data member, method,
4. public
constructor or class.
There are 4 types of java access modifiers
1. static
2. final
- Non-Access modifiers: provide information about the
3. abstract
characteristics of a class, method, or variable to the 4. synchronized
JVM. 7 types of Non-Access modifiers are: 5. volatile
6. transient
7. native 136
Types of Access Specifiers in Java:
137
1. public Example
package mainapp;
package test; import test.A;
138
2. private Example
class priv{
package test2;
class privv { public static void main(String[] args) {
private int p=100; privv ob1=new privv();
private void show() { //System.out.println("value of
System.out.println("I am in a p="+ob1.p);//error
private college!!!!!"+p); //ob1.show(); //error
} ob1.display();
public void display() }
{
show(); }
}
} OP:
I am in a private college!!!!!100
Used only inside the same class.
139
3. Default (no keyword required)
class A { class B {
int x = 30; // default access public static void main(String[] args) {
A obj = new A(); // Same package
void show() { obj.show();
System.out.println("Default show() in A"); }
} }
}
140
4. protected Example package test1;
import test2.priv;
package test2;
class testt1 extends priv{
public class priv {
protected int p=100;
public static void main(String[] args) {
protected void show() {
testt1 ob1=new testt1();
System.out.println("I am in a
System.out.println("value of p="+ob1.p);
protected college!!!!!"+p);
ob1.show();
}
}
}
}
141
Member access and Inheritance
• A subclass includes all members of its super class but can’t access its private declared members.
• Attempt to access a private variable would cause compilation error as it causes access violation.
• The variables declared as private, is only accessible by other members of its own class.
• Subclass have no access to it. 142
Package
• A package is like a folder (has its unique name ) that groups similar types of
classes, interfaces and sub-packages.
• For example: package shapes; // inside Circle.java
- This means the class is part of the shapes package.
Types of Packages:
Advantage of Package
1) used to categorize the classes and interfaces into a separate namespace, or name group
so that they can be easily maintained.
2) provides access protection.
3) removes naming collision.
143
Built-in Packages
These packages consist of a large number of classes . Commonly used built-in packages are:
1) java.lang: Contains language support classes(e.g classed which defines primitive data
types, math operations). This package is automatically imported.
2) java.io: Contains classed for supporting input / output operations.
3) java.util: Contains utility classes which implement data structures like Linked List,
Dictionary and support ; for Date / Time operations.
4) java.applet: Contains classes for creating Applets.
5) java.awt: Contain classes for implementing the components for GUI (like button , menus
etc).
6) java.net: Contain classes for supporting networking operations.
144
How to Create a package?(using command prompt)
• Choose the name of the package. Include the package command as the first line of code in Source File.
• The Source file contains the classes, interfaces, etc you want to include in the package. Compile to create
the Java packages
A folder with the given package name is created in the specified destination, & the compiled class files will be placed in
that folder.
The -d switch specifies the destination where to put the generated class file. You can use any directory name like
d:/abc (in case of windows) etc. If you want to keep the package within the same directory, you can use . (dot).
Although interfaces & classes with same name can’t appear in the same package, they can appear in different packages
145
package mypack;
public class Simple
{
public static void main(String args[])
{ System.out.println("Welcome to package"); } }
package mypack;
class calc {
int a; OP:
int b;
void sum(int n,int m){
a=n;
b=m;
int s=a+b;
System.out.println("Sum is=>>"+s); }
import mypack.calc;
class usePack {
public static void main(String[] args) {
calc c=new calc();
c.sum(10,20);
}}
• If there are several classes inside package mypack then import the package as:
import mypack.*;
149
Steps to Create a Package in Eclipse
Step 1: Create Java Project
1. Create shapes package, Right-click on src → New → PackageName: shapes → Click Finish
2. Create mainapp package, Right-click on src → New → PackageName: mainapp → Click
Finish
151
• Now add another shape — a Square — and use both Circle and Square from the
shapes package in your mainapp.MainApp class.
• Add Square.java in the shapes package. Modify MainApp.java to use both Circle and
Square
Step 1: Create Square.java in shapes package, Right-click on the shapes package, Click
New → ClassName it: Square → Click Finish
package shapes;
public class Square {
double side;
public Square(double s) {
side = s; }
package mainapp;
// Import both classes
import shapes.Circle; Output:
import shapes.Square;
Area of Circle = 95.03317777109125
public class MainApp { Area of Square = 16.0
public static void main(String[] args) {
// Circle
Circle c = new Circle(5.5);
c.area();
// Square
Square s = new Square(4);
s.area();
}} 153
Classpath settings for packages in Eclipse
Required especially while working with multiple packages
- Eclipse automatically handles classpath settings for packages inside the src folder of a
Java project. We rarely need to manually set anything unless we are importing external
libraries (JARs).
154
Check/Verify Classpath in Eclipse:
Here’s where you add external JARs (if needed), Click OK to close
155
JAR( creating & running in cmd prompt
A JAR file (Java ARchive) is a file format used to package Java classes and associated
metadata and resources (like images, property files, etc.) into a single file for distribution.
Running a JAR File: it’s an executable JAR with a Main-Class in the manifest:
> java -jar MyApp.jar 156
PRACTICE PROGRAM
1- make a java file:
public class demoJar {
public static void main(String[] args) {
System.out.println("Hello, World!");
Output Explanation
} }
2- save as demoJar.java and compile it In cvfm,
3- make a manifest file-manifest.mf and write:
Manifest-Version: 1.0
c : Create a new JAR.
Main-Class: demoJar
(Press enter to insert a new blank line) v: Verbose output (shows
4- make a jar file file as below: details/ view or update).
f: Specify the JAR file name.
C:\practiceOOPS>jar cvfm demo.jar manifest.mf demoJar.class
m: Include the manifest file.
OP: added manifest
adding: demoJar.class(in = 421) (out= 292)(deflated 30%) 157
Cont… How to Run the JAR
As the JAR is created, it can now get executed directly by using:
c:\practiceOOPS> java -jar demo.jar
- jar file get executed and give output from the main file here JarDemo.
- Now to execute same program without opening command prompt and writhing the
command, copy the demo.jar from original location and paste anywhere eg. Destop.
- From here, this executable file can be executed directly by just double clicking it.
Such application is used when needed to execute file in GUI mode without writing
command and opening command prompt.
158
Simple program on making and using jar: Example: Even or Odd Checker
Step 1: EvenOdd.java
import java.util.Scanner;
public class EvenOdd { Step 3: To make .jar
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in); 1. Compile it: javac EvenOdd.java
System.out.print("Enter a number: "); 2. Create manifest.mf:
int number = scanner.nextInt(); Manifest-Version: 1.0
if (number % 2 == 0) { Main-Class: EvenOdd
System.out.println(number + " is even "); 3. Make the JAR file:
} else { jar cvfm evenodd.jar manifest.mf EvenOdd.class
System.out.println(number + " is odd "); 4. Run the JAR:
} } } java -jar evenodd.jar
Step 2: Compile & Run:
c:\OOPJ>javac EvenOdd.java
c:\OOPJ>java EvenOdd
Enter a number: 9
9 is odd
c:\OOPJ>java EvenOdd
Enter a number: 8
159
8 is even
Using External Packages or JARs or external Java
libraries(in Eclipse)
To use external Java libraries, you need to:
Now your classpath includes that library, and you can use it in
your code. 160
Making jar files for library packages(in Eclipse)
To create a JAR file in Eclipse for our library packages like shapes, so they can be reused in
other projects:
We'll create a JAR file that contains: shapes.Circle , shapes.Square. Then, we’ll learn how
to use this JAR in another project.
Both classes should be public, and in the shapes package under the src folder.
161
Step 2: Export as JAR,
Right-click your project (e.g., PackageDemo),
• Click Export… Choose: Java → JAR file → Click Next.
• In the export window: Select only the shapes package,(since we're exporting
only the library)
• Tick: Export generated class files and resources
• Uncheck: Export Java source files (optional)
• Destination: Choose where to save your JAR file (e.g.,
C:\Users\You\Documents\shapes-lib.jar), Click Finish
import java.util.Scanner;
167
Standard Naming Conventions for Packages
1. All lowercase letters, Why?
Avoid conflicts with class names (which usually start with uppercase).
Good to write: shapes, utilities, myapp
2. Use your reversed domain name (for large projects) Especially in real-world
applications or libraries:
com.google.maps, org.apache.logging
- our package = com.ourname.projectname.module
4. Avoid using Java keywords or special characters. Package names can't contain symbols
like -, #, or start with numbers.
5. Be descriptive and specific. Name should reflect the purpose of the package.
math.operations, user.profile.details 168
Additional points about package:
• Package statement must be first statement in the program even before the
import statement.
• Store all the classes in that package folder.
• All classes of the package which we wish to access outside the package must be
declared public.
• All classes within the package must have the package statement as its first line.
• All classes of the package must be compiled before use.
169
To access package from another package:
There are three ways to access the package from outside the package :
a) import package.*;
b) import package.classname;
c) fully qualified name.
170
1) Using packagename.* : all classes and interfaces of this package are accessible but not subpackages.
The import k/w is used to make classes & interface of another package accessible to current package.
//save by A.java
package pack; Example:
public class A {
public void msg() { Output: Hello! I
System.out.println("Hello! I am from class A, package pack"); } }
am from class A,
//save by B.java package pack
package mypack;
import pack.*;
class B {
public static void main(String args[]) {
A obj = new A();
obj.msg();
} } 171
2) Using packagename.classname: only declared class of this package will be accessible.
Example:
//save by A.java
package pack;
public class A {
public void msg() {
System.out.println("Hello ! I am from class A, package pack"); } }
Output: Hello! I
//save by B.java am from class A,
package mypack; package pack
import pack.A;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
} }
172
3) Using fully qualified name
Only declared class of this package will be accessible. Now, import is not required.
Needed to use fully qualified name every time the class or interface are accessed.
- generally used when two packages have same class name e.g. java.util and java.sql
packages contain Date class.
Example: //save by A.java
package pack;
public class A {
public void msg() {
System.out.println(("Hello ! I am from class A, package pack");
} }
//save by B.java
package mypack;
class B {
public static void main(String args[]) {
pack.A obj = new pack.A(); //using fully qualified name
obj.msg();
} }
173
Subpackage in java
- On import of a package, all the classes and interface of that package will be imported
excluding the classes and interfaces of the subpackages.
Hence, needed to import the subpackage as well.
For example :
If I create a package inside letmecalculate package then that will be called sub package.
174
Lets say I have created another package inside letmecalculate and the sub package name is multiply.
So if I create a class in this subpackage it should have this package declaration in the beginning:
175