0% found this document useful (0 votes)
33 views23 pages

Oops 1

The document provides an introduction to Java, highlighting its features, applications, and history. It explains the Java Virtual Machine (JVM), Java Runtime Environment (JRE), and Java Development Kit (JDK), along with the structure of Java programs and key programming concepts such as classes, objects, and methods. Additionally, it covers the process of writing and compiling a simple Java program, including the importance of constructors and method definitions.

Uploaded by

Chaudhary Aviral
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)
33 views23 pages

Oops 1

The document provides an introduction to Java, highlighting its features, applications, and history. It explains the Java Virtual Machine (JVM), Java Runtime Environment (JRE), and Java Development Kit (JDK), along with the structure of Java programs and key programming concepts such as classes, objects, and methods. Additionally, it covers the process of writing and compiling a simple Java program, including the importance of constructors and method definitions.

Uploaded by

Chaudhary Aviral
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/ 23

Unit-1: Introduction

Friday, May 3, 2024 3:42 PM

"OOPS with Java"


Java
→ Java is a high Level programming language and it is also called as a platform. Java is a secured and
robust high level object-oriented programming language.
→ It was developed by James Gosling in 1991.
→ Platform: Any software or hardware environment in which a program runs is known as a platform.
Java has its own runtime environment (JRE) and API so java is also called as platform.
→ Java fallows the concept of Write Once, Run Anywhere.

Application of java

→ Desktop Applications
→ Web Applications
→ Mobile
→ Enterprise Applications
→ Smart Card
→ Embedded System
→ Games
→ Robotics etc

Features of Java

1. Simple
→ Java is very easy to learn and its syntax is simple, clean and easy to understand.
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}

2. Object-oriented
→ Java is object-oriented programming language

3. Platform Independent
→ Java is platform independent because it is different from other languages like C, C++ etc. which are
compiled into platform specific machines while Java is a write once, run anywhere language.

4. Secured
→ Java is best known for its security. With Java, we can develop virus-free systems.

5. Robust
→ Robust simply means strong.

6. Architecture-neutral
→ Java is architecture neutral because there is no implementation dependent features e.g. size of
primitive types is fixed. In C programming, int data type occupies 2 bytes of memory for 32-bit
architecture and 4 bytes of memory for 64-bit architecture. But in java, it occupies 4 bytes of
memory for both 32 and 64 bit architectures.

7. Portable J
→ Java is portable because it facilitates you to carry the java bytecode to any platform. It doesn't
require any type of implementation.

8. High-performance
→ Java is faster than other traditional interpreted programming languages because Java bytecode is
"close” to native code. It is still a little bit slower than a compiled language (e.g. C++). Java is an
interpreted language that is why it is slower than compiled languages e.g. C, C++ etc.

Unit-1 Page 1
9. Distributed
→ Java is distributed because it facilitates users to create distributed applications in java. RMI and EJB are
used for creating distributed applications. This feature of Java makes us able to access files by calling the
methods from any machine on the internet.

10. Multi-threaded
→ A thread is like a separate program, executing concurrently. We can write Java programs that deal with
many tasks at once by defining multiple threads. The main advantage of multi-threading is that it doesn't
occupy memory for each thread. It shares a common memory area. Threads are important for multi-
media, Web applications etc.

11. Dynamic
→ Java is a dynamic language. It supports dynamic loading of classes. It means classes are loaded on
demand. It also supports functions from its native languages i.e. C and C++. Java supports dynamic
compilation and automatic memory management (garbage collection).

History of Java

1) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language project in June
1991. The small team of sun engineers called Green Team at Sun Microsystem.
2) Initially it was 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. After that, it was
called Oak and was developed as a part of the Green project.
4) Why Oak? Oak is a symbol of strength and chosen as a national tree of many countries like the
U.S.A., France, Germany, Romania, etc.
5) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak Technologies.
6) Java is an island in Indonesia where the first coffee was produced (called Java coffee). Java name
was chosen by James Gosling while having a cup of coffee nearby his office.
7) Initially developed by James Gosling at Microsystems Sun (which is now a subsidiary of Oracle
Corporation) and released in 1995.
8) JDK 1.0 was released on January 23, 1996.

After the first release of Java, there have been many additional features added to the language.
Now Java is being used in Windows applications, Web applications, enterprise applications, mobile
applications, cards, etc. Each new version adds new features in Java.

JVM (Java Virtual Machine)

