0% found this document useful (0 votes)
15 views

Java Unit 1 AKTU

The document provides a comprehensive overview of Object Oriented Programming with Java, covering topics such as Java's history, applications, platforms, and features. It discusses fundamental programming structures, object-oriented concepts, data types, variables, operators, and the Java environment including JDK, JRE, and JVM. Additionally, it includes examples and explanations of Java syntax, comments, and input handling using Scanner and BufferedReader.

Uploaded by

rajatmaurya7906
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Java Unit 1 AKTU

The document provides a comprehensive overview of Object Oriented Programming with Java, covering topics such as Java's history, applications, platforms, and features. It discusses fundamental programming structures, object-oriented concepts, data types, variables, operators, and the Java environment including JDK, JRE, and JVM. Additionally, it includes examples and explanations of Java syntax, comments, and input handling using Scanner and BufferedReader.

Uploaded by

rajatmaurya7906
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 163

BCS403: Object Oriented Programming with Java

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
 Introduction To Java

 History

 Applications

 Editions and Versions

 Features and Architecture


INTRODUCTION TO JAVA
• JAVA was developed by Sun Microsystems Inc in 1991, later acquired by Oracle
Corporation.
• It is a simple programming language.
• It helps to create reusable code and modular programs.
• made for developers to write once run anywhere ie. compiled Java code can run
on all platforms that support Java.

• Java applications are compiled to byte code that can run on any JVM.

• The syntax of Java is similar to c/c++.


HISTORY - FROM OAK TO JAVA
1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June 1991.

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.

7) JDK 1.0 released in(January 23, 1996)..


APPLICATIONS
1) Standalone Application
Also known as desktop applications or window-based applications.
These are traditional s/w that we need to install on every machine.
Examples: Media player, antivirus, etc. . AWT and Swing are used to create SAs
2) Web Application
An application that runs on the server side and creates a dynamic page.
Servlet, JSP, Struts, Spring, Hibernate, etc. technologies are used to create WAs
3) Enterprise Application
An application that is distributed in nature, such as banking applications, etc. It
has advantages of the high-level security, load balancing, and clustering.
EJB is used for creating enterprise applications.
4) Mobile Application
An application which is created for mobile devices
Currently, Android and Java ME are used to create MAs.
JAVA PLATFORMS / EDITIONS
1) Java SE (Java Standard Edition)-J2SE
It is a Java programming platform, includes Java programming APIs such as
java.lang, java.io, java.net, java.util, java.sql, java.math etc.

2) Java EE (Java Enterprise Edition)-J2EE


An enterprise platform,mainly used to develop web and enterprise applications.
It includes topics like Servlet, JSP, Web Services, EJB, JPA(Java Persistence API.),
etc.
3) Java ME (Java Micro Edition)-J2ME
It is a micro platform which is mainly used to develop mobile applications.

4) JavaFX
It is used to develop rich internet applications.
It uses a light-weight user interface API.
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
FEATURES OF JAVA
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
JAVA ARCHITECTURE
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

To compile: javac First.java


To execute: java First

Output:Hello Java Compilation Flow:


When we compile Java program using javac tool, java compiler
converts the source code into byte code.
JDK, JRE and JVM
JRE = JVM + libraries to run Java application.
JDK = JRE + tools to develop Java Application.

Java Development Kit (JDK)


A Kit which provides environment to develop & execute the Java program.
The kit includes two things:
-Development Tools(to provide an environment to develop java programs)
-JRE (to execute java program).

Java Virtual machine (JVM)


All code assigned to JVM is executed by an execution engine. The execution engine reads the byte code
and executes one by one. It uses two inbuilt interpreter and JIT compiler to convert the bytecode to
machine code and execute it.

Java Runtime Environment (JRE)


The (JRE) is a s/w package which bundles the libraries (jars) and the JVM,
and other components to run applications written in the Java.
To execute any Java application, JRE must be installed in the machine.
It’s the min. requirement to run(not develop) Java applications on any
computer.
 VARIABLES

 DATA TYPES

 OPERATORS

 KEYWORDS
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.
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.
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); }

public static void main(String[] args) {


VarEx obj = new VarEx();
System.out.println("Accessing Instance Variable using object: " + obj.instVar);
System.out.println("Accessing Static Variable using class name: " + VarEx.stVar);
obj.exampleMethod();
}
}
use of static variable
class stock{
public static int price= 100;
public st() {
price++;
System.out.println("Price for this share is=>>"+price);
}
}
public class stEx {
public static void main(String args[]) {
stock st1 = new stock();
System.out.println(st1.price);
stock st2 = new stock();
System.out.println(st2.price);
stock st3 = new stock();
System.out.println(st3.price);
} }
Constants in Java
• is a value that cannot be changed after assigning it.
• Defined by using the non-access modifiers static and final.
According to naming convention the identifier name must be in capital letters.
Example: static final double PRICE=432.78;
import java.util.Scanner;
public class ConstantEx {
private static final double PRICE=234.90;
public static void main(String[] args) {
Example: int unit;
double total_bill;
System.out.print("Enter the number of units you have used: ");
unit=12;
total_bill=PRICE*unit;
System.out.println("The total amount you have to deposit is: "+total_bill);
/*PRICE=10.21;
System.out.println("The total amount you have to deposit is: "+PRICE); “Give
error*/
} }
DATA TYPES
• Data types specify the different sizes and values that can be stored in the variable.
• Java is a statically-typed programming language. It means, all variables must be declared before
its use. That is why we need to declare variable's type & name.

