0% found this document useful (0 votes)
3 views29 pages

Object Oriented Programming(1&2)

Uploaded by

luvyakapoor22
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)
3 views29 pages

Object Oriented Programming(1&2)

Uploaded by

luvyakapoor22
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
You are on page 1/ 29

JIMS EMTC

Object-Oriented Programming AIML 202

UNIT -1
Object-oriented programming (OOP) is at the core of Java. In fact, all Java
programs are to at least some extent object-oriented. OOP is so integral to Java that
it is best to understand its basic principles before you begin writing even simple
Java programs. Therefore, this chapter begins with a discussion of the theoretical
aspects of OOP.

Two Paradigms
All computer programs consist of two elements: code and data. Furthermore, a
program can be conceptually organized around its code or around its data. That is,
some programs are written around “what is happening” and others are written
around “who is being affected.” These are the two paradigms that govern how a
program is constructed. The first way is called the process-oriented model. This
approach characterizes a program as a series of linear steps (that is, code). The
process- oriented model can be thought of as code acting on data. Procedural
languages such as C employ this model to considerable success. However, as
mentioned in Chapter 1, problems with this approach appear as programs grow
larger and more complex.
To manage increasing complexity, the second approach, called object-oriented
programming, was conceived. Object-oriented programming organizes a program
around its data (that is, objects) and a set of well-defined interfaces to that data. An
object-oriented program can be characterized as data controlling access to code. As
you will see, by switching the controlling entity to data, you can achieve several
organizational benefits.

Abstraction
An essential element of object-oriented programming is abstraction. Humans
manage complexity through abstraction. For example, people do not think of a car
as a set of tens of thousands of individual parts. They think of it as a well-defined
object with its own unique behavior. This abstraction allows people to use a car to
drive to the grocery store without being overwhelmed by the complexity of the
individual parts. They can ignore the details of how the engine, transmission, and
braking systems work. Instead, they are free to utilize the object as a whole.
A powerful way to manage abstraction is through the use of hierarchical
classifications. This allows you to layer the semantics of complex systems,
breaking them into more manageable pieces. From the outside, the car is a single
object. Once inside, you see that the car consists of several subsystems: steering,
brakes, sound system, seat belts, heating, cellular phone, and so on. In turn, each of
JIMS EMTC

these subsystems is made up of more specialized units. For instance, the sound
system might consist of a radio, a CD player, and/or MP3 player. The point is that
you manage the complexity of the car (or any other complex system) through the
use of hierarchical abstractions.
Hierarchical abstractions of complex systems can also be applied to computer
programs. The data from a traditional process-oriented program can be transformed
by abstraction into its component objects. A sequence of process steps can become
a collection of messages between these objects. Thus, each of these objects
describes its own unique behavior. You can treat these objects as concrete entities
that respond to messages telling them to do something. This is the essence of
object-oriented Programming.
EX. class Geeks {
public static void main(String[] args)
{
System.out.println("I am AIML");
}
}

OUTPUT:
I am AIML

OOPs Concepts:
● Class
● Objects
● Data Abstraction
● Encapsulation
● Inheritance
● Polymorphism
● Dynamic Binding

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
JIMS EMTC

them will have 4 wheels, Speed Limit, Mileage range, etc. So here, cars are the
class, and wheels, speed limits, mileage are their properties.
2. Object:
It is a basic unit of Object-Oriented Programming and represents 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.