→ JVM (Java Virtual Machine) is an abstract machine.


→ It is a specification that provides runtime environment in which java bytecode can be executed.
→ JVMs are available for many hardware and software platforms (i.e. JVM is platform dependent).

# How does it work ?

→ When you write a Java program, the compiler


(JAVAC) converts it into byte code.
→ BYTECODE- Bytecode is like a secret language that
can understand only by JVM.
→ JVM takes this bytecode and execute it.
→ It will run Into any system in which IVM software is
present.

# What is good it for ?

Platform independent - You write code once, and the VM runs it on different platforms like window, mac or
Linux.
Safety first - The JVM checks for error before running code, preventing crash. When_you run a Java
program, you are actually saying, hey, VM, work your magic.

# operations

The JVM performs following operations:-


→ Loads code
→ Verifies codes
→ Executes code
→ Provide Runtime environment.

Unit-1 Page 2
JRE(Java Runtime Environment)

→ JRE is set of software tools which are used for


developing the java applications.
→ We can write it as JAVA RTE also.
→ JRE works with the help of JVM.
→ It contain set of libraries and other files that JVM
uses at run time.

# How does it work ?

→ JRE contain the JVM and set of libraries and some other files.
→ So its work like JVM

→ JRE = JVM + set of libraries + some other files

# What is it good for ?

Memory Management - It handles memory, garbage collection, and keeps things neat.
Speedy Execution - The JRE improves code for well-organized execution.
Platform independent - You write code once, and the JVM runs it on different platforms like window, mac or
Linux.
Safety first - the JVM checks for error before running code, preventing crash.

Java environment

→ Java environment includes large number of development tools The development tools are part of the
system known as Java development kit ( JDK).

JDK(Java Development Kit)

→ It is a software development environment which is used to develop and run Java programs.
→ It is a collection of tools.
→ That are used for developing.
→ It is physically exist.
→ And it contain JVM and JRE

→ JDK = JVM + JRE + DOVELOPEMENT TOOLS.

→ It works with the any one of the below java platform


○ Standard edition java platform
○ Enterprise edition java platform
○ Micro edition java platform

JDK includes:-

i. Applet Viewer (For Reviewing Java Applets)


ii. Java (Java Interpreter) (translator )
iii. Javac (Java Compiler)
iv. JavaP (Java Disassembler)
v. JavaH (lmport Files)
vi. Javadoc (Web Based Application)
vii. Jdb (Java Debugger)

Java Source File Structure

→ It is used to describe that the Java scores code file Must follow a structure., Java program Contain
exactly one public class.
→ The name of public class and name of program must match

Unit-1 Page 3
Structure of Java Program

1. Package Statements:
→ Package statement is like an address on a letter. And it is the first line in the source file. It tells to Java
program that where to find the classes and interfaces that are used in the code
→ Example: package com.example.myapp;

2. Import Statements:
→ It is like a shortcut that allow you to use Classes and methods form other libraries without having to
write their full names every time.
→ It is used to import classes, interfaces, or packages from other sources and allows you to use their
functionality in your code.
→ Example: import java.util.ArrayList;

3. Class Definition:
A class is a blueprint for creating objects.
It Contains variables and functions.
When we write a class definition in java, we are creating a detailed plan for how objects Will look and
function.
Example: public class MyClass
// variables and functions go here

Procedure to write simple JAVA Program

1. Install JDK - Before you run the java program you need to install JDK on your computer.

2. Setup your work space :-


a. Open a text editor like Notepad on Windows
b. Write your Java code in the editor.
c. Here’s an example of a simple “Hello, World!” program
public class HelloWorld{
public static void main(String [ ] args) {
System.out println('Hello, World!");
}
}

3. Save Your File -


a) Save the file with a .java extension, for example, HelloWorld,java
b) Make sure the file name matches the class name.

4. Compile Your Program —


a. Open the Command Prompt (cmd) on Windows
b. Navigate to the directory where your file is saved.
c. Compile the program using the Java compiler javac - javac HelloWorld.java

5. Run Your Program


a. After compilation, a .class file will be created.
b. Run the program using the Java command: java HelloWorld

6. See the Output


If everything is correct, you should see the output Hello, World! In the Command Prompt.

Unit-1 Page 4
A first Java Program

Class Keyword: It is used to declare a class in Java.

Public Keyword: It makes classes, attributes(variables), methods, available from anywhere in the program.