There are two types of data types in Java:

1.Primitive data types: It include boolean, char, byte, short, int, long, float & double.

2.Non-primitive data types: It include Classes, Interfaces, and Arrays.


Data Types, Size, Minimum and Maximum Range along with Default Value

Byte Data Type


• used to save memory in large arrays
• It is 4 times smaller than an integer.
Short Data Type
Also be used to save memory
2 times smaller than an integer.

Example: Boolean one = false


Example: byte a = 10, byte b = -20
Example: short s = 10000, short r = -5000
Example: int a = 100000, int b = -200000
Example: float f1 = 234.5f
Example: long a = 100000L, long b = -200000L
Example: double d1 = 12.3
Example: char letterA = 'A'
OPERATORS
An operator is a symbol which is used to perform operations. For example: +, -, *, / etc.

Types of operators:
Operator Type Category Precedence

• Unary Operator, Unary postfix expr++ expr--


• Arithmetic Operator, prefix ++expr --expr +expr -expr ~ !
• Shift Operator,
Arithmetic multiplicative */%
• Relational Operator,
additive +-
• Bitwise Operator,
Shift shift << >>
• Logical Operator,
Relational comparison < > <= >=
• Ternary Operator and
• Assignment Operator. equality == !=
Bitwise bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
Logical logical AND &&
logical OR ||
Ternary ternary ?:
Assignment assignment = += -= *= /= %= &= ^= |= <<= >>=
Left Shift and Right Shift Operator
<< is used to shift all of the bits in a value to the left side of a specified number of times.
class OperatorExample
{
Example
public static void main(String args[])
{
System.out.println(10<<2); //10*2^2=10*4=40
System.out.println(10<<3); //10*2^3=10*8=80
System.out.println(20<<2); //20*2^2=20*4=80
System.out.println(15<<4); //15*2^4=15*16=240
}}

>> is used to move left operands value to right by the no. of bits specified by the right operand.

Example class OperatorExample


{
public static void main(String args[]){
System.out.println(10>>2); //10/2^2=10/4=2
System.out.println(20>>2); //20/2^2=20/4=5
System.out.println(20>>3); //20/2^3=20/8=2
} }
Relational Operator Example:

Example and Output:


class RelaOpr {
public static void main(String[] args) {
int a = 7, b = 11;
System.out.println("a is " + a + " and b is " + b);
System.out.println(a == b); // false
System.out.println(a != b); // true
System.out.println(a > b); // false
System.out.println(a < b); // true
System.out.println(a >= b); // false
System.out.println(a <= b); // true
}
}
Bitwise Operator

• Such operators are used to perform bit operations.


• All the decimal values will convert into binary values (sequence of bits i.e., 0100,
1100, 1000, 1001, etc.).
• The Java Bitwise Operators will work on these bits such as shifting them left to right
or converting bit value from 0 to 1 etc.
Bitwise &(AND) Operator Example:

Bitwise | (inclusive OR) Operator Example:


Bitwise ^(exclusive OR) Operator Example:

Example:

Ternary Operator • Used as one liner replacement for if-then-else statement.


• It is the only conditional operator which takes three operands.

class TrnyOpr {
public static void main(String[] args) {

int febDays = 29;


String result;

result = (febDays == 28) ? "Not a leap year" : "Leap year";


System.out.println(result);
}
}
KEYWORDS
• Also known as reserved words.
• Keywords are particular words which acts as a key to a code.
• These are predefined words by Java so it cannot be used as a variable or object name.
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(/* */)

Single Line Comment (//)

MultiLine Comment(/* */)


- used to comment multiple lines.
Example:

public class ComEx {


public static void main(String[] args)
{
int i=10; //Here, i is a variable
System.out.println(i);
/* Let's declare and
print variable in java. */
} }
Scanner and BufferedReader
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();

• Methods used by Scanner class(nextXXX()) : System.out.println("Enter an integer:");


int b = sc.nextInt();
Such as: nextInt(), nextFloat(), System.out.println("You have entered name as " + a);
nextByte(), nextShort(), nextDouble(),
nextLong(), next(). System.out.println("You have entered number as: " + b);
}}
BufferedReader
• java.io.BufferedReader class reads text from a character-input stream, buffering
characters so as to provide for the efficient reading of sequence of characters
• It reads characters from any input stream line.
• It can use readLine() to read data line by line.
import java.io.*;
class Differ { Output:
public static void main(String args[]) throws IOException { Enter an integer
BufferedReader br = new BufferedReader(new 12
InputStreamReader(System.in));
System.out.println("Enter an integer"); Enter a String
KIRAN
int a = Integer.parseInt(br.readLine());
System.out.println("Enter a String"); You have entered:-
String b = br.readLine(); 12 and name as KIRAN
System.out.printf("You have entered:-\n " + a +
" and name as " + b);
} }
Key differences between the Scanner and BufferedReader class :
Both BufferedReader and Scanner can read a file or user input from the command prompt, but
some significant differences between them are:

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.
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]);
}
}
# PARSE #

PARSE : It is a method which take a string(input) as an argument and convert in other formats as
like :

Integer
Float
Double

THE FUNCTIONS OF PARSE METHODS :


•ParseInt(); – It is a member function in Integer Class;
•ParseDouble(); – It is a member function in Double Class;
•ParseFloat(); – It is a member function in Float Class;
// 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
Arrays
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)

