0% found this document useful (0 votes)
5 views28 pages

Unit II

This document provides an overview of Object-Oriented Programming (OOP) concepts, including classes, objects, encapsulation, inheritance, and polymorphism, emphasizing their importance in programming. It also discusses Java as a high-level, object-oriented language, highlighting its features such as platform independence, simplicity, and rich standard libraries. Additionally, it covers Java's data types, including primitive and non-primitive types, and provides examples to illustrate these concepts.

Uploaded by

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

Unit II

This document provides an overview of Object-Oriented Programming (OOP) concepts, including classes, objects, encapsulation, inheritance, and polymorphism, emphasizing their importance in programming. It also discusses Java as a high-level, object-oriented language, highlighting its features such as platform independence, simplicity, and rich standard libraries. Additionally, it covers Java's data types, including primitive and non-primitive types, and provides examples to illustrate these concepts.

Uploaded by

ashwini.khade005
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Unit II: - JAVA

Introduction of Object-Oriented Programming


As the name suggests, Object-Oriented Programming or OOPs refers to languages that use
objects in programming. Object-oriented programming aims to implement real-world entities
like inheritance, hiding, polymorphism, etc in programming. The main aim of OOP is to bind
together the data and the functions that operate on them so that no other part of the code can
access this data except that function.
OOPs Concepts:
 Class
 Objects
 Data Abstraction
 Encapsulation
 Inheritance
 Polymorphism
 Dynamic Binding
 Message Passing
1. Class:
A class is a user-defined data type. It consists of data members and member functions, which can
be accessed and used by creating an instance of that class. It represents the set of properties or
methods that are common to all objects of one type. A class is like a blueprint for an object.
For Example: Consider the Class of Cars. There may be many cars with different names and
brands but all of them will share some common properties like all of them will have 4 wheels,
Speed Limit, Mileage range, etc. So here, Car is the class, and wheels, speed limits, mileage are
their properties.
2. Object:
It is a basic unit of Object-Oriented Programming and represents the real-life entities. An Object
is an instance of a Class. When a class is defined, no memory is allocated but when it is
instantiated (i.e. an object is created) memory is allocated. An object has an identity, state, and
behavior. Each object contains data and code to manipulate the data. Objects can interact without
having to know details of each other’s data or code, it is sufficient to know the type of message
accepted and type of response returned by the objects.
For example “Dog” is a real-life Object, which has some characteristics like color, Breed, Bark,
Sleep, and Eats.
3. Data Abstraction:
Data abstraction is one of the most essential and important features of object-oriented
programming. Data abstraction refers to providing only essential information about the data to
the outside world, hiding the background details or implementation. Consider a real-life example
of a man driving a car. The man only knows that pressing the accelerators will increase the speed
of the car or applying brakes will stop the car, but he does not know about how on pressing the
accelerator the speed is increasing, he does not know about the inner mechanism of the car or the
implementation of the accelerator, brakes, etc in the car. This is what abstraction is.
4. Encapsulation:
Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism that
binds together code and the data it manipulates. In Encapsulation, the variables or data of a class
are hidden from any other class and can be accessed only through any member function of their
class in which they are declared. As in encapsulation, the data in a class is hidden from other
classes, so it is also known as data-hiding.
Encapsulation can be understood with a company example.
In a company, departments like Finance and Sales manage their own data and activities.
The Finance department cannot directly access Sales data.
It must request the required information through an authorized person in Sales.
Thus, data and the people handling it are bundled together under one section, which represents
encapsulation.
5. Inheritance:
Inheritance is an important pillar of OOP(Object-Oriented Programming). The capability of a
class to derive properties and characteristics from another class is called Inheritance. When we
write a class, we inherit properties from other classes. So when we create a class, we do not need
to write all the properties and functions again and again, as these can be inherited from another
class that possesses it. Inheritance allows the user to reuse the code whenever possible and
reduce its redundancy.