Static Keyword: It is a special tag that you can put on a variable and method to say "this belong to the class
itself, not to specific object."

Void: It is the return type of method. It means it does not return any value.

Main: It represents the starting point of the program.

String[] args: It is used for command line argument. It contains the value provided by the user when running
the program.

System.out.println(): It is used to print statement.

Compilation

A program is written in JAVA, the javac compiles it. The result of the JAVA compiler is the .class file or the
bytecode and not the machine native code (unlike C compiler).

The bytecode generated is a non-executable code and needs an interpreter to execute on a machine. This
interpreter is the JVM and thus the Bytecode is executed by the JVM. And finally program runs to give the
desired output.

Fundamentals of Java

Variables: Little boxes where you store information

Data Types: Tells you what kind of stuff you can put in the boxes like numbers or letters.

Operators: Symbols that let you do math or compare things.

Control Statements: Rules that tell the computer what to do next, like choosing which path to take.

Unit-1 Page 5
Methods: Sets of instructions that you can use over and over, like a recipe.

Classes: Blueprints for making objects that group data and methods together.

Objects: Things you create using classes that can do all sorts of tasks.

Programming Structures in Java


Class

a) It's like a blueprint for creating objects in java.


b) It tells the computer what properties (like size or color) and actions (like calculating or moving) the
objects should have.
c) A class is like a recipe for making objects.

Basic Syntax Of Class In Java

a) Class Declaration: You start with the class keyword followed


by the class name. The class name should start with an
uppercase letter.
b) Class Body: Inside the class, you define fields (variables) and
methods (functions). The body is enclosed in curly braces.
c) Fields: A field is like a storage box within a class where you
can keep data. It’s a variable (instance variable) that belongs
to a class, and you can use it to store values like numbers,
text, or any other type of data (int for numbers, string for
text etc.)
d) Methods: Method like a set of instruction. That you can use
over and over again. It's a block of codes. That does a
specific task. And you can run it whenever you need to by
calling its name. think of it like as a helper that takes a
particular job so you don’t have to write the same code
multiple times.
example:
class MyClass{
//Field
int_number;
// Method
void displayNumber() {
System.out println('Number: " + number);
}
}
public class Main {
public static void main(String[] args) {
// Creating an object of MyClass
MyClass obj = new MyClass();
// Accessing the field and method of MyClass using the object
obj.number = 10;
obj.displayNumber() ;
}
}

Types of Class

1. Predefined Classes: These are the classes that come with Java itself. They're part of Java’s libraries
and you can use them directly in your program. Examples include String, Math, and Array List.

2. User-Defined Classes: These are the classes user create by themselves. User write the code to define
what the class does and what kind of data it holds. Example: If you are making a game, you might
create a Player class with fields for the player's name, score and level.

Unit-1 Page 6
Constructors

In Java programming, a constructor is like a special method that helps create an object from a class. It's
called automatically when you use the new keyword to make a new object.

a) Initial Setup: It sets up the new object with initial values and states.
b) Automatic Call: It’s called automatically when you create an object.
c) No Return Type: It doesn’t return anything, not even void.
d) Same Name as Class: It has the same name as the class it’s in.

For example, if you have a class Bike, the constructor Bike() will set up a new bike object when you do
something like new Bike(). Here’s a simple code example:

class Bike {
int_speed;
// This is the constructor for the Bike class.
Bike() {
speed = 0;
// Setting the initial speed of the bike
}
}
public class TestBike {
public_static void main(String[] args) {
// Creating a new Bike object.
Bike myBike = new Bike();
System.out.println('Bike speed: " + myBike.speed);
}
}

In this code, Bike() is the constructor that sets the initial speed of the Bike object to 0. When we create a new
Bike with new Bike() the constructor is called, and the bike’s speed is set.

Types Of Constructor

1. Default Constructor: This is the constructor that doesn’t need any extra information. If you don’t write a
constructor for your class, Java automatically gives you this one. It's like getting a basic model of a car
with no extra options.

2. Parameterized Constructor: This constructor takes some information to work, like specific features you
want. It’s like ordering a car with your choice of color and engine type.

Rules for creating java constructors

a) Same Name: The constructor's name must be exactly the same as the class name
b) No Return Type: Constructors don’t have a return type, not even void.
c) Access Levels: You can use access modifiers like public, private, etc., to _control who can use the
constructor.
d) No Static: Constructors can’t be static. They are part of the object, not the class itself.
e) Overloading Allowed: You can have more than one constructor in a class as long as each has a different
set of parameters (this is called overloading).