• Element type can be a primitive type or an object reference


Types of Array: Single Dimensional & Multidimensional Array
•Single Dimensional Array Instantiation:
Syntax to declare: arrayRefVar=new datatype[size];
1. dataType[] arr; (or)
2. dataType arr[];
//Declaration, instantiation & initialization of array in a single line
class Testarray{
public static void main(String args[]){
int a[]=new int[5]; class array1{
//declaration and instantiation
a[0]=10; //initialization public static void main(String args[]){
a[1]=20; int a[]={33,3,4,5};//declaration, instantiation and initialization
a[2]=70;
a[3]=40;
//printing array
a[4]=50; for(int i=0;i<a.length;i++)//length is the property of array
//traversing array System.out.println(a[i]);
for(int i=0;i<a.length;i++)//length is array’s
property }}
System.out.println(a[i]);
}}
MultiDimensional Array:
Data is stored in row & column based index (also known as matrix form).

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

//Example of multidimensional array


class Testarray3{
public static void main(String args[]){
int arr[][]={{1,2,3},{2,4,5},{4,4,5}}; //declaring and initializing 2D array

//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(); } }}
STRING HANDLING
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.

• In many other languages, a string is treated as a character array.


• But in Java, a string is treated as an object.
• After creating a string object we can not change it. So that is why it is said that a string is
immutable.
Note: Strings in Java are not primitive types (like int, char, etc). Instead, all strings are objects of a predefined class -> String.
And, all string variables are instances of the String class.
String Classes
• Java provides three string classes named: String, StringBuffer & StringBuilder.

• Both are mutable.

• The StringBuffer and StringBuilder classes have the same methods with one

difference and that's synchronization.

• A StringBuffer is synchronized (which means it is thread-safe and hence can

be used it when we implement threads for our methods) whereas

StringBuilder is not synchronized (which implies it isn't thread-safe).


String class
 String is represented by String class which is located into java.lang package.
 In java, every string that we create is actually an object of type String.
 String objects are immutable.i.e. once created, it can’t be changed.
 The Java String class implements Serializable, Comparable and CharSequence
interface that we have represented using the below image.

What is an Immutable object?


It is an object whose state cannot be changed after it is created.
String, Integer, Byte, Short, Float, Double and all other wrapper
classes objects are immutable.
Creating a String object

String is immutable. Whenever we change any string, a new instance is created.


There are two ways to create String object: 1. By string literal 2. By new keyword

1) Using a String literal public class Demo{


String literal is a simple string enclosed in double quotes " ". public static void main(String[] args)
A string literal is treated as a String object. { OP:
String s1 = "Hello Java"; Hello
System.out.println(s1); Java
} }

2) Using new Keyword public class Demo{


We can create a new string object by using new operator. public static void main(String[] args) {
It allocates memory for the object. String s1 = new String("Hello
Java");
System.out.println(s1);
}
}
OP:
Hello Java
Each time we create a String literal, the JVM checks the string pool first. If the string literal already exists in the pool, a
reference to the pool instance is returned. If string does not exist in the pool, a new string object is created, and is placed in
the pool. String objects are stored in a special memory area known as string constant pool inside the heap memory.
String object and How they are stored
(1) When we create a new string object using string literal,
that string literal is added to the string pool, if it is not present there
already.
String str= "Hello";
Creating String in heap :
(3) But if we change the new string, its reference gets
modified.
str2=str2.concat("world");

(2) And, when we create another object with same string,


then a reference of the string literal already present in string pool is
returned.
String str2 = str;
String class methods

• The java.lang.String class provides a lot of methods to work on string.

• By the help of these methods, we can perform operations on string such as trimming, concatenating,
converting, comparing, replacing strings etc.

Important methods of String class =>>


String Methods
(A) Concatenating String
There are 2 methods to concatenate two or more string.
(1) concat() method (2) Using + operator
Example:

1) Using concat() method public class Demo{


used to add two or more string into a single string public static void main(String[] args) { OP:
object. String s1 = "Hello"; HelloJava
String s2 = "Java";
2) Using + operator String s3 = s1.concat(s2);
"+" operator concatenate two string objects into single one. System.out.println(s3); } }
It can also concatenate numeric value with string object.
public class Demo{
public static void main(String[] args) {
Example: String s1= "Hello";
String s2 = "Java";
String s3 = s1+s2; OP:
String s4= "Java"+11; HelloJava
System.out.println(s3); Java11
System.out.println(s4); }
}
(B) String Comparison

3 ways:

1. Using equals() method


2. Using == operator
3. By CompareTo() method

(B-1) Using equals() method


compares two strings for equality. It compares the original content of the string.
String class provides two methods:

• public boolean equals(Object another) compares this string to the specified object.

• public boolean equalsIgnoreCase(String another) compares this String to another string,


ignoring case.
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
} }
(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)
} }

(B-3) By CompareTo() method


Compares the given string with current string lexicographically. It returns positive number, negative number or 0.
It compares strings on the basis of Unicode value of each character in the strings(lexicographically)
public class CompareToExample{
public static void main(String[] args) {
String s1 = "Abhi";
if s1 > s2, it returns positive number String s2 = "Vinny";
if s1 < s2, it returns negative number String s3 = "Abhi";
if s1 == s2, it returns 0 int a = s1.compareTo(s2); //return -21 because s1 < s2
System.out.println("s1.compareTo(s2)=>>"+a);
a = s1.compareTo(s3); //return 0 because s1 == s3
System.out.println("s1.compareTo(s3)=>>"+a);
a = s2.compareTo(s1); //return 21 because s2 > s1
System.out.println("s2.compareTo(s1)=>>"+a); } }
(C) Substring