6. Polymorphism:
The word polymorphism means having many forms. In simple words, we can define
polymorphism as the ability of a message to be displayed in more than one form. For example, A
person at the same time can have different characteristics. Like a man at the same time is a
father, a husband, an employee. So the same person posses different behavior in different
situations. This is called polymorphism.

7. Dynamic Binding:
In dynamic binding, the code to be executed in response to the function call is decided at
runtime. Dynamic binding means that the code associated with a given procedure call is not
known until the time of the call at run time. Dynamic Method Binding One of the main
advantages of inheritance is that some derived class D has all the members of its base class B.
Once D is not hiding any of the public members of B, then an object of D can represent B in any
context where a B could be used. This feature is known as subtype polymorphism.
8. Message Passing:
It is a form of communication used in object-oriented programming as well as parallel
programming. Objects communicate with one another by sending and receiving information to
each other. A message for an object is a request for execution of a procedure and therefore will
invoke a function in the receiving object that generates the desired results. Message passing
involves specifying the name of the object, the name of the function, and the information to be
sent.
Why do we need object-oriented programming
 To make the development and maintenance of projects more effortless.
 To provide the feature of data hiding that is good for security concerns.
 We can solve real-world problems if we are using object-oriented programming.
 It ensures code reusability.
 It lets us write generic code: which will work with a range of data, so we don't have to
write basic stuff over and over again.
Java is a high-level, object-oriented programming language. This language is very easy to learn
and widely used. It is known for its platform independence, reliability, and security. It follows
one principle, that is "Write Once, Run Anywhere" principle. It supports various features like
portability, robustness, simplicity, multithreading, and high performance, which makes it a
popular choice for beginners as well as for developers.
In this article, we are going to discuss the important features of Java programming language.
Features in Java
1. Simple Syntax
Java syntax is very straightforward and very easy to learn. Java removes complex features like
pointers and multiple inheritance, which makes it a good choice for beginners.
Example: Basic Java Program
// Java program to Demonstrate the Basic Syntax
import [Link].*;
class datascience {
public static void main(String[] args)
{
[Link]("SYBSC Data Science!");
}
}
Output
SYBSC Data Science!
Explanation: In Java, the execution starts from the main() method, which is the entry point of
every Java program. The class named datascience contains the main method. The statement
[Link]("SYBSC Data Science!"); is used to display the message on the screen.
The statement import [Link].*; is used to import input-output related classes from the [Link]
package.
2. Object Oriented
Java is a pure object-oriented language. It supports core OOP concepts like,
 Class
 Objects
 Inheritance
 Encapsulation
 Abstraction
 Polymorphism
Example: The below Java program demonstrates the basic concepts of OOPs.
// Java program to demonstrate the basic concepts of oops
// like class, object, Constructor and method
import [Link].*;

class Student {
int age;
String name;
public Student(int age, String name)
{
[Link] = age;
[Link] = name;
}

// This method display the details of the student


void display()
{
[Link]("Name is: " + name);
[Link]("Age is: " + age);
}
}

class Geeks {
public static void main(String[] args)
{
Student student = new Student(22, "GFG");
[Link]();
}
}
Output
Name is: GFG
Age is: 22
Explanation: In the above example, we have created a Student class and inside the class we
have declared two variables age and name. A constructor is used to initialize these variables
when an object of the Student class is created. In the main method we are creating an object of
the student class and then we are calling the display method which is prinitng the name and age
on the console.
3. Platform Independent
Java is platform-independent because of Java Virtual Machine (JVM).
 When we write Java code, it is first compiled by the compiler and then converted into
bytecode (which is platform-independent).
 This byte code can run on any platform which has JVM installed.