Method

→ In Java programming, a method is a block of code that performs a specific task. It’s like a mini-program
within a program that you can run over and over. To create a method, you follow these steps:

1. Name Your Method: Choose a name that describes what the method does
2. Write Parameters: Decide what information, if any, the method needs to do its job.
3. Specify a Return Type: Determine what type of result the method will give back after it runs.
4. Add a Method Body: Write the code that will run each time the method is called.

Unit-1 Page 7
Syntax: Example:

public int add(int num1, int num2){


int sum=num1+num2;
return sum;
}

Access Modifier: This controls who can use the method. Common modifiers are public, private, or protected.
Return Type: This is the type of data the method will return. If it doesn’t return anything, use void
Method Name: This is the name you give your method.
Parameter Type: This is the type of data you're passing into the method.
Parameter Name: This is the name of the data you’re using inside the method. method body: This is where
you write the code that the method will execute.

Access Modifiers

Access modifiers in Java are like rules that tell who can use certain parts of your code. They're like the
privacy settings on your social media profile.

1. Private: The access level of a private modifier is only


within the class. It cannot be accessed from outside
the class.
2. Default: The access level of a default modifier is only
within the package. It cannot be accessed from outside
the package. If you do not specify any access level, it
will be the default.
3. Protected: The access level of a protected modifier is
within the package and outside the package through
child class. If you do not make the child class, it cannot
be accessed from outside the package.
4. Public: The access level of a public modifier is
everywhere. It can be accessed from within the class,
outside the class, within the package and outside the
package.

Let us understand access modifiers using the following table:-

Unit-1 Page 8
Static Members and Final Members

In Java, static members are those which belongs to the class and you can access these members without
instantiating the class.
The static keyword can be used with methods, fields, classes (inner/nested), blocks.

The final method in Java is used as a non-access modifier applicable only to a variable, a method, or a class.
It is used to restrict a user in Java.
The following are different contexts where the final is used:
1. Variable
2. Method
3. Class

Comments

→ The Java comments are the statements in a program that are not executed by the compiler and
interpreter.

Why do we use comments in a code?

→ Comments are used to make the program more readable by adding the details of the code.
→ It makes easy to maintain the code and to find the errors easily.
→ The comments can be used to provide information or explanation about the variable, method, class, or
any statement.
→ It can also be used to prevent the execution of program code while testing the alternative code.

Unit-1 Page 9
Data Types

→ Data types specify the different sizes and values that can be stored in the variable.
→ There are two types of data types in Java:

1. Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and
double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.

Variables

In Java, Variables are the data containers that save the data values during Java m program execution. Every
Variable in Java is assigned a data type that designates the type and quantity of value it can hold. A variable
is a memory location name for HRR Sy the data.

Java variable is a name given to a memory location. It is the basic unit of storage in a program.

○ The value stored in a variable can be changed during program execution.


○ Variables in Java are only a name given to a memory location. All the operations done on the variable
affect that memory location.
○ In Java, all variables must be declared before use.

Unit-1 Page 10
Operators

→ Operators in Java are the symbols used for performing specific operations in Java. Operators make
tasks like addition, multiplication, etc which look easy although the implementation of these tasks is
quite complex.

Types of Operators

1. Unary Operators: Unary operators need only one operand. They are used to increment, decrement, or
Logical not operator (!) negate a value.
○ Unary minus (-): It used to convert into a negative number
○ Unary plus (+): Tt used to convert into a positive number
○ Logical not operator (!)
○ Increment operator (++): It increments the value by 1.
○ Decrement operator (-): It decrements the value by 1.

2. Arithmetic Operators: They are used to perform simple arithmetic operations on primitive data types.

Output:

3. Assignment Operator: For assigning values

Unit-1 Page 11
4. Relational Operators: For comparing two 5. Logical Operators: For Combining Conditions
values

6. Ternary Operator: A shorthand for if-then-else


statements, using the syntax condition? if-true:
if-false

7. Bitwise Operators: Bitwise operators in Java


are used to perform operations on individual
bits of integer types. These operators work at
the binary level and are used for control the bit
patterns of the data types they are applied to.

8. Shift Operators: These operators are used to


shift the bits of a number left or right, thereby
multiplying or dividing the number by two,
respectively.