A part of string is called substring or it is a subset of another string.


In case of string:
startIndex: inclusive
endIndex: exclusive
(Index starts from 0).

We can get substring from the given string object by one of the two methods:

(i) public String substring(int startIndex):


returns new String object containing the substring of the given string from specified startIndex (inclusive).
(ii) public String substring(int startIndex, int endIndex):
returns new String object containing the substring of the given string from specified startIndex to endIndex.

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
}
}
(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)
}
}
(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
} }

(G) join() method


returns a string joined with given delimiter. Delimiter is copied for each elements.
Example: public class Testjoin {
public static void main(String[] args)
{
String date = String.join("/", "30","09","2010");
System.out.print("Date is=>>"+date);
String time = String.join(":", “03",“10",“10");
System.out.println(".........Time is=>>" +time); } }
(H) charAt() method
returns a character at specified index.

Example: public class TestcharAt{


public static void main(String args[]){
String s="Abhineet";
System.out.println("Given String is=>"+s);
System.out.println("s.charAt(0)=>>"+s.charAt(0)); //A
System.out.println("s.charAt(4)=>>"+s.charAt(4)); //n
}
}

(I) length() method


The string length() method returns length of the string.

public class Testlength{


Example: public static void main(String args[]){
String s="Abhineet";
System.out.println("Given String is=>"+s);
System.out.println("s.length()=>>"+s.length()); //8
}
}
(J) valueOf() method
used to convert primitive data types into Strings.

Example: public class TestvalueOf{


public static void main(String args[]){
int num=10;
String s=String.valueOf(num);
System.out.println(s+10);
System.out.println("type of num is: "+s.getClass().getName());
} }
(K) replace() method
replaces all occurrence of first sequence of character with second sequence of character.
Example:
public class TestReplace
{
public static void main(String args[])
{
String s1="Java is a programming language. \nJava is platform-independent. \nJava is an Island.
System.out.println("Given String is->>\n"+s1);
System.out.println("-----replace String------\n");
String replaceString=s1.replace("Java","Zava"); //replaces all occurrences of "Java" to "Zava"
System.out.println(replaceString);
} }
(L) indexOf() method
returns index of given character value or substring. If it is not found, it returns -1. The index counter starts from zero.

Example:

public class Testindexof


{
public static void main(String args[])
{
String s1="this is index of example";
//passing substring
int i1=s1.indexOf("is"); //returns the index of is substring
int i2=s1.indexOf("index"); //returns the index of index substring
System.out.println("index1=>"+ i1+" "+"index2=>>"+i2); //2 8
//passing substring with from index
int i3=s1.indexOf("is",4); //returns the index of is substring after 4th index
System.out.println("index3=>>"+i3); //5 i.e. the index of another is
//passing char value
int i4=s1.indexOf('s’); //returns the index of s char value
System.out.println("index4=>>"+i4);//3
}
}
(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.

public class Testtochararray {


public static void main(String[] args) {
String s1 = "Welcome to Web Tech";
System.out.println("Given String is=>>"+s1);
char[] ch = s1.toCharArray();
int len = ch.length;
System.out.println("Char Array length: " + len);
System.out.println("Char Array elements: ");
for (int i = 0; i < len; i++) {
System.out.print(ch[i]+" ");
}
}
}
CLASS AND OBJECT
Classes and objects are the two main aspects of OOP

OOPs (Object-Oriented Programming System)


Object means a real-world entity such as a pen, chair, table, computer, watch, etc.
OOP is a methodology or paradigm to design a program using classes and objects. It simplifies s/w
development and maintenance by providing some concepts:
•Object
•Class
•Inheritance
•Polymorphism
•Abstraction
•Encapsulation
a) object
• An entity that has state and behavior is known as an object
e.g., chair, bike, marker, pen, table, car, etc.

• An object has three characteristics:

Example: Pen is an object. Its name is Rotomac; color is white,


known as its state. It is used to write, so writing is its behavior.

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.
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:

new keyword is used to allocate memory at runtime


Rules for Java Class

• A class can have only public or default access specifier.


• It can be either abstract, final or concrete (normal class).
• It must have the class keyword, and class must be followed by a legal identifier.
• It may optionally extend only one parent class. By default, it extends Object class.
• The variables and methods are declared within a set of curly braces.
• A Java class can contains fields, methods, constructors, and blocks.

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
}
}
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.

File: Student.java Output: 0


//Defining a Student class.
class Student{ null
int id; //field or data member or instance variable
String name;

public static void main(String args[]){


Student s1=new Student(); //Creating an object or instance

//Printing values of the object


System.out.println(s1.id); //accessing member through reference variable
System.out.println(s1.name);
}
}
Another Ex.

public class Student{

String name; int rollno; int age;


void info(){
System.out.println("Name: "+name);
System.out.println("Roll Number: "+rollno);
System.out.println("Age: "+age);
}
public static void main(String[] args) {
Student student = new Student();
student.name = "Ramesh";
student.rollno = 253; Output:
student.age = 25;
student.info(); Name: Ramesh
}} Roll Number: 253
Age: 25
METHODS
A method is a block of code grouped together to perform a certain task or operation.