4. Interpreted
Java code is not directly executed by the computer. It is first compiled into bytecode. This byte
code is then understand by the JVM. This enables Java to run on any platform without rewriting
code.
5. Scalable
Java can handle both small and large-scale applications. Java provides features
like multithreading and distributed computing that allows developers to manage loads more
easily.
6. Portable
When we write a Java program, the code first get converted into bytecode and this bytecode does
not depend on any operating system or any specific computer. We can simply execute this
bytecode on any platform with the help of JVM. Since JVMs are available on most devices and
that's why we can run the same Java program on different platform
7. Secured and Robust
Java is a reliable programming language because it can catch mistakes early while writing the
code and also keeps checking for errors when the program is running. It also has a feature
called exception handling that helps deal with unexpected problems smoothly.
8. Memory Management
Memory management in Java is automatically handled by the Java Virtual Machine (JVM).
 Java garbage collector reclaim memory from objects that are no longer needed.
 Memory for objects are allocated in the heap
 Method calls and local variables are stored in the stack.
9. High Performance
Java is faster than old interpreted languages. Java program is first converted into bytecode which
is faster than interpreted code. It is slower than fully compiled languages like C or C++ because
of interpretation and JIT compilation process. Java performance is improve with the help of Just-
In-Time (JIT) compilation, which makes it faster than many interpreted languages but not as fast
as fully compiled languages.
10. Multithreading
Multithreading in Java allows multiple threads to run at the same time.
 It improves CPU utilization and enhancing performance in applications that require
concurrent task execution.
 Multithreading is especially important for interactive and high-performance applications,
such as games and real-time systems.
 Java provides build in support for managing multiple threads. A thread is known as the
smallest unit of execution within a process.
Example: Basic Multithreadig in Java
// Java program to demonstrate multithreading
class MyThread extends Thread {

public void run() {

[Link]("Thread is running...");
}
}

public class Geeks {


public static void main(String[] args) {
MyThread thread = new MyThread();

// Starts the thread


[Link]();
}
}

Output
Thread is running...
Explanation: The MyThread class extends the Thread class and overrides the run method. In the
main method, an object of MyThread is created, and the start method is called to begin the
execution of the thread. The run method is executed in a separate thread, printing "Thread is
running..." to the console.
11. Rich Standard Library
Java provides various pre-built tools and libraries which is known as Java API. Java API is used
to cover tasks like file handling, networking, database connectivity (JDBC), security, etc. With
the help of these libraries developers save a lot of time and ready to use solutions and can also
build a powerful application.
12. Functional Programming Features
Since Java 8, the language has introduced functional programming features such as:
 lambda expression let us to write small block of code in a very easy way without creating
full methods.
 Stream API allows data to be processed easily, Instead of writing long loops we can just
filter, change, or combine data in a few lines.
 Functional interfaces are inteface that contains only one method. They work perfectly
with lambda expressions and help us write flexible and reusable code.
Example:
// Java program demonstrating lambda expressions
interface Lambda {

int operate(int a, int b);


}

public class Geeks {

public static void main(String[] args) {

// Lambda expression
Lambda add = (a, b) -> a + b;
[Link]("Addition: " + [Link](2, 3));
}
}

Output
Addition: 5
Explanation: A functional interface Lambda is defined with a single method operate. A lambda
expression (a, b) -> a + b is used to implement the operate method. The main method calls the
operate method using the lambda expression and prints the result.
13. Integration with Other Technologies
Java can easily work with many languages and tools as well. For example, Java can connect with
C and C++ with the help of Java Native Interface (JNI). Java is very popular for
building websites and webservices like RESTful & SOAP. In Java we can use JDBC for
database connectivity also Java is the main language for android development. As we can see
Java works so well with so many different technologies that's the reason developer prefers Java
more to create scalable and powerful application.
14. Support for Mobile and Web Application
Java offers support for both web and mobile applications.
 For web development: Java offers technologies like JSP and Servlets, along with
frameworks like Spring and Springboot, which makes it easier to build web applications.
 For mobile development: Java is the main language for Android app development. The