9. Instance of Operator: The instance of the operator is used for type checking. It can be used to test if
an object is an instance of a class, a subclass, or an interface.

Control Flow

→ Control flow in Java refers to the order in which the statements instructions, or function calls of a
program are executed or evaluated.
→ In simple terms, it's like the path your code follows based on certain conditions or loops you have set up.
Java provides various control flow statements that allow you to dictate how your program should run
under different conditions.

Decision-Making Statements:

1) If Statement: In Java, the "if" statement is used to evaluate a condition. The control of the program is
diverted depending upon the specific condition. The condition of the If statement gives a Boolean
value, either true or false.

1. Simple if statement 2. if-else-if ladder 3. if-else statement 4. Nested if-statement

Unit-1 Page 12
1) Simple if statement: It is the most basic statement among all control flow statements in Java. It evaluates a
Boolean expression and enables the program to enter a block of code if the expression evaluates to true.

Syntax:

Output:

2) If-else Statement: The if-else statement is an extension to the if-statement, which uses another
block of code, i.e., else block. The else block is executed if the condition of the if-block is evaluated as
false.

3) If-else-if ladder: The if-else-if statement contains the if-statement followed by multiple else-if
statements. In other words, we can say that it is the chain of if-else statements that create a decision
tree where the program may enter in the block of code where the condition is true. We can also define
an else statement at the end of the chain.

4) Nested if-statement: In nested if-statements, the if statement can contain a if or if-else statement
inside another if or else-if statement.

Unit-1 Page 13
Switch Statements

→ In Java, Switch statements are similar to if-else-if statements. The switch statement contains multiple
blocks of code called cases and a single case is executed based on the variable which is being switched.
The switch statement is easier to use instead of if-else-if statements. It also enhances the readability of
the program.

○ The case variables can be int, short, byte, char, or enumeration. String type is also supported since
version 7 of Java
○ Cases cannot be duplicate
○ Default statement is executed when any of the case doesn't match the value of expression. It is optional.
○ Break statement terminates the switch block when the condition is satisfied. It is optional, if not used,
next case is executed. o While using switch statements, we must notice that the case expression will be
of the same type as the variable. However, it will also be a constant value.

OUTPUT:- 2

Loop Statements

→ In programming, sometimes we need to execute the block of code repeatedly while some condition
evaluates to true. However, loop statements are used to execute the set of instructions in a repeated
order. The execution of the set of instructions depends upon a particular condition.
→ In Java, we have three types of loops that execute similarly. However, there are differences in their
syntax and condition checking time.
1. for loop
2. while loop
3. do-while loop

1. Java for loop : In Java, for loop is similar to C and C++. It enables us to initialize the loop variable, check the
condition, and increment/decrement in a single line of code. We use the for loop only when we exactly
know the number of times, we want to execute the block of code.

Unit-1 Page 14
2. While Loop: The while loop is also used to iterate over the number of
statements multiple times. However, if we don't know the number of
iterations in advance, it is recommended to use a while loop. Unlike
for loop, the initialization and increment/decrement doesn't take
place inside the loop statement in while loop.

It is also known as the entry-controlled loop since the condition is


checked at the start of the loop. If the condition is true, then the loop
body will be executed; otherwise, the statements after the loop will
be executed.

3. do-while loop: The do-while loop checks the condition at the end of the loop after executing the loop
statements. When the number of iteration is not known and we have to execute the loop at least once,
we can use do-while loop. It is also known as the exit-controlled loop since the condition is not
checked in advance.

Jump Statements

→ Jump statements are used to transfer the control of the program to the specific statements. In other
words, jump statements transfer the execution control to the other part of the program. There are two
types of jump statements in Java, i.e, break and continue.

Java break statement

→ As the name suggests, the break statement is used to break the current flow of the program and
transfer the control to the next statement outside a loop or switch statement.
→ However, it breaks only the inner loop in the case of the nested loop.
→ The break statement cannot be used independently in the Java program, i.e., it can only be written
inside the loop or switch statement.

Java continue statement

→ Unlike break statement, the continue statement doesn't break the loop, whereas, it skips the specific
part of the loop and jumps to the next iteration of the loop immediately

Unit-1 Page 15
Array

→ Array is a collection of similar type of elements that have contiguous memory