• It is used to achieve the reusability of code.


• We write a method once and use it many times.
• It also provides the easy modification and readability of code
• The method is executed by its name and only when we call or invoke it.
• The most important method in Java is the main() method.
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

• Method Signature: includes the method name and parameter list.


• Access Specifier: specifies the visibility of the method
java has 4 access specifier: Public, Private, Protected, Default
• Return Type: a data type that a method returns, give void if it does not return anything.
• Method Name: a unique name to define name of a method.
• Parameter List: list of parameters separated by a comma and enclosed in the pair of ().
• Method Body: contains all the actions to be performed, enclosed within pair of {}
Types of Method
Types of methods: (1) Predefined Method (2) User-defined Method

(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.

• Each and every predefined method is defined inside a class.


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:

Maximum number is: 9


2. User-defined Method
Method written by the user or programmer. These methods are modified according to the requirement.

Ex: Create and call user defined method(findEvenOdd) that checks the number is even or odd:

import java.util.Scanner;
public class EvenOdd {

public static void findEvenOdd(int num) //user defined method Output 1:


{ Enter the number: 16
if(num%2==0)
System.out.println(num+" is even");
16 is even
else
System.out.println(num+" is odd"); Output 2:
} Enter the number: 11
11 is odd
public static void main (String args[]) {
Scanner scan=new Scanner(System.in); //creating Scanner class object
System.out.print("Enter the number: ");
int num=scan.nextInt(); //reading value from user
findEvenOdd(num); //method calling
}

}
Call by Value and Call by Reference in Java

There are two ways to pass an argument to a method

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.
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.)

public class CallByValueExample {


Example of call by value:
public static void main(String[] args) {
int x = 10;
System.out.println("Before calling method, x = " + x);
modifyValue(x);
System.out.println("After calling method, x = " + x);
}

public static void modifyValue(int num) {


num = num * 2;
System.out.println("Inside method, num = " + num);
}
}

Output: Before calling method, x = 10


Inside method,num=20;
After calling method, x = 10
Example: Call by Reference : changes are reflected
class Person {
String name="aru"; }

public class cbr {


public static void main(String[] args) {
Person person = new Person();
System.out.println("Before calling method, person.name = " + person.name);
modifyObject(person);
System.out.println("After calling method, person.name = " + person.name);
}

public static void modifyObject(Person p) {


p.name = "Alice";
System.out.println("Inside method, p.name = " + p.name);
}
}
Another Example: Call by Reference using an array:

public class cbr{


public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
System.out.println("Before calling method, numbers[0] = " + numbers[0]);
modifyArray(numbers);
System.out.println("After calling method, numbers[0] = " + numbers[0]);
}

public static void modifyArray(int[] arr) {


arr[0] = 100;
System.out.println("Inside method, arr[0] = " + arr[0]);
}
}
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.

• There are two different ways of method overloading.


• Different datatype of arguments
• Different number of arguments
(1) Method overloading by changing data type of arguments.
Example:
class Calculate {
void sum (int a, int b) {
System.out.println("sum is"+(a+b)) ;
}
void sum (float a, float b) {
System.out.println("sum is"+(a+b));
}
public static void main (String[] args)
{
Calculate cal = new Calculate();
cal.sum (8,5); //sum(int a, int b) is method is called.
cal.sum (4.6f, 3.8f); //sum(float a, float b) is called.
}
}
(2) Method overloading by changing no. of argument.
Example:
class Demo
{
void multiply(int l, int b)
{
System.out.println("Result is"+(l*b)) ;
}
void multiply(int l, int b,int h)
{
System.out.println("Result is"+(l*b*h));
}
public static void main(String[] args) {
Demo ar = new Demo();
ar.multiply(8,5); //multiply(int l, int b) is method is called
ar.multiply(4,6,2); //multiply(int l, int b,int h) is called
} }
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.

Example:we created three main() methods having different parameter types.


public class MethodDemo{
public static void main(int args) {
System.out.println("Main Method with int argument Executing");
System.out.println(args); }
public static void main(char args) {
System.out.println("Main Method with char argument Executing");
System.out.println(args); }
public static void main(double args) {
System.out.println("Main Method with Double Executing");
System.out.println(args); }
public static void main(String[] args) {
System.out.println("Original main Executing");
MethodDemo.main(12);
MethodDemo.main('c');
MethodDemo.main(12.36); } }
Static Members(ex: Fields, Methods)
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
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(); } }
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(); } }
Static block

• Used to initialize the static data member. Example 2:


• Executed before main method at the time of class loading. class Test {
• Also, static blocks are executed before constructors static int i; int j;
static {
public class Demo { i = 10;
Example 1: static int a; System.out.println("static block called ");
static int b; }
static { Test(){
a = 10; System.out.println("Constructor called"); }
b = 20; }
}
public static void main(String args[]) { class Demo {
public static void main(String args[]) {
System.out.println("Value of a = " + a); // Although we have two objects, static block is
System.out.println("Value of b = " + b); executed only once.
Test t1 = new Test();
} Test t2 = new Test();
} } }
Output:
Output:
static block
Value of a = 10
called
Value of b = 20
Constructor
Final Members(variable, method or
class)
• final keyword is used to denote constants. It can be
used with variables, methods, and classes.

• Once any entity (variable, method or class) is declared


final, it can be assigned only once. That is,
• the final variable cannot be reinitialized with another value
• the final method cannot be overridden
• the final class cannot be extended
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);
}
}
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."); }