Android SDK uses special version of Java and its various tools to build mobile apps for
Android devices.
15. Documentation and Community Support
Java provide documentation which includes guides, API references, and tutorials for easy
learning. Java has a large and active global community contributing to open-source projects,
and resources. This community support helps developers solve problems and stay updated with
new advancements.
Java Data Types
Java is a statically typed programming language, which means the data type of every variable is
known at compile time. The compiler enforces type safety and prevents invalid assignments such
as:
int x = "GfG"; // Compile-time error
Data types in Java define the kind of data a variable can hold and the memory required to store it.
They are broadly divided into two categories:
 Primitive Data Types: Store simple values directly in memory.
 Non-Primitive (Reference) Data Types: Store memory references to objects.
Data Types in Java
Primitive Data Types
Primitive data types store simple values directly in memory. Java provides eight primitive data
types, each with a fixed size and range, which are summarized below:

Type Description Default Size Example Range

Not JVM-
Logical values false true, false true or false
boolean defined

8-bit signed
0 1 byte 10 -128 to 127
byte integer
Type Description Default Size Example Range

16-bit Unicode
\u0000 2 bytes 'A', '\u0041' 0 to 65,535
char character

16-bit signed
0 2 bytes 2000 -32,768 to 32,767
short integer

32-bit signed -2,147,483,648 to


0 4 bytes 1000, -500
int integer 2,147,483,647

64-bit signed
0L 8 bytes 123456789L ±9.22e18
long integer

32-bit floating
0.0f 4 bytes 3.14f ~6–7 digits precision
float point

64-bit floating ~15–16 digits


0.0d 8 bytes 3.14159d
double point precision

1. boolean Data Type


Represents one of two logical values: true or false. It is commonly used in conditions and control
statements.
Syntax:
boolean booleanVar;
public class Geeks {
public static void main(String[] args) {
boolean isJavaFun = true;
boolean isFishTasty = false;
[Link]("Is Java fun? " + isJavaFun);
[Link]("Is fish tasty? " + isFishTasty);
}
}

Output
Is Java fun? true
Is fish tasty? false
2. byte Data Type
An 8-bit signed integer used to save memory in large numeric arrays.
Syntax:
byte byteVar;
public class Geeks {
public static void main(String[] args) {
byte age = 25;
byte temperature = -10;
[Link]("Age: " + age);
[Link]("Temperature: " + temperature);
}
}

Output
Age: 25
Temperature: -10
3. short Data Type
A 16-bit signed integer often used when memory is limited and values are moderate in size.
Syntax:
short shortVar;
public class Geeks {
public static void main(String[] args) {
short students = 1000;
short temp = -200;
[Link]("Students: " + students);
[Link]("Temperature: " + temp);
}
}

Output
Number of Students: 1000
Temperature: -200
4. int Data Type
A 32-bit signed integer and the most commonly used numeric data type.
Syntax:
int intVar;
Size : 4 bytes ( 32 bits )
public class Geeks {
public static void main(String[] args) {
int population = 2000000;
int distance = 150000000;
[Link]("Population: " + population);
[Link]("Distance: " + distance);
}
}

Output
Population: 2000000
Distance: 150000000
5. long Data Type
A 64-bit signed integer used when int is not sufficient for large values.
Syntax:
long longVar;
Size : 8 bytes (64 bits)
public class Geeks {
public static void main(String[] args) {
long worldPopulation = 7800000000L;
long lightYears = 9460730472580800L;
[Link]("World Population: " + worldPopulation);
[Link]("Light Years: " + lightYears);
}
}

Output
World Population: 7800000000
Light Year Distance: 9460730472580800
6. float Data Type
A 32-bit single-precision floating-point type used for fractional values.
Syntax:
float floatVar;
Size : 4 bytes (32 bits)
public class Geeks {
public static void main(String[] args) {
float pi = 3.14f;
float gravity = 9.81f;
[Link]("Pi: " + pi);
[Link]("Gravity: " + gravity);
}
}