Object
Example:
public class Main {
int x = 5;

public static void main(String[] args) {


Main myObj = new Main();
System.out.println(myObj.x);
}

3. Data Abstraction:
JIMS EMTC

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.

Consider a real-life example of encapsulation, in a company, there are different


sections like the accounts section, finance section, sales section, etc. The finance
section handles all the financial transactions and keeps records of all the data
related to finance. Similarly, the sales section handles all the sales-related activities
and keeps records of all the sales. Now there may arise a situation when for some
reason an official from the finance section needs all the data about sales in a
particular month. In this case, he is not allowed to directly access the data of the
sales section. He will first have to contact some other officer in the sales section
JIMS EMTC

and then request him to give the particular data. This is what encapsulation is. Here
the data of the sales section and the employees that can manipulate them are
wrapped under a single name “sales section”.
public class Person {
private String name; // private = restricted access

// Getter
public String getName() {
return name;
}

// Setter
public void setName(String newName) {
this.name = newName;
}

The get method returns the value of the variable name.

The set method takes a parameter (newName) and assigns it to the name variable.
The this keyword is used to refer to the current object.

However, as the name variable is declared as private, we cannot access it from


outside this class

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.
JIMS EMTC

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.

// Java program to illustrate the


// concept of inheritance

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
JIMS EMTC

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 possesses different behavior in different situations. This is called
polymorphism.

// Java program to demonstrate working of method


// overloading in Java

public class Sum {


// Overloaded sum(). This sum takes two int parameters
public int sum(int x, int y) { return (x + y); }

// Overloaded sum(). This sum takes three int parameters


JIMS EMTC

public int sum(int x, int y, int z)


{
return (x + y + z);
}

// Overloaded sum(). This sum takes two double


// parameters
public double sum(double x, double y)
{
return (x + y);
}
public static void main(String args[])
{
Sum s = new Sum();
System.out.println(s.sum(10, 20));
System.out.println(s.sum(10, 20, 30));
System.out.println(s.sum(10.5, 20.5));
}
}

Virtual function example:

Parent.Java:

class Parent {
void v1() //Declaring function
{
System.out.println("Inside the Parent Class");
}
}
JIMS EMTC

Child.java:

public class Child extends Parent{


void v1() // Overriding function from the Parent class
{
System.out.println("Inside the Child Class");
}
public static void main(String args[]){
Parent ob1 = new Child(); //Referring the child class object using the
parent class
ob1.v1();
}
}
Output:

Inside the Child Class

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.
● When the type of the object is determined at run-time, it is known as
dynamic binding.

Example of dynamic binding


class Animal{
void eat(){System.out.println("animal is eating...");}
}

class Dog extends Animal{


void eat(){System.out.println("dog is eating...");}

public static void main(String args[]){


Animal a=new Dog();
JIMS EMTC

a.eat();
}
}

Output: dog is eating...

Benefits of OOP
● We can build the programs from standard working modules that
communicate with one another, rather than having to start writing the
code from scratch which leads to saving of development time and higher
productivity,
● OOP language allows to break the program into bit-sized problems that
can be solved easily (one object at a time).
● The new technology promises greater programmer productivity, better
quality of software and lesser maintenance cost.
● OOP systems can be easily upgraded from small to large systems.
● It is possible that multiple instances of objects co-exist without any
interference,
● It is very easy to partition the work in a project based on objects.
● It is possible to map the objects in the problem domain to those in the
program.
● The principle of data hiding helps the programmer to build secure
programs which cannot be invaded by the code in other parts of the
program.
● By using inheritance, we can eliminate redundant code and extend the
use of existing classes.
● Message passing techniques is used for communication between objects
which makes the interface descriptions with external systems much
simpler.
● The data-centered design approach enables us to capture more details of
model in an implementable form.

Object-Oriented Design (OOD)


Object-oriented design (OOD) is a programming technique that solves software
problems by building a system of interrelated objects. It makes use of the concepts
of classes and objects, encapsulation, inheritance, and polymorphism to model
real-world entities and their interactions. A system architecture that is modular,
adaptable, and simple to understand and maintain is produced using OOD.
JIMS EMTC

Key Principles of OOD


A number of fundamental principles support object-oriented design (OOD),
helping in the development of reliable, expandable, and maintainable systems:
1. Encapsulation: Bundling data with methods that operate on the data,
restricting direct access to some components and protecting object
integrity.
2. Abstraction: Simplifying complex systems by modeling classes
appropriate to the problem domain, highlighting essential features while
hiding unnecessary details.
3. Inheritance: Establishing a hierarchy between classes, allowing derived
classes to inherit properties and behaviors from base classes, promoting
code reuse and extension.
4. Polymorphism: Enabling objects to be treated as instances of their parent
class, allowing one interface to be used for a general class of actions,
improving flexibility and integration.
5. Composition: Building complex objects by combining simpler ones,
promoting reuse and flexible designs.

Object-Oriented Design (OOD) is important in system design due to several key


reasons:
● Modularity: OOD simplifies development and maintenance by
decomposing complicated structures into smaller, more manageable
components.
● Reusability: Objects and classes can be reused across different projects,
reducing redundancy and saving time.
● Scalability: OOD facilitates system growth by making it simple to
incorporate new objects without interfering with already-existing
functionality.
● Maintainability: Encapsulation of data and behavior within objects
simplifies troubleshooting and updates, enhancing system reliability.
● Clear Mapping to Real-World Problems: By modeling software after
real-world entities and their interactions, OOD makes systems more
intuitive and easier to understand.
● Flexibility and Extensibility: Through inheritance and polymorphism,
OOD allows for extending and adapting systems with minimal changes,
accommodating future requirements efficiently.

Introduction to Java
JIMS EMTC

Java is a class-based, object-oriented programming language that is designed to


have as few implementation dependencies as possible. It is intended to let
application developers Write Once and Run Anywhere (WORA), meaning that
compiled Java code can run on all platforms that support Java without the need for
recompilation. Java was developed by James Gosling at Sun Microsystems Inc. in
May 1995 and later acquired by Oracle Corporation and is widely used for
developing applications for desktop, web, and mobile devices.

Java is known for its simplicity, robustness, and security features, making it a
popular choice for enterprise-level applications. Java applications are compiled to
byte code that can run on any Java Virtual Machine. The syntax of Java is similar
to C/C++.
Java makes writing, compiling, and debugging programming easy. It helps to
create reusable code and modular programs.
Key Features of Java

1. Platform Independent

Compiler converts source code to byte code and then the JVM executes the
bytecode generated by the compiler. This byte code can run on any platform be it
Windows, Linux, or macOS which means if we compile a program on Windows,
then we can run it on Linux and vice versa. Each operating system has a different
JVM, but the output produced by all the OS is the same after the execution of the
byte code. That is why we call java a platform-independent language.

2. Object-Oriented Programming

Java is an object-oriented language, promoting the use of objects and classes.


Organizing the program in the terms of a collection of objects is a way of object-
oriented programming, each of which represents an instance of the class.
The four main concepts of Object-Oriented programming are:
● Abstraction
● Encapsulation
● Inheritance
● Polymorphism
JIMS EMTC

3. Simplicity

Java’s syntax is simple and easy to learn, especially for those familiar with C or C+
+. It eliminates complex features like pointers and multiple inheritances, making it
easier to write, debug, and maintain code.

4. Robustness

Java language is robust which means reliable. It is developed in such a way that it
puts a lot of effort into checking errors as early as possible, that is why the java
compiler is able to detect even those errors that are not easy to detect by another
programming language. The main features of java that make it robust are garbage
collection, exception handling, and memory allocation.

5. Security

In java, we don’t have pointers, so we cannot access out-of-bound arrays i.e it


shows ArrayIndexOutOfBound Exception if we try to do so. That’s why several
security flaws like stack corruption or buffer overflow are impossible to exploit in
Java. Also, java programs run in an environment that is independent of the
os(operating system) environment which makes java programs more secure.

6. Distributed

We can create distributed applications using the java programming language.


Remote Method Invocation and Enterprise Java Beans are used for creating
distributed applications in java. The java programs can be easily distributed on one
or more systems that are connected to each other through an internet connection.

7. Multithreading

Java supports multithreading, enabling the concurrent execution of multiple parts


of a program. This feature is particularly useful for applications that require high
performance, such as games and real-time simulations.

8. Portability
JIMS EMTC

As we know, java code written on one machine can be run on another machine.
The platform-independent feature of java in which its platform-independent
bytecode can be taken to any platform for execution makes java portable.
WORA(Write Once Run Anywhere) makes java application to generates a ‘.class’
file that corresponds to our applications(program) but contains code in 0binary
format. It provides ease t architecture-neutral ease as bytecode is not dependent on
any machine architecture. It is the primary reason java is used in the enterprising
IT industry globally worldwide.

9. High Performance

Java architecture is defined in such a way that it reduces overhead during the
runtime and at some times java uses Just In Time (JIT) compiler where the
compiler compiles code on-demand basis where it only compiles those methods
that are called making applications to execute faster.
How Java Code Executes?
The execution of a Java application code involves three main steps:

How Java Code Executes


JIMS EMTC

1. Creating the Program

Java programs are written using a text editor or an Integrated Development


Environment (IDE) like IntelliJ IDEA, Eclipse, or NetBeans. The source code is
saved with a .java extension.

2. Compiling the Program

The Java compiler (javac) converts the source code into bytecode, which is stored
in a .class file. This bytecode is platform-independent and can be executed on any
machine with a JVM.

3. Running the Program

The JVM executes the compiled bytecode, translating it into machine code specific
to the operating system and hardware.
Example Program:

public class HelloWorld {

public static void main(String[] args)

System.out.println("Hello, World!");

Characteristics of java
The primary objective of Java programming language creation was to make it
portable, simple and secure programming language. Apart from this, there are also
some excellent features which play an important role in the popularity of this
language. The features of Java are also known as Java buzzwords.

A list of the most important features of the Java language is given below.
JIMS EMTC

1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10. Multithreaded
11. Distributed
12. Dynamic

Java sandbox model

The "sandbox" model in Java refers to a security mechanism designed to protect a


user's system from potentially harmful or malicious code. It allows untrusted code,
such as Java applets or code downloaded from the internet, to run within a
restricted environment where it cannot perform actions that could harm the host
system. Here's a brief overview of the sandbox model in Java:
JIMS EMTC

1. Purpose of the Sandbox Model:

The sandbox model aims to strike a balance between the ability to run untrusted
code and maintaining system security. It's especially important in scenarios where
users interact with content from untrusted sources, such as web browsers running
Java applets.

2. Key Features of the Sandbox Model:

Code Isolation: Untrusted code runs in a controlled and isolated environment


separate from the host system's resources and processes. This isolation prevents the
code from directly affecting the host system.

Security Manager: Java employs a "security manager" component that acts as a


guardian, enforcing security policies. The security manager evaluates requests
made by the untrusted code to access resources like the file system, network, or
system properties. If the requested action is not permitted, it is denied.

Access Control Lists (ACLs): The security manager uses access control lists to
define what actions or resources are allowed or denied. Developers can configure
these ACLs to specify fine-grained security policies.

3. Restricted Actions:

Within the sandbox, certain actions are typically restricted or prohibited. These
actions may include:

Accessing or modifying files on the host system.

Making network connections to arbitrary servers.

Loading or running native code.

Accessing sensitive system properties.

4. Permission Model:

In Java, permissions are used to grant or deny specific actions to code running in
the sandbox. Permissions are organized into permission classes, each representing
a specific type of action, such as file access, network access, or reflection.
JIMS EMTC

Developers and administrators can configure policies to assign permissions to code


based on the principle of least privilege.

5. Code Signing:

Code signing is a practice in which code is digitally signed with a certificate to


verify its source and integrity. Signed code may be granted more privileges when
running in the sandbox, as it is considered more trustworthy. Unsigned code
typically has stricter restrictions.

6. Applet Security:

Historically, Java applets were a common use case for the sandbox model. Applets
were small Java applications embedded within web pages. They ran in a restricted
environment, ensuring that they couldn't harm the user's computer. However, due
to security concerns, many modern web browsers have deprecated or removed
support for Java applets.

7. Evolving Security:

The security landscape is continually evolving, and vulnerabilities may emerge. To


address these challenges, Java has periodically updated its security features and
policies to strengthen the sandbox model.
JIMS EMTC

● The essence of the sandbox model is that local code is trusted to have full
access to vital system resources (such as the file system) while
downloaded remote code (an applet) is not trusted and can access only
the limited resources provided inside the sandbox.
● A sandbox typically provides a tightly controlled set of resources for guest
programs to run in, such as limited space on disk and memory.

Java programs for beginners

1. Java Program To Calculate Area Of Circle


import java.util.Scanner;

class AreaOfCircle

public static void main(String args[])

Scanner s= new Scanner(System.in);

System.out.println("Enter the radius:");

double r= s.nextDouble();

double area=(22*r*r)/7 ;

System.out.println("Area of Circle is: " + area);

2. Java Program To Calculate Factorial using standard values with


outputs
JIMS EMTC

class Factorial

public static void main(String arg[])

int n=5,fact=1;

for(int i=1;i<=n;i++)

fact=fact*i;

System.out.println("factorial="+fact);

3. Java Program Calculate Average Marks Using Arrays


import java.util.Scanner;
class AverageMarks
{
public static void main(String args[])
{

int i;
JIMS EMTC

System.out.println("Enter number of subjects");

Scanner sc=new Scanner(System.in);

int n=sc.nextInt();

int[] a=new int[n];

double avg=0;

System.out.println("Enter marks");

for( i=0;i<n;i++)
{
a[i]=sc.nextInt();
}

for( i=0;i<n;i++)
{
avg=avg+a[i];
}

System.out.print("Average of (");

for(i=0;i<n-1;i++)
{
System.out.print(a[i]+",");
}
System.out.println(a[i]+") ="+avg/n);
}
}

4. Java Program To Calculate Average Of N Numbers


class Average
{
public static void main(String arg[])
{
int n=5,result=0;
JIMS EMTC

int a[]=new int[5];

a[0]=10;

a[1]=20;

a[2]=30;

a[3]=40;

a[4]=50;

for(int i=0;i<n;i++)
result=result+a[i];

System.out.println("average of
("+a[0]+","+a[1]+","+a[2]+","+a[3]+","+a[4]+") is ="+result/n);

}
}

5. Java Program to Check if a Given Integer is Odd or Even


// Java Program to Check if Given Integer is Odd or Even
// Using Brute Force Approach

// Importing required classes


import java.io.*;
import java.util.Scanner;

// Main class
class GFG {

// Main Driver Method


public static void main(String[] args)
{
// Declaring and initializing integer variable
int num = 10;

// Checking if number is even or odd number


JIMS EMTC

// via remainder
if (num % 2 == 0) {

// If remainder is zero then this number is even


System.out.println("Entered Number is Even");
}

else {

// If remainder is not zero then this number is


// odd
System.out.println("Entered Number is Odd");
}
}
}

6. Armstrong Number In Java Program


Consider the example: 371
A: 3^3 + 7^3 + 1^3 = 371 ( If you add those all numbers, the final digit should be
same as given number ).

import java.util.Scanner;
class ArmstrongWhile
{
public static void main(String[] arg)
{
int i=100,arm;
System.out.println("Armstrong numbers between 100 to 999");
while(i<1000)
{
arm=armstrongOrNot(i);
if(arm==i)
System.out.println(i);
i++;
}
}
static int armstrongOrNot(int num)
{
int x,a=0;
JIMS EMTC

while(num!=0)
{
x=num%10;
a=a+(x*x*x);
num/=10 ;
}
return a;
}
}

UNIT-2
Data types in Java are of different sizes and values that can be
stored in the variable that is made as per convenience and
circumstances to cover up all test cases. Java has two categories in
which data types are segregated
1. Primitive Data Type: such as boolean, char, int, short, byte, long, float,
and double. The Boolean with uppercase B is a wrapper class for the
primitive data type boolean in Java.
2. Non-Primitive Data Type or Object Data type: such as String, Array, etc.

// Java Program to demonstrate int data-type


import java.io.*;

class GFG
{
public static void main (String[] args)
{
// declaring two int variables
int a = 10;
int b = 20;

System.out.println( a + b );
}
}
JIMS EMTC

Primitive Data Types

1. boolean Data Type

The boolean data type represents a logical value that can be either true or false.
Conceptually, it represents a single bit of information, but the actual size used by
the virtual machine is implementation-dependent and typically at least one byte
(eight bits) in practice. Values of the boolean type are not implicitly or explicitly
converted to any other type using casts. However, programmers can write
conversion code if needed.
Syntax:
boolean booleanVar;
Size : Virtual machine dependent (typically 1 byte, 8 bits)

2. byte Data Type

The byte data type is an 8-bit signed two’s complement integer. The byte data type
is useful for saving memory in large arrays.
Syntax:
JIMS EMTC

byte byteVar;
Size : 1 byte (8 bits)-

3. short Data Type

The short data type is a 16-bit signed two’s complement integer. Similar to byte, a
short is used when memory savings matter, especially in large arrays where space
is constrained.
Syntax:
short shortVar;
Size : 2 bytes (16 bits)

4. int Data Type

It is a 32-bit signed two’s complement integer.


Syntax:
int intVar;
Size : 4 bytes ( 32 bits )

5. long Data Type

The long data type is a 64-bit signed two’s complement integer. It is used when an
int is not large enough to hold a value, offering a much broader range.
Syntax:
long longVar;
Size : 8 bytes (64 bits)

6. float Data Type

The float data type is a single-precision 32-bit IEEE 754 floating-point. Use a float
(instead of double) if you need to save memory in large arrays of floating-point
numbers. The size of the float data type is 4 bytes (32 bits).
Syntax:
JIMS EMTC

float floatVar;
Size : 4 bytes (32 bits)

7. double Data Type

The double data type is a double-precision 64-bit IEEE 754 floating-point. For
decimal values, this data type is generally the default choice. The size of the
double data type is 8 bytes or 64 bits.
Syntax:
double doubleVar;
Size : 8 bytes (64 bits)
Note: Both float and double data types were designed especially for scientific
calculations, where approximation errors are acceptable. If accuracy is the most
prior concern then, it is recommended not to use these data types and use
BigDecimal class instead.

8. char Data Type

The char data type is a single 16-bit Unicode character with the size of 2 bytes (16
bits).
Syntax:
char charVar;
Size : 2 bytes (16 bits)
Non-Primitive (Reference) Data Types

The Non-Primitive (Reference) Data Types will contain a memory address of


variable values because the reference types won’t store the variable value directly
in memory. They are strings, objects, arrays, etc.

1. Strings

Strings are defined as an array of characters. The difference between a character


array and a string in Java is, that the string is designed to hold a sequence of
JIMS EMTC

characters in a single variable whereas, a character array is a collection of separate


char-type entities. Unlike C/C++, Java strings are not terminated with a null
character.
Syntax: Declaring a string
<String_Type> <string_variable> = “<sequence_of_string>”;
Example:
// Declare String without using new operator
String s = "GeeksforGeeks";
// Declare String using new operator
String s1 = new String("GeeksforGeeks");

Literal: Any constant value which can be assigned to the variable is called
literal/constant.
// Here 100 is a constant/literal.
int x = 100;

Floating-Point literal

For Floating-point data types, we can specify literals in only decimal form, and we
cant specify in octal and Hexadecimal forms.
Decimal literals(Base 10): In this form, the allowed digits are 0-9.
double d = 123.456;

Char literals

For char data types, we can specify literals in 4 ways:


Single quote: We can specify literal to a char data type as a single character within
the single quote.
char ch = 'a';
Char literal as Integral literal: we can specify char literal as integral literal,
which represents the Unicode value of the character, and that integral literal can be
JIMS EMTC

specified either in Decimal, Octal, and Hexadecimal forms. But the allowed range
is 0 to 65535.
char ch = 062;
Unicode Representation: We can specify char literals in Unicode representation ‘\
uxxxx’. Here xxxx represents 4 hexadecimal numbers.
char ch = '\u0061';// Here /u0061 represents a.
Escape Sequence: Every escape character can be specified as char literals.
char ch = '\n';

String literals

Any sequence of characters within double quotes is treated as String literals.


String s = "Hello";
String literals may not contain unescaped newline or linefeed characters. However,
the Java compiler will evaluate compile-time expressions

You might also like