public static void main(String[] args) {


Main obj = new Main();
obj.display(); } }
3) final Class
• the final class cannot be inherited by another class. For example,

// 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."); }

public static void main(String[] args) {


Main obj = new Main();
obj.display(); } }
Constructors
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.

• There are basically two rules defined for the constructor.

• Constructor name must be same as its class name

• Constructor must have no explicit return type

Types of java constructors: There are 2 types of constructors:

1. Default constructor / No-arg constructor) 2. Parameterized constructor


Default Constructor
A constructor that have no parameter is known as default constructor.
It will be invoked at the time of object creation.

class Book{
Example:
Book()
{
System.out.println("Book is published");
}
public static void main(String args[])
{
Book b=new Book();
}} Output: Book is published
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); }

public static void main(String args[])


{
AddDemo1 obj=new AddDemo1();
} }
Example of parameterized constructor

Constructor of Student class that have two parameters.


We can have any number of parameters in the constructor.
class Student{
int id; String name;

Student(int i, String n){


id = i; name = n;
}
void display(){
System.out.println(id+" "+name);}

public static void main(String args[]){


Student s1 = new Student(111,"Kiran");
Student s2 = new Student(222,"Avi");
s1.display();
s2.display(); } }
Constructor Overloading
A technique in which a class can have any number of constructors that differ in parameter lists.
Compiler differentiates these constructors by the number of parameters in the list & their type.

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);}

public static void main(String args[]){


Student s1 = new Student(111,"Kiran");
Student s2 = new Student(222,"Abhi",25);
s1.display(); s2.display(); }}
Constructor Chaining
• It is the process of calling one constructor from another constructor in the same class.
• To call constructor from another constructor this keyword is used.
• this keyword is used to refer current object.
class abc {
public abc() {
this(5);
System.out.println("Default Constructor"); }
public abc(int x) {
this(5, 6);
System.out.println("Constructor with one Parameter");
System.out.println("Value of x ==> "+x); }
public abc(int x, int y) {
System.out.println("Constructor with two Parameter");
System.out.println("Value of x and y ==> "+x+" "+y); } }

class ChainingDemo1 {
public static void main(String as[])
{
abc obj = new abc(); }}

** Used when we want to perform multiple tasks by creating a single object of the class.
Difference between constructor and method

Constructor Method

used to initialize the state of an object. used to expose behaviour of an object.

must not have return type. must have return type.

invoked implicitly. invoked explicitly.

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.
INHERITANCE IN JAVA
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:

1. For Method Overriding (so runtime polymorphism can be achieved).


2. For Code Reusability.
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.
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.
Types of Inheritance
1) Single Inheritance: One class inherits from one parent class. (One parent, one
children)

2) Multilevel inheritance: relationship where a class extends the child class.


For example class C extends class B and class B extends class A
(Grandparent → Parent → Child)

3) Hierarchical inheritance: more than one classes


extends the same class. For example, classes B & C
extends the same class A. (One parent, many children)

• In java, multiple & hybrid inheritance is supported through interface only.


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();
}
}
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 !!!”); }

public static void main(String[] args) {


C c = new C();
c.show();
c.display();
c.print() } }
Ex. of Hierarchical Inheritance
class A{
String bookname="Oracle";
void show() {
System.out.println(" Book Name = "+ bookname);
} }

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();
} }
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
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

public int getAge() { return age; }} } }


Polymorphism
"Poly" = many, "morph" = forms
In Java, Polymorphism means: One method behaves differently
based on the object that calls it.
Two Types:
Compile-Time Polymorphism → Method Overloading
Runtime Polymorphism → Method Overriding
(core concept in polymorphism-Dynamic method dispatch)

Dynamic Method Dispatch means: When a parent class reference


refers to a child class object, and overridden methods are called
— Java executes child’s method at runtime.
Example: Compile-Time Polymorphism (Method Overloading)
Same method name, but different parameters in same class
class Calculator {
void add(int a, int b) {
System.out.println("Sum: " + (a + b)); O/P:
}
Sum: 30
void add(double a, double b) {
System.out.println("Sum (double): " + (a + b));
Sum (double): 12.0
} }

public class Test {


public static void main(String[] args) {
Calculator c = new Calculator();
c.add(10, 20); // calls int version
c.add(5.5, 6.5); // calls double version
} }
Method Overriding
If subclass has the same method as declared in parent class, it is
method overriding.
Usage:
• to provide specific implementation of a method that is already
provided by its super class.
• used for runtime polymorphism

Rules for Java Method Overriding


1. method must have same name as in the parent class
2. method must have same parameter as in the parent class.
3. must be IS-A relationship (inheritance).
Example: Runtime Polymorphism (Method Overriding)
Basic Overriding : Create a class Animal with a method sound(). Then create a child class
Dog that overrides sound() to print "Dog barks".
If want to display methods of both parent and
class Animal {
child then use super kw as in the below lines:
void sound() {
System.out.println("Animal makes a sound");
} } class Dog extends Animal {
O/P: void sound() {
class Dog extends Animal { Dog barks super.sound();
void sound() { System.out.println("Dog barks");
System.out.println("Dog barks"); } }
} }
O/P:
public class Test {
Animal makes a sound
public static void main(String[] args) {
Dog d = new Dog(); Dog barks
d.sound(); // Calls Dog's version of sound()
} }
Dynamic Method Dispatch:(Overriding + Reference of Parent)
Use Animal as reference but create a Dog object. Call the sound() method.