Output
Value of Pi: 3.14
Gravity: 9.81
7. double Data Type
A 64-bit double-precision floating-point type and the default for decimal numbers.
Syntax:
double doubleVar;
Size : 8 bytes (64 bits). It is recommended to go through rounding off errors in java.
public class Geeks {
public static void main(String[] args) {
double pi = 3.141592653589793;
double avogadro = 6.02214076e23;
[Link]("Pi: " + pi);
[Link]("Avogadro's Number: " + avogadro);
}
}

Output
Value of Pi: 3.141592653589793
Avogadro's Number: 6.02214076E23
8. char Data Type
A 16-bit Unicode character used to store single symbols or letters.
Syntax:
char charVar;
Size : 2 bytes (16 bits)
Example: This example, demonstrates how to use char data type to store individual characters.
public class Geeks {
public static void main(String[] args) {
char grade = 'A';
char symbol = '$';
[Link]("Grade: " + grade);
[Link]("Symbol: " + symbol);
}
}

Output
Grade: A
Symbol: $
Non-Primitive (Reference) Data Types
Non-primitive data types store references (memory addresses) rather than actual values. They are
created by users and include types like String, Class, Object, Interface, and Array.
1. String
String represents a sequence of characters enclosed in double quotes. Unlike C/C++, Java strings
are objects and are immutable.
Syntax:
String str = "Hello";
public class Geeks {
public static void main(String[] args) {
String name = "Geek1";
String message = "Welcome to Java";
[Link]("Name: " + name);
[Link]("Message: " + message);
}
}

Output
Name: Geek1
Message: Welcome to Java
Note: String cannot be modified after creation. Use StringBuilder for heavy string manipulation.
2. Class
A class is a user-defined blueprint that defines variables and methods. It represents a type of
object and forms the foundation of Object-Oriented Programming.
class Car {
String model;
int year;

Car(String model, int year) {


[Link] = model;
[Link] = year;
}

void display() {
[Link](model + " " + year);
}
}

public class Geeks {


public static void main(String[] args) {
Car myCar = new Car("Toyota", 2020);
[Link]();
}
}

Output
Toyota 2020
3. Object
An Object is an instance of a class representing real-world entities. It has state (data), behavior
(methods), and identity (unique reference).
class Car {
String model;
int year;

Car(String model, int year) {


[Link] = model;
[Link] = year;
}
}

public class Geeks {


public static void main(String[] args) {
Car myCar = new Car("Honda", 2021);
[Link]("Model: " + [Link]);
[Link]("Year: " + [Link]);
}
}

Output
Car Model: Honda
Car Year: 2021
4. Interface
An interface defines a contract of abstract methods that implementing classes must define. It
provides a way to achieve abstraction and multiple inheritance in Java.
interface Animal {
void sound();
}

class Dog implements Animal {


public void sound() {
[Link]("Woof");
}
}

public class Geeks {


public static void main(String[] args) {
Animal dog = new Dog();
[Link]();
}
}

Output
Woof
5. Array
An array stores multiple elements of the same type in a single structure. Java arrays are objects,
dynamically allocated, and indexed from 0.
public class Geeks {
public static void main(String[] args) {
int[] numbers = {1, 2, 3, 4, 5};
String[] names = {"Geek1", "Geek2", "Geek3"};
[Link]("First number: " + numbers[0]);
[Link]("Second name: " + names[1]);
}
}
Types of Java Variables
Last Updated : 3 Oct, 2025

In Java, variables are containers that store data values, such as numbers, text, or Boolean values.
Java variables are categorized into different types based on their scope, lifetime, and usage,
helping programmers manage data efficiently and write organized, maintainable code
Type of Variable
Let us discuss the traits of every type of variable listed here in detail.
Local Variables
A variable defined within a block, method, or constructor is referred to as a local variable.
Key Features
 The Local variable is created at the time of declaration and destroyed when the function
completes its execution.
 The scope of local variables exists only within the block in which they are declared.
 We first need to initialize a local variable before using it within its scope.
Example: Java Program to show the use of local variables
import [Link].*;