location.
→ Java array is an object that contains elements of similar data type.
→ It is a data structure where we store similar elements.
→ We can store only fixed set of elements in a java array.
→ Array in java is index based, first element of the array is stored at 0 index.
Advantage of Java Array
Code Optimization: It makes the code optimized, we can retrieve or sort the data
easily.
Random access: We can get any data located at any index position.
Disadvantage of Java Array
Size Limit: We can store only fixed size of elements in the array. It doesn't grow its
size at runtime. To solve this problem, collection framework is used in java

Types of Array:-

1) Single Dimensional Array


2) Multidimensional Array

Example: int[][] arr=new int[3][3];//3 row and 3 column


class Testarray{ Example to initialize Multidimensional Array in java
public static void main(String arr[0][0]=1;
args[]){
arr[0][1]=2;
int a[]=new int[5];
a[0]=10; Example:
a[1]=20; class Testarray3{
a[2]=70; public static void main(String args[]){
a[3]=40; //declaring and initializing 2D array

a[4]=50; int arr[][]={{1,2,3},{2,4,5},{4,4,5}};

for(int i=0;i<a.length;i++) //printing 2D array

System.out.println(a[i]); for(int i=0;i<3;i++){

}} for(int j=0;j<3;j++){
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}}
Java String

→ In Java, string is basically an object that represents sequence of char values. An array of
characters works same as Java string.
→ The java.lang.String class is used to create a string object.
→ For example:

→ Java String class provides a lot of methods to perform operations on strings such as compare(),
concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.

→ The java.lang.String class implements


○ Serializable, Comparable and CharSequence interfaces.

Unit-1 Page 16
→ There are two ways to create String object:

1. By string literal

2. By new Keyword

String Operations

1. equals(): System.out.println(s1.equals(s2));//true

2. compare by ==:
System.out.println(s1==s2);//true

3. compareTo():
s1 == s2 :0
s1 > s2 :positive value
s1 < s2 :negative value
System.out.println(s1.compareTo(s2));//0

4. Concat:
String s="Sachin"+" Tendulkar";
System.out.println(s);//Sachin Tendulkar

5. Split():
String[] words=s1.split(“ ");//splits the string based on whitespace

6. Ends with():
System.out.println(s1.endsWith("t"));

7. Substring() method
String s1="javatpoint";
System.out.println(s1.substring(2,4));//returns va

8. Join()
String joinString1=String.join("-","welcome","to","javatpoint");
System.out.println(joinString1);
}}
welcome-to-javatpoint

Unit-1 Page 17
Object Oriented Programming
Class

→ A Class is a template or blueprint for creating →


Objects; an Object is an Instance of a Class.

Java Classes:

1. Class is not a real-world entity. It is just a template or


blueprint or prototype from which objects are created.
2. Class does not occupy memory.
3. Class is a group of variables of different data types and a
group of methods.
4. A Class in Java can contain:
○ Data Member
○ Method
○ Constructor
○ Nested Class
○ Interface

Object In Java

An entity that has state and behavior is known as an object e.qg., chair, bike, pen, table, car,
etc. It can be physical or logical (tangible and intangible). The example of an intangible object is
the banking system

For Example, Pen is an object. Its name is Reynolds;


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.

Object Definitions:

○ An object is a real-world entity.


○ An object is a runtime entity
○ The object is an entity which has state and
behavior
○ The object is an instance of a class

Inheritance

→ Java, Inheritance is an important pillar of OOP. It is the mechanism in Java by which one class is
allowed to inherit the features(fields and methods) of another class.
→ In Java, Inheritance means creating new classes based on existing ones.
→ A class that inherits from another class can reuse the methods and fields of that class.
→ In addition, you can add new fields and methods to your current class as well.

Why Do We Need Java Inheritance? Important Terminologies Used in Java Inheritance

○ Code Reusability Super Class/Parent Class: The class whose features are
○ Method Overriding inherited is known as a superclass(or a base class or a parent
○ Abstraction class).

Sub Class/Child Class: The class that inherits the other class
is known as a subclass(or a derived class, extended class, or
child class). The subclass can add its own fields and methods
in addition to the superclass fields and methods.

Unit-1 Page 18
How to Use Inheritance in Java?

The extends keyword is used for inheritance in Java. Using the extends keyword indicates you are derived
from an existing class. In other words, “extends” refers to increased functionality.

Syntax:

Types of inheritance in java

→ On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.

→ In java programming, multiple and hybrid inheritance is supported through interface only. We will learn
about interfaces later.

1. Single Inheritance
→ In single inheritance, subclasses inherit the features of
one superclass. In the image below, class A serves as a
base class for the derived class B.

2. Multilevel Inheritance
→ In Multilevel Inheritance, a derived class will be inheriting
a base class, and as well as the derived class also acts as
the base class for other classes.

3. Hierarchical Inheritance
→ In Hierarchical Inheritance, one class serves as a superclass
(base class) for more than one subclass. In the below image,
class A serves as a base class for the derived classes B, C,
and D.

4. Multiple Inheritance (Through Interfaces)


→ In Multiple inheritances, one class can have more than one
superclass and inherit features from all parent classes.
Please note that Java does not support multiple
inheritances with classes.

5. Hybrid Inheritance
→ It is a mix of two or more of the above types of inheritance. Since
Java doesn’t support multiple inheritances with classes, hybrid
inheritance involving multiple inheritance is also not possible with
classes. In Java, we can achieve hybrid inheritance only
through Interfaces if we want to involve multiple inheritance to
implement Hybrid inheritance.

Unit-1 Page 19
Overloading and Overriding

Overloading: Overloading occurs when two or more methods in the same class have the same
name but different parameters. Method overloading is also called compile-time polymorphism,
static polymorphism, or early binding. In Method overloading, the child argument takes
precedence over the parent argument.

Overriding: Method overriding Is the act of declaring a method In a subclass that Is already
present in a parent class.
When two or more methods in the same class have the same method name but different
parameters, this is called overloading. In contrast, overriding occurs when two methods have
the same name and parameters

Encapsulation in Java

→ Encapsulation in Java is a fundamental concept in object-oriented


programming (OOP) that refers to the bundling of data and methods that
operate on that data within a single unit, which is called a class in Java. Java
Encapsulation is a way of hiding the implementation details of a class from
outside access and only exposing a public interface that can be used to
interact with the class.

→ Encapsulation in Java is a process of wrapping code and data together into a single unit, for example, a
capsule which is mixed of several medicines.

→ Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism that binds
together code and the data it manipulates.
→ Another way to think about encapsulation is, that it is a protective shield that prevents the data from
being accessed by the code outside this shield.
→ Encapsulation can be achieved by Declaring all the variables in the class as private and writing public
methods in the class to set and get the values of variables.
→ It is more defined with the setter and getter method.

Advantages Disadvantages

1. Data Hiding 1. Can lead to increased complexity, especially if not used


2. Code Reusability properly.
3. Getter and Setter Methods 2. Can make it more difficult to understand how the system
4. Total Control works.
5. Flexibility and Maintainability 3. May limit the flexibility of the implementation.
6. Ease of Testing

Polymorphism

→ The word polymorphism means having many forms. In simple words, we “can define Java
Polymorphism as the ability of a message to be displayed in more than one form.

Real-life Illustration of Polymorphism in Java: A person at the same time can have different characteristics.
Like a man at the same time is a father, a husband, and an employee. So the same person possesses
different behaviors in different situations. This is called polymorphism.

Unit-1 Page 20
What is Polymorphism in Java?

→ Polymorphism is considered one of the important features of Object-Oriented Programming.


→ Polymorphism allows us to perform a single action in different ways.
→ In other words, polymorphism allows you to define one interface and have multiple implementations.
→ The word “poly” means many and “morphs” means forms, So it means many forms.

Advantages of Polymorphism in Java

1. Increases code reusability by allowing objects of different classes to be treated as objects of a common
class.
2. Improves readability and maintainability of code by reducing the amount of code that needs to be written
and maintained.
3. Supports dynamic binding, enabling the correct method to be called at runtime, based on the actual class
of the object.
4. Enables objects to be treated as a single type, making it easier to write generic code that can handle
objects of different types.

Disadvantages

1. Can make it more difficult to understand the behavior of an object, especially if the code is complex.
2. This may lead to performance issues, as polymorphic behavior may require additional computations at
runtime.

Abstraction

→ Abstraction in Java is the process in which we only show essential details/functionality to the user. The
non-essential implementation details are not displayed to the user.
→ In Java, abstraction is achieved by interfaces and abstract classes. We can achieve 100% abstraction
using interfaces.
→ Data Abstraction may also be defined as the process of identifying only the required characteristics of
an object ignoring the irrelevant details. The properties and behaviours of an object differentiate it from
other objects of similar type and also help in classifying/grouping the objects.

Java Abstract classes and Java Abstract methods

1. An abstract class is a class that is declared with an abstract keyword.


2. An abstract method is a method that is declared without implementation.
3. An abstract class may or may not have all abstract methods. Some of them can be concrete methods.
4. A method-defined abstract must always be redefined in the subclass, thus making overriding
compulsory or making the subclass itself abstract.

Interfaces Syntax:

The interface in Java is to achieve abstraction. There can be only


abstract methods in the Java interface, not the method body. It is
used to interface and multiple inheritances in Java using Interface.
In other words, you can say that interfaces can have abstract
methods and variables. It cannot have a method body. Java
Interface also represents the IS-A relationship.

Unit-1 Page 21
How to declare an Interface?

→ An interface is declared by using the interface keyword. It provides total abstraction; means all the
methods in an interface are declared with the empty body, and all the fields are public, static and final by
default. A class that implements an interface must implement all the methods declared in the interface.

Abstract Class

→ Abstract classes are classes that contain one or more abstract methods(methods without body)
→ Abstract class is declared with abstract modifier.
→ Abstract class can contain concrete methods as well.
→ Concrete methods are complete methods with method heading and body.

Packages
→ Package in Java is a mechanism to encapsulate a group of classes, sub packages and interfaces.
→ Packages are used for:

1. Preventing naming conflicts. For example there can be two classes with name Employee in two
packages, college.staff.cse.Employee and college.staff.ee.Employee
2. Making searching/locating and usage of classes, interfaces, enumerations and annotations easier
3. Providing controlled access: protected and default have package level access control. A protected
member is accessible by classes in the same package and its subclasses. A default member (without
any access specifier) is accessible by classes in the same package only.
4. Packages can be considered as data encapsulation (or data-hiding).

Classpath in Java

CLASSPATH describes the location where all the required files are available which are used in the application.
Java Compiler and JVM (Java Virtual Machine)_use CLASSPATH to locate the required files. If the CLASSPATH
is not set, Java Compiler will not be able to find the required files and hence will throw the following error.

Note:
The above error is resolved when CLASSPATH is set.
Semi-colon(;) is used as a seperator
Set the CLASSPATH in JAVA in Windows
dot(.) is the default value of classpath.

Unit-1 Page 22
Command Line: Find out where you have installed Java, basically, it's in /usr/lib/jvm path. Set the
CLASSPATH in /etc/environment using

JAR Files in Java

→ A JAR (Java Archive) is a package file format typically used to aggregate many Java class files and
associated metadata and resources (text, images, etc.) into one file to distribute application software or
libraries on the Java platform.
→ In simple words, a JAR file is a file that contains a compressed version of .class files, audio files, image
files, or directories.
→ We can imagine a .jar file as a zipped file(.zip) that is created by using WinZip software. Even, WinZip
software can be used to extract the contents of a .jar .
→ So you can use them for tasks such as lossless data compression, archiving, decompression, and
archive unpacking.

1.1 Create a JAR file


In order to create a .jar file, we can use jar cf command in the following ways as discussed below:

Syntax:

Here, cf represents to create the file. For example , assuming our package pack is available in C:\directory , to
convert it into a jar file into the pack.jar , we can give the command as:

1. 2 View a JAR file


1.3 Extracting a JAR file
1.4 Updating a JAR File
1.5 Running a JAR file

Package Naming Conversion in Java

→ In Java, package plays an important role in preventing naming conflicts, controlling access, and making
searching and usage of classes, enumeration, interfaces, and annotation easier.

Naming Conventions

→ For avoiding unwanted package names, we have some following naming conventions which we use in
creating a package.
○ The name should always be in the lower case.
○ They should be period-delimited.
○ The names should be based on the company or organization name

→ In order to define a package name based on an organization, we'll first reverse the company URL. After
that, we define it by the company and include division names and project names.

Static import in Java

→ In Java, static import concept is introduced in 1.5 version. With the help of static import, we can access
the static members of a class directly without class name or any object.
→ For Ex: we always use sqrt() method of Math class by using Math class i.e. Math.sqrt(), but by using static
import we can access sqrt() method directly. According to SUN microSystem, it will improve the code
readability and enhance coding. But according to the programming experts, it will lead to confusion and
not good for programming. If there is no specific requirement then we should not go for static import.

Advantage: Disadvantage

If user wants to access any static member Static import makes the program
of class then less coding is required. unreadable and unmaintainable if you are
reusing this feature.

Unit-1 Page 23

You might also like