class Animal {
void sound() {
System.out.println("Animal makes a sound"); } }

class Dog extends Animal {


void sound() {
System.out.println("Dog barks"); } }

public class Test {


public static void main(String[] args) {
Animal a = new Dog(); // Polymorphism in action
a.sound(); // Dog's sound() is called
} }
Reason: In Java, method calls are resolved at runtime (dynamic binding).
Benefits of Polymorphism
Code Reusability + Flexibility
Example:
There are many shapes: Circle, Square, Triangle This benefit of
All shapes have a method: area() polymorphism with
dynamic method dispatch
Now you can do this: can be further explored
using Abstract class and
Shape s1 = new Circle(); Interface also.
Shape s2 = new Square();
Shape s3 = new Triangle();

s1.area();
s2.area();
s3.area();

Benefit: You treat all objects the same (as Shape), but
they behave differently!
Key Difference:

Feature Method Overloading Method Overriding


Compile-time
Type Runtime Polymorphism
Polymorphism
Method
Must be different Must be same
Signature
Parent-child relationship
Class Location Same class
needed
Abstraction
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.

Abstraction is done using: a) abstract class b) interface


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.

Syntax: abstract class class_name { }


Abstract method

• Method declared without any body within an abstract class.


• The method body will be defined by its subclass.
• Abstract method can never be final and static.
• Any class that extends an abstract class must implement all the
abstract methods.

Syntax: abstract return_type function_name ();


Abstract Class and Method
1. Abstract classes are not Interfaces.
2.An abstract class may or may not have an abstract method.
3.But if any class has even a single abstract method, then it
must be declared abstract.
4.Abstract classes can have Constructors, Member variables
and Normal methods.
5.When Abstract class is extended with abstract method, we must define the
abstract method in the child class, or make the child class abstract.
Problem: Create a shape class with area calculation — but each shape (Circle, Rectangle)
will implement area in their own way.
Rectangle class
// Abstract class
class Rectangle extends Shape {
abstract class Shape {
void area() {
abstract void area(); // abstract method (no body)
int l = 10, b = 5;
}
int a = l * b;
Circle class System.out.println("Area of
Rectangle: " + a);
class Circle extends Shape { } }
void area() {
double r = 5;
double a = 3.14 * r * r;
System.out.println("Area of Circle: " + a);
}
}
Main class
Key Points to Remember:
public class Test {
public static void main(String[] args) {
Concept Meaning
Shape s;
Can't be used directly to create
abstract class
s = new Circle(); object
s.area(); // Circle's version abstract method No body, must be overridden
child class Must override abstract methods
s = new Rectangle();
s.area(); // Rectangle's version
}
}

Output:
Area of Circle: 78.5
Area of Rectangle: 50
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(); } }
INTERFACE
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.
}
• 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.

Relationship b/w classes & interfaces

A class extends another class, an interface


extends another interface,

but

a class implements an interface.0


Real-Life Concept: Payment System interface Payment {
Different payment methods like: void pay(double amount); // common method
Credit Card, UPI, PayPal }
All can be handled using a common interface: Payment.

A- Credit Card Class B- UPI Class


class UPI implements Payment {
class CreditCard implements Payment { public void pay(double amount) {
public void pay(double amount) { System.out.println("Paid ₹" +
System.out.println("Paid ₹" + amount + " amount + " using UPI.");
using Credit Card."); }
} } }

class PayPal implements Payment {


public void pay(double amount) {
C- PayPal Class
System.out.println("Paid ₹" + amount + " using PayPal.");
} }
Main Class:
Output:
public class Test {
Paid ₹500.0 using Credit Card.
public static void main(String[] args)
Paid ₹250.75 using UPI.
{ Paid ₹999.99 using PayPal.
Payment p;
1. Interface Payment is like a rule: everyone
p = new CreditCard(); must define the pay() method.
p.pay(500.00);
2. Each class (CreditCard, UPI, PayPal)
p = new UPI(); implements it differently.
p.pay(250.75);
3. The reference is polymorphic — behaves
p = new PayPal(); based on object.
p.pay(999.99);
} }
• Inheritance with Interface in Java — an important combo of
Abstraction + Inheritance.
• A class inherits from an interface using implements keyword.
• Interface = 100% Abstraction(Unlike abstract class which can have
both abstract + normal methods)

Benefits of Using Interface Inheritance:


• Supports multiple inheritance (Java doesn't support it with classes)
• Gives flexibility in large apps
• Allows you to decouple code (more organized)
• Interface = Structure without implementation that allows you to
build flexible and plug-and-play code
Interface Example: Bank
Example: implementation of Bank interface:
File: MyInterface.java
interface Bank{
float printROI(); }

class SBI implements Bank{


public float printROI(){
return 9.10f;} }

class BOB implements Bank{


public float printROI(){
return 8.15f;} }

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()); } }
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");}

public static void main(String args[]){


MyInterface obj = new MyInterface();
Output:
obj.print();
Hello
} }

emp and dept interface have same methods but its implementation is provided by
class MyInterface1, so there is no ambiguity.
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.
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.
Access Specifiers

Packages
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
Types of Access Specifiers in Java:

Modifier Where it can be accessed from


Accessible everywhere (same class, package,
public
outside package)
private Accessible only within the same class
Accessible in same package and by subclass
protected
outside
Accessible only in the same package (no keyword
(default)
used)
1. public Example