class Geeks {
public static void main(String[] args)
{
// Declared a Local Variable
int var = 10;

[Link]("Local Variable: " + var);


}
}

Output
Local Variable: 10
Example: This example demonstrates that local variables are only accessible within the block in
which they are declared
// Java Program to show the use of Local Variables
import [Link].*;

public class Geeks {


public static void main(String[] args)
{
// x is a local variable
int x = 10;

// message is also a local


// variable
String message = "Hello, world!";

[Link]("x = " + x);


[Link]("message = " + message);

if (x > 5) {
// result is a
// local variable
String result = "x is greater than 5";
[Link](result);
}
// Uncommenting the line below will result in a
// compile-time error [Link](result);
for (int i = 0; i < 3; i++) {
String loopMessage
= "Iteration "
+ i; // loopMessage is a local variable
[Link](loopMessage);
}
// Uncommenting the line below will result in a
// compile-time error
// [Link](loopMessage);
}
}

Output
x = 10
message = Hello, world!
x is greater than 5
Iteration 0
Iteration 1
Iteration 2
Instance Variables
Instance variables are known as non-static variables and are declared in a class outside of any
method, constructor, or block.
Key Features
 Instance variables are created when an object is instantiated and destroyed when the
object is destroyed.
 Can have access specifiers; default access is used if none is specified.
 Instance Variables are not mandatory to initialize; take default values based on data type
(0 for int, null for String, etc.).
 Scope is throughout the class, except in static contexts.
 Accessed only through objects of the class.
 Instance Variables can be initialized using constructors or instance blocks.
Example: This example demonstrates the use of instance variables, which are declared within a
class and initialized via a constructor, with default values for uninitialized primitive types.
import [Link].*;

class Geeks {
// Declared Instance Variable
public String geek;
public int i;
public Integer I;
public Geeks()
{
// Default Constructor
// initializing Instance Variable
[Link] = "Sweta Dash";
}

// Main Method
public static void main(String[] args)
{
// Object Creation
Geeks name = new Geeks();

// Displaying O/P
[Link]("Geek name is: " + [Link]);
[Link]("Default value for int is "+ name.i);

// toString() called internally


[Link]("Default value for Integer is: "+ name.I);
}
}
Output
Geek name is: Sweta Dash
Default value for int is 0
Default value for Integer is: null
Static Variables
Key Features
Static variables in Java are variables declared with the static keyword inside a class but outside
any method. They are shared among all objects of the class and exist for the entire lifetime of the
program.
 There is only one copy of a static variable for the entire class, and all objects share it
 Static variable are created at program start and destroyed when the program ends.
 Not mandatory to initialize; default values depend on the data type (0 for int, null for
String, etc.).
 Can be accessed via the class name; accessing through objects shows a compiler warning.
 Cannot be declared locally inside instance methods.
 Can be initialized using static blocks.
Example: This example demonstrates the use of static variables, which belong to the class and
can be accessed without creating an object of the class.
import [Link].*;

class Geeks {

// Static variable
static String geek = "Sweta Dash";

public static void main(String[] args)


{
// Access static variable without creating an object
[Link]("Geek Name is: " + [Link]);

// static int c = 0;
// Error: static variables cannot be declared inside a method
}
}

Output
Geek Name is: Sweta Dash
Difference Between Local, Instance, and Static Variables

Feature Local Variable Instance Variable Static Variable

Inside class, outside Inside class with static


Declared Inside method/block
methods keyword

Only within the Across class methods Shared across all


Scope
block/method (non-static) objects of class

Exists only during Exists as long as Exists throughout


Lifetime
method/block object exists program execution

Number of Each method call Each object has its Only one copy for the
Copies creates new own copy class

No default; must Default based on type Default based on type


Default Value
initialize (0, null) (0, null)

Only within Through class name (or


Access Through objects
method/block object)
Feature Local Variable Instance Variable Static Variable

Optional; can use Optional; can use static


Initialization Required before use
constructors blocks

You might also like