package mainapp;
package test; import test.A;

public class A { public class B {


public int x = 10; public static void main(String[] args) {
A obj = new A();
public void show() { System.out.println(obj.x); // public var
System.out.println("Public show() obj.show(); // public method
in A"); }
} }
}

Accessible in another package.


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.
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"); }
} }
}

Not accessible outside the package.


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();
}
}
}
}

protected works across packages but only via inheritance.


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.
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.
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.
Steps to Create a Package in Eclipse

Step 1: Create Java Project

File → New → Java Project-> Name it: PackageDemo-> Click Finish

Step 2: Create Packages

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

Step 3: Add a Class in shapes package

Class: Circle.java,-> Right-click on shapes → New → ClassName: Circle->


Paste this code:
package shapes; package mainapp;
public class Circle {
double radius; // Import the Circle class from shapes package

public Circle(double r) { import shapes.Circle;


radius = r;
} public class MainApp {
public void area() { public static void main(String[] args)
double result = Math.PI * radius * radius; {
System.out.println("Area of Circle = " + result); Circle c = new Circle(5.5);
} c.area();
} }}

Step 4: Add Main Class in mainapp package, Class: MainApp.java,


Right-click on mainapp → New → ClassName: MainApp-> Check
the box “public static void main” . Write this code:
• 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; }

public void area() {


double result = side * side;
System.out.println("Area of Square = " + result);
} }
Step 2: Update MainApp.java in mainapp package. Modify the existing MainApp.java
code like this:

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();
}}
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).

How Classpath Works for Packages in Eclipse


Example Project Structure:
Check/Verify Classpath in Eclipse:

To view or adjust classpath settings:

• Right-click project → Choose Build Path → Configure Build Path


• Go to the "Source" tab, Ensure that src/ is listed there as a source
folder,
• Go to the "Libraries" tab.

Here’s where you add external JARs (if needed), Click OK to close
Using External Packages or JARs or external Java libraries:

To use external Java libraries, you need to:

• Download the .jar file (e.g., mysql-connector.jar, log4j.jar, etc.)


• Right-click your project → Build Path → Configure Build Path
• Go to the Libraries tab → Click Add External JARs
• Select the .jar file → Click Apply and Close

Now your classpath includes that library, and you can use it in
your code.
Making jar files for library packages
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.

Step-by-Step: Create a JAR File in Eclipse

Step 1: Prepare the Code


Ensure shapes package has our classes: a) Circle.java b) Square.java

Both classes should be public, and in the shapes package under the src folder.
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, Leave mainapp or
MainApp.java unchecked (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

shapes-lib.jar file is now created


Step 3: Use the JAR in Another Project

• Create a new project: File → New → Java Project (e.g., name it JARUserApp)
• Create a new class with main()
• Add the JAR to Classpath: Right-click the project → Build Path → Configure Build
Path
• Click Libraries tab → Add External JARs-> Select shapes-lib.jar →
• Click Apply and Close
import shapes.Circle;
import shapes.Square; Output:
Code to Use the JAR: public class TestJAR { Area of Circle = 63.61725123519331
public static void main(String[] args) { Area of Square = 25.0
Circle c = new Circle(4.5);
c.area();
Square s = new Square(5);
s.area(); }}
What is import?
import is used to access classes or interfaces from other packages.
Syntax: import packageName.ClassName;
import java.util.Scanner;

public class Example1 {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in); // Using imported class
System.out.println("Enter your name: ");
String name = sc.nextLine();
System.out.println("Hello " + name);
}
}

Here, Scanner is in java.util, so we import it.


What is static import?
static import is used to access static members (methods or variables) of a class without
class name prefix.
Syntax: import static packageName.ClassName.staticMember;

Or:

import static packageName.ClassName.*; // to import all static members


public class MathExample {
Ex: Without static import: public static void main(String[] args) {
double r = Math.sqrt(25); // using class name Math
System.out.println("Square root = " + r);
} }

import static java.lang.Math.*;


public class MathExample {
Ex: With static import: public static void main(String[] args) {
double r = sqrt(25); // no need to write Math.sqrt
System.out.println("Square root = " + r);
}
}

sqrt() is a static method of Math, so we can use static import.


Feature import static import
Used for Classes/interfaces Static methods/variables
Example import java.util.Scanner; import static java.lang.Math.sqrt;
Prefix needed? Yes (Scanner sc = ...) No (sqrt(25))
Introduced in Java 1.0 Java 5

When to Use Static Import?

• When you're using many static methods (like Math.*, Collections.*)


• To improve readability (but don’t overuse—it can reduce clarity)
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
Not write : Shapes, 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


3. Separate words with dots. Use nested package structure to organize.
com.kanha.shapes, org.school.student.data

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

Why Follow This?

Due to following reasons:


• Clean and organized code
• Easy for teams to understand
• Avoids conflicts
• Industry-standard (used in all Java frameworks)
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.
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.
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();
} }
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();
} }
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();
} }
Subpackage in java

• Package inside the package is called the subpackage.


• Created to categorize the package further.

- 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.
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:

package letmecalculate.multiply;
// Save as Multiplication.java Now if I need to use this Multiplication class I have to
either import the package like this:
public class Multiplication
{ import letmecalculate.multiply;
int product(int a, int b){
or I can use fully qualified name like this:
return a*b;
}
} letmecalculate.multiply.Multiplication obj =
new letmecalculate.multiply.Multiplication();

You might also like