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

JAVA Unit 1

Uploaded by

Praveen Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

JAVA Unit 1

Uploaded by

Praveen Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 88

UNIT I

Object Orientated Paradigm:


Introduction to Procedural and Object oriented programming, A way of viewing world –
agents and communities, responsibilities, messages, methods, class and instance, Oops concepts.
Java Basics: Introduction to Java , JVM Architecture, Java Buzz words, Java Tokens-
Comments, Identifiers, Keywords, Separators, Data types, enumerated types, Variables,
constants, Type Conversion, Operators, Control Statements, Wrapper Classes, Structure of java
with simple standalone program, arrays, console input and output, formatting output,
constructors, methods – static and instance, parameter passing, access control modifiers, this
reference, overloading methods and constructors, recursion, garbage collection, Inner classes,
exploring String and String Buffer class.

History of Java

Java was originally designed for interactive television, but it was too advanced technology for
the digital cable television industry at the time. The history of Java starts with the Green Team.
Java team members initiated this project to develop a language for digital devices such as set-
top boxes, televisions, etc. However, it was best suited for internet programming. Later, Java
technology was incorporated by Netscape.

The principles for creating Java programming were "Simple, Robust, Portable, Platform-
independent, Secured, High Performance, Multithreaded, Architecture Neutral, Object-
Oriented, Interpreted, and Dynamic".

Java was developed by James Gosling, who is known as the father of Java, in 1995. James
Gosling and his team members started the project in the early '90s.

Java is used in internet programming, mobile devices, games, e-business solutions, etc.
Following are given significant points that describe the 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.
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.
4) After that, it was called Oak and was developed as a part of the Green project.
Why Java was named as "Oak"?

5) 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.
T]\
6) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
Technologies.

Why Java Programming named "Java"?

7) Why had they chose the name Java for Java language? The team gathered to choose a new
name. The suggested words were "dynamic", "revolutionary", "Silk", "jolt", "DNA", etc. They
wanted something that reflected the essence of the technology: revolutionary, dynamic, lively,
cool, unique, and easy to spell, and fun to say.
According to James Gosling, "Java was one of the top choices along with Silk". Since Java was
so unique, most of the team members preferred Java than other names.
8) Java is an island in Indonesia where the first coffee was produced (called Java coffee). It is a
kind of espresso bean. Java name was chosen by James Gosling while having a cup of coffee
nearby his office.
9) Notice that Java is just a name, not an acronym.
10) Initially developed by James Gosling at Sun Microsystems released in 1995.
11) In 1995, Time magazine called Java one of the Ten Best Products of 1995.
12) 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.

1. JDK Alpha and Beta (1995)


2. JDK 1.0 (23rd Jan 1996)
3. JDK 1.1 (19th Feb 1997)
4. J2SE 1.2 (8th Dec 1998)
5. J2SE 1.3 (8th May 2000)
6. J2SE 1.4 (6th Feb 2002)
7. J2SE 5.0 (30th Sep 2004)
8. Java SE 6 (11th Dec 2006)
9. Java SE 7 (28th July 2011)
10. Java SE 8 (18th Mar 2014)
11. Java SE 9 (21st Sep 2017)
12. Java SE 10 (20th Mar 2018)
13. Java SE 11 (September 2018)
14. Java SE 12 (March 2019)
15. Java SE 13 (September 2019)
16. Java SE 14 (Mar 2020)
17. Java SE 15 (September 2020)
18. Java SE 16 (Mar 2021)
19. Java SE 17 (September 2021)
20. Java SE 18 (to be released by March 2022)

Application

According to Sun, 3 billion devices run Java. There are many devices where Java is currently
used. Some of them are as follows:

1. Desktop Applications such as acrobat reader, media player, antivirus, etc.


2. Web Applications such as irctc.co.in etc.
3. Enterprise Applications such as banking applications.
4. Mobile
5. Embedded System
6. Smart Card
7. Robotics
8. Games, etc.

Types of Java Applications

There are mainly 4 types of applications that can be created using Java programming:

1) Standalone Application

Standalone applications are also known as desktop applications or window-based applications.


These are traditional software that we need to install on every machine. Examples of standalone
application are Media player, antivirus, etc. AWT and Swing are used in Java for creating
standalone applications.

2) Web Application

An application that runs on the server side and creates a dynamic page is called a web
application. Currently, Servlet, JSP, Struts, Spring, Hibernate, JSF, etc. technologies are used for
creating web applications in Java.

3) Enterprise Application

An application that is distributed in nature, such as banking applications, etc. is called an


enterprise application. It has advantages like high-level security, load balancing, and clustering.
In Java, EJB is used for creating enterprise applications.
4) Mobile Application

An application which is created for mobile devices is called a mobile application. Currently,
Android and Java ME are used for creating mobile applications.

Java Platforms / Editions

There are 4 platforms or editions of Java:


1) Java SE (Java Standard Edition) It is a Java programming platform. It includes Java
programming APIs such as java.lang, java.io, java.net, java.util, java.sql, java.math etc. It
includes core topics like OOPs, String, Regex, Exception, Inner classes, Multithreading, I/O
Stream, Networking, AWT, Swing, Reflection, Collection, etc.
2) Java EE (Java Enterprise Edition) It is an enterprise platform that is mainly used to develop
web and enterprise applications. It is built on top of the Java SE platform. It includes topics like
Servlet, JSP, Web Services, EJB, JPA, etc.
3) Java ME (Java Micro Edition) It is a micro platform that is dedicated to mobile
applications.

4) JavaFX It is used to develop rich internet applications. It uses a lightweight user interface
API.

Object-Oriented Programming
The word object-oriented is the combination of two words i.e. object and oriented.
The meaning of the object is an article or entity that exists in the real world.
The meaning of oriented is interested in a particular kind of thing or entity.

Object-oriented programming has several advantages over procedural programming:


 OOP is faster and easier to execute
 OOP provides a clear structure for the programs
 OOP helps to keep the Java code DRY "Don't Repeat Yourself", and makes the code
easier to maintain, modify and debug
 OOP makes it possible to create full reusable applications with less code and shorter
development time

OOPs Concepts

The OOPs concepts include the following:

1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation

Object
An object is a real-world entity that has attributes, behavior, and properties. It is referred to as an
instance of the class. It contains member functions, variables that we have defined in the class. It
occupies space in the memory. Different objects have different states or attributes, and behaviors.

Any entity that has state and behavior is known as an object. For example, a chair, pen, table,
keyboard, bike, etc. It can be physical or logical.
An Object can be defined as an instance of a class. An object contains an address and takes up
some space in memory. Objects can communicate without knowing the details of each other's
data or code. The only necessary thing is the type of message accepted and the type of response
returned by the objects

Class

Collection of objects is called class. It is a logical entity.


A class can also be defined as a blueprint from which you can create an individual object. Class
doesn't consume any space.
It is a user-defined data type. Inside a class, we define variables, constants, member functions,
and other functionality. it binds data and functions together in a single unit. It does not consume
memory at run time. Note that classes are not considered as a data structure. It is a logical entity.
It is the best example of data binding. Note that a class can exist without an object but vice-versa
is not possible.
The following figure best illustrates the class and object in OOP.

Abstraction
The concept allows us to hide the implementation from the user but shows only essential
information to the user. Using the concept developer can easily make changes and added over
time.
There are the following advantages of abstraction:
o It reduces complexity.
o It avoids delicacy.
o Eases the burden of maintenance
o Increase security and confidentially.

Encapsulation

Encapsulation is a mechanism that allows us to bind data and functions of a class into an entity.
It protects data and functions from outside interference and misuse. Therefore, it also provides
security. A class is the best example of encapsulation.

Inheritance

The concept allows us to inherit or acquire the properties of an existing class (parent class) into a
newly created class (child class). It is known as inheritance. It provides code reusability.
Polymorphism

The word polymorphism is derived from the two words i.e. ploy and morphs. Poly means many
and morphs means forms. It allows us to create methods with the same name but different
method signatures. It allows the developer to create clean, sensible, readable, and resilient code.

The above figure best describes the concepts of polymorphism. A person plays an employee role
in the office, father and husband role in the home.

The major concepts that we have discussed above are known as pillars of OOPs. There
are four pillars on which OOP rests.
o Abstraction
o Encapsulation
o Inheritance
o Polymorphism
Benefits of OOP
o Modular, scalable, extensible, reusable, and maintainable.
o It models the complex problem in a simple structure.
o Object can be used across the program.
o Code can be reused.
o We can easily modify, append code without affecting the other code blocs.
o Provides security through encapsulation and data hiding features.
o Beneficial to collaborative development in which a large project is divided into groups.
o Debugging is easy.

List of Object-Oriented Programming Languages

There are various object-oriented programming languages are present. They are Java, C+
+, C#, Python, R, PHP, Visual Basic.NET, JavaScript, Ruby, Perl, Object Pascal, Objective-
C, Dart, Swift, Scala, Kotlin, Common Lisp, MATLAB, and Smalltalk.

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

Simple

Java is very easy to learn, and its syntax is simple, clean and easy to understand. According to
Sun Microsystem, Java language is a simple programming language because:

o Java syntax is based on C++ (so easier for programmers to learn it after C++).
o Java has removed many complicated and rarely-used features, for example, explicit
pointers, operator overloading, etc.
o There is no need to remove unreferenced objects because there is an Automatic Garbage
Collection in Java.

Object-oriented
Java is an object-oriented programming language. Everything in Java is an object. Object-
oriented means we organize our software as a combination of different types of objects that
incorporate both data and behavior.
Object-oriented programming (OOPs) is a methodology that simplifies software development
and maintenance by providing some rules.
Basic concepts of OOPs are:

1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation

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.
A platform is the hardware or software environment in which a program runs.
There are two types of platforms software-based and hardware-based. Java provides a software-
based platform.
The Java platform differs from most other platforms in the sense that it is a software-based
platform that runs on top of other hardware-based platforms. It has two components:

1. Runtime Environment
2. API(Application Programming Interface)

Java code can be executed on multiple platforms, for example, Windows, Linux, Sun Solaris,
Mac/OS, etc. Java code is compiled by the compiler and converted into bytecode. This bytecode
is a platform-independent code because it can be run on multiple platforms, i.e., Write Once and
Run Anywhere (WORA).

Secured

Java is best known for its security. With Java, we can develop virus-free systems. Java is secured
because:
o No explicit pointer
o Java Programs run inside a virtual machine sandbox

o Classloader: Classloader in Java is a part of the Java Runtime Environment (JRE) which
is used to load Java classes into the Java Virtual Machine dynamically. It adds security by
separating the package for the classes of the local file system from those that are
imported from network sources.
o Bytecode Verifier: It checks the code fragments for illegal code that can violate access
rights to objects.
o Security Manager: It determines what resources a class can access such as reading and
writing to the local disk.

Java language provides these securities by default. Some security can also be provided by an
application developer explicitly through SSL, JAAS, Cryptography, etc.

Robust

The English mining of Robust is strong. Java is robust because:

o It uses strong memory management.


o There is a lack of pointers that avoids security problems.
o Java provides automatic garbage collection which runs on the Java Virtual Machine to
get rid of objects which are not being used by a Java application anymore.
o There are exception handling and the type checking mechanism in Java. All these points
make Java robust.

Architecture-neutral

Java is architecture neutral because there are no implementation dependent features, for example,
the 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. However, it occupies 4 bytes of memory for both 32 and 64-
bit architectures in Java.
Portable

Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't
require any implementation.

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.

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.

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.

Dynamic

Java is a dynamic language. It supports the 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).
S.no. On the Procedural Programming Object-oriented programming
basis of

1. Definition It is a programming language that Object-oriented programming is a


is derived from structure computer programming design
programming and based upon the philosophy or methodology that
concept of calling procedures. It organizes/ models software design
follows a step-by-step approach in around data or objects rather than
order to break down a task into a functions and logic.
set of variables and routines via a
sequence of instructions.

2. Security It is less secure than OOPs. Data hiding is possible in object-


oriented programming due to
abstraction. So, it is more secure
than procedural programming.

3. Approach It follows a top-down approach. It follows a bottom-up approach.

4. Data In procedural programming, data In OOP, objects can move and


movement moves freely within the system communicate with each other via
from one function to another. member functions.

5. Orientation It is structure/procedure-oriented. It is object-oriented.

6. Access There are no access modifiers in The access modifiers in OOP are
modifiers procedural programming. named as private, public, and
protected.

7. Inheritance Procedural programming does not There is a feature of inheritance in


have the concept of inheritance. object-oriented programming.

8. Code There is no code reusability It offers code reusability by using


reusability present in procedural the feature of inheritance.
programming.

9. Overloading Overloading is not possible in In OOP, there is a concept of


procedural programming. function overloading and operator
overloading.

10. Importance It gives importance to functions It gives importance to data over


over data. functions.

11. Virtual In procedural programming, there In OOP, there is an appearance of


class are no virtual classes. virtual classes in inheritance.

12. Complex It is not appropriate for complex It is appropriate for complex


problems problems. problems.
13. Data hiding There is not any proper way for There is a possibility of data
data hiding. hiding.

14. Program In Procedural programming, a In OOP, a program is divided into


division program is divided into small small parts that are referred to as
programs that are referred to as objects.
functions.

15. Examples Examples of Procedural The examples of object-oriented


programming include C, Fortran, programming are -
Pascal, and VB. .NET, C#, Python, Java, VB.NET,
and C++.
JVM
JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine because it
doesn't physically exist. It is a specification that provides a runtime environment in which Java
bytecode can be executed. It can also run those programs which are written in other languages
and compiled to Java bytecode.
JVMs are available for many hardware and software platforms. JVM, JRE, and JDK are platform
dependent because the configuration of each OS is different from each other. However, Java is
platform independent. There are three notions of the JVM: specification, implementation, and
instance.
The JVM performs the following main tasks:
Loads code
Verifies code
Executes code
Provides runtime environment
JVM (Java Virtual Machine) Architecture
1. Java Virtual Machine
2. Internal Architecture of JVM

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

JVM is:

1. A specification where working of Java Virtual Machine is specified. But implementation


provider is independent to choose the algorithm. Its implementation has been provided by
Oracle and other companies.
2. An implementation Its implementation is known as JRE (Java Runtime Environment).
3. Runtime Instance Whenever you write java command on the command prompt to run
the java class, an instance of JVM is created.

The JVM performs following operation:

o Loads code
o Verifies code
o Executes code
o Provides runtime environment

JVM provides definitions for the:

o Memory area
o Class file format
o Register set
o Garbage-collected heap
o Fatal error reporting etc.
JVM Architecture

Let's understand the internal architecture of JVM. It contains classloader, memory area,
execution engine etc.

1) Classloader

Classloader is a subsystem of JVM which is used to load class files. Whenever we run the java
program, it is loaded first by the classloader. There are three built-in classloaders in Java.

1. Bootstrap ClassLoader: This is the first classloader which is the super class of
Extension classloader. It loads the rt.jar file which contains all class files of Java
Standard Edition like java.lang package classes, java.net package classes, java.util
package classes, java.io package classes, java.sql package classes etc.
2. Extension ClassLoader: This is the child classloader of Bootstrap and parent classloader
of System classloader. It loades the jar files located inside
$JAVA_HOME/jre/lib/ext directory.
3. System/Application ClassLoader: This is the child classloader of Extension classloader.
It loads the classfiles from classpath. By default, classpath is set to current directory. You
can change the classpath using "-cp" or "-classpath" switch. It is also known as
Application classloader.

//Example to print the classloader name


public class ClassLoaderExample
{
public static void main(String[] args)
{
// Let's print the classloader name of current class.
//Application/System classloader will load this class
Class c=ClassLoaderExample.class;
System.out.println(c.getClassLoader());
//If we print the classloader name of String, it will print null because it is an
//in-built class which is found in rt.jar, so it is loaded by Bootstrap classloader
System.out.println(String.class.getClassLoader());
}
}
Output:

sun.misc.Launcher$AppClassLoader@4e0e2f2a
null

These are the internal classloaders provided by Java. If you want to create your own classloader,
you need to extend the ClassLoader class.

2) Class(Method) Area

Class(Method) Area stores per-class structures such as the runtime constant pool, field and
method data, the code for methods.

3) Heap

It is the runtime data area in which objects are allocated.

4) Stack

Java Stack stores frames. It holds local variables and partial results, and plays a part in method
invocation and return.
Each thread has a private JVM stack, created at the same time as thread.
A new frame is created each time a method is invoked. A frame is destroyed when its method
invocation completes.

5) Program Counter Register

PC (program counter) register contains the address of the Java virtual machine instruction
currently being executed.
6) Native Method Stack

It contains all the native methods used in the application.

7) Execution Engine

It contains:

1. A virtual processor
2. Interpreter: Read bytecode stream then execute the instructions.
3. Just-In-Time(JIT) compiler: It is used to improve the performance. JIT compiles parts
of the byte code that have similar functionality at the same time, and hence reduces the
amount of time needed for compilation. Here, the term "compiler" refers to a translator
from the instruction set of a Java virtual machine (JVM) to the instruction set of a
specific CPU.

8) Java Native Interface

Java Native Interface (JNI) is a framework which provides an interface to communicate with
another application written in another language like C, C++, Assembly etc. Java uses JNI
framework to send output to the Console or interact with OS libraries.

JRE

JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The Java
Runtime Environment is a set of software tools which are used for developing Java applications.
It is used to provide the runtime environment. It is the implementation of JVM. It physically
exists. It contains a set of libraries + other files that JVM uses at runtime.
The implementation of JVM is also actively released by other companies besides Sun Micro
Systems.
JDK

JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a software
development environment which is used to develop Java applications and applets. It physically
exists. It contains JRE + development tools.
JDK is an implementation of any one of the below given Java Platforms released by Oracle
Corporation:

o Standard Edition Java Platform


o Enterprise Edition Java Platform
o Micro Edition Java Platform

The JDK contains a private Java Virtual Machine (JVM) and a few other resources such as an
interpreter/loader (java), a compiler (javac), an archiver (jar), a documentation generator
(Javadoc), etc. to complete the development of a Java Application.
1 What is a class in Java
A class is a group of objects which have common properties. It is a template or blueprint from
which objects are created. It is a logical entity. It can't be physical.

A class in Java can contain:


1. Fields
2. Methods
3. Constructors
4. Blocks
5. Nested class and interface
Type 1: Object and Class Example: main within the class
Here, we are creating a main() method inside the class.

class Student
{
int id;
String name;
public static void main(String args[])
{
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}
Save : Student.java

Compilation Flow:
When we compile Java program using javac tool, the Java compiler converts the source code into
byte code.

What happens at runtime?

At runtime, the following steps are performed:


Classloader: It is the subsystem of JVM that is used to load class files.
Bytecode Verifier: Checks the code fragments for illegal code that can violate access rights to
objects.
Interpreter: Read bytecode stream then execute the instructions.

Parameters used in First Java Program

Let's see what is the meaning of class, public, static, void, main, String[], System.out.println().

o class keyword is used to declare a class in Java.


o public keyword is an access modifier that represents visibility. It means it is visible to all.
o static is a keyword. If we declare any method as static, it is known as the static method.
The core advantage of the static method is that there is no need to create an object to
invoke the static method. The main() method is executed by the JVM, so it doesn't
require creating an object to invoke the main() method. So, it saves memory.
o void is the return type of the method. It means it doesn't return any value.
o main represents the starting point of the program.
o String[] args or String args[] is used for command line argument. We will discuss it in
coming section.
o System.out.println() is used to print statement. Here, System is a class, out is an object
of the PrintStream class, println() is a method of the PrintStream class. We will discuss
the internal working of System.out.println() statement in the coming section.
To compile: javac Student.java
To execute: java Student

Type 2: Object and Class Example: main outside the class


In this type we create classes and use it from another class. It is a better approach than previous
one. Here we are writing main() method in another class.

We can have multiple classes in different Java files or single Java file. If you define multiple
classes in a single Java source file, it is a good idea to save the file name with the class name
which has main() method.

class Student
{
int id;
String name;
}
class TestStudent1
{
public static void main(String
args[])
{
Student s1=new Student();
System.out.println(s1.id);

System.out.println(s1.name);
}
}
Save: TestStudent1.java
1 What is an object in Java
An entity that has state and behavior is known as an object. It can be physical or logical (tangible
and intangible).
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.
An object has three characteristics:

State: represents the data (value) of an object.


Behavior: represents the behavior (functionality) of an object such as deposit, withdraw, etc.
Identity: An object identity is typically implemented via a unique ID. The value of the ID is not
visible to the external user. However, it is used internally by the JVM to identify each object
uniquely.
3 Ways to initialize object
There are 3 ways to initialize object in Java.
 By reference variable
 By method
 By constructor
1) Object and Class Example: Initialization through reference
Initializing an object means storing data into the object.

class Student
{
int id;
String name;
}
class TestStudent2
{
public static void main(String args[])
{
Student s1=new Student();
s1.id=101;
s1.name="Sonoo";
System.out.println(s1.id+" "+s1.name);//printing members with a white space
}
}
Save: TestStudent2.java
2) Object and Class Example: Initialization through method
In this type, we are creating the two objects of Student class and initializing the value to these
objects by invoking the insertRecord method. Here, we are displaying the state (data) of the
objects by invoking the displayInformation() method.

class Student
{
int rollno;
String name;
void insertRecord(int r, String n)
{
rollno=r;
name=n;
}
void displayInformation()
{
System.out.println(rollno+" "+name);
}
}
class TestStudent4
{
public static void main(String args[])
{
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}
}
Save: TestStudent4.java

3) Object and Class Example: Initialization through a constructor


Data Types
 Java Is a Strongly Typed Language
 Every variable has a type, every expression has a type, and every type is strictly defined.
 All assignments, whether explicit or via parameter passing in method calls, are checked
for type compatibility.
 There are no automatic conversions of conflicting types as in some languages.
 For example, in C/C++ you can assign a floating-point value to an integer. In Java, you
cannot.
Integer Data Types
 Java does not support unsigned, positive-only integers.
 All are signed, positive and negative values.
Byte Data Type
 The smallest integer type is byte.
 Variables of type byte are especially useful while working with a stream of data from a
network or file.
 Byte variables are declared by use of the byte keyword.
Ex: byte b, c;
Floating Point Types
 There are two kinds of floating-point types.
 All math functions, such as sin( ), cos( ), and sqrt( ), return double values.
Boolean Data Type
 It can have only one of two possible values, true or false.
 This is the type, returned by all relational operators, such as a < b.
Character Data Type
 char in Java is not the same as char in C or C++.
 Java uses Unicode to represent characters.
 Unicode defines a fully international character set that can represent all of the characters
found in all human languages.
 It is a unification of dozens of character sets, such as Latin, Greek, Arabic, Cyrillic,
Hebrew, Katakana, Hangul, and many more.
 Hence it requires 16 bits.
 The range of a char in java is 0 to 65,536.
 There are no negative chars.
Data Types
Name Width in bits Range
long 64 –9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
int 32 –2,147,483,648 to 2,147,483,647
short 16 –32,768 to 32,767
byte 8 –128 to 127
double 64 4.9e–324 to 1.8e+308
float 32 1.4e−045 to 3.4e+038
char 16 0 to 65,536.
public class IntDemo
{
public static void main(String args[])
{
System.out.println(" For an Integer ");
System.out.println("Size is : "+Integer.SIZE);
int i1 = Integer.MAX_VALUE;
int i2 = Integer.MIN_VALUE ;
System.out.println("Max value is : "+i1);
System.out.println("Min Value is : "+i2);

System.out.println(" For an Byte");


System.out.println("Size is : "+Byte.SIZE);
byte b1 = Byte.MAX_VALUE;
byte b2 = Byte.MIN_VALUE ;
System.out.println("Max value is : "+b1);
System.out.println("Min Value is : "+b2);

System.out.println(" For an Short");


System.out.println("Size is : "+Short.SIZE);
short s1 = Short.MAX_VALUE;
short s2 = Short.MIN_VALUE ;
System.out.println("Max value is : "+s1);
System.out.println("Min Value is : "+s2);

System.out.println(" For an Long");


System.out.println("Size is : "+Long.SIZE);
long l1 = Long.MAX_VALUE;
long l2 = Long.MIN_VALUE ;
System.out.println("Max value is : "+l1);
System.out.println("Min Value is : "+l2);
}
}
public class FloatDemo
{
public static void main(String args[])
{
System.out.println(" For an Float");
System.out.println("Size is : "+Float.SIZE);
float f1 = Float.MAX_VALUE;
float f2 = Float.MIN_VALUE ;
System.out.println("Max value is : "+f1);
System.out.println("Min Value is : "+f2);

System.out.println(" For an Double");


System.out.println("Size is : "+Double.SIZE);
double d1 = Double.MAX_VALUE;
double d2 = Double.MIN_VALUE ;
System.out.println("Max value is : "+d1);
System.out.println("Min Value is : "+d2);
}
}
Output:
For an FloatSize is : 32
Max value is : 3.4028235E38
Min Value is : 1.4E-45
For an DoubleSize is : 64
Max value is : 1.7976931348623157E308
Min Value is :
public class CharDemo
{
public static void main(String args[]
{
System.out.println(" For a Char");
System.out.println("Size is : "+Character.SIZE);
int f1 = Character.MAX_VALUE;
long f2 = Character.MIN_VALUE ;
System.out.println("Max value is : "+f1);
System.out.println("Min Value is : "+f2);
}
}

Variables
A variable is a container which holds the value while the Java program is executed. A variable is
assigned with a data type.

Variable is a name of memory location. There are three types of variables in java: local,
instance and static.

A variable is the name of a reserved area allocated in memory. In other words, it is a name of the
memory location. It is a combination of "vary + able" which means its value can be changed.

The variable is the basic unit of storage in a Java program.

A variable is defined by the combination of an identifier, a type, and an optional initializer.

Declaring a Variable
In Java, all variables must be declared before they can be used.
type identifier [ = value][, identifier [= value] ...] ;

1) Local Variable
A variable declared inside the body of the method is called local variable. You can use this
variable only within that method and the other methods in the class aren't even aware that the
variable exists.
A local variable cannot be defined with "static" keyword.
2) Instance Variable
A variable declared inside the class but outside the body of the method, is called an instance
variable. It is not declared as static.
It is called an instance variable because its value is instance-specific and is not shared among
instances.
3) Static variable
A variable that is declared as static is called a static variable. It cannot be local. You can create a
single copy of the static variable and share it among all the instances of the class. Memory
allocation for static variables happens only once when the class is loaded in the memory.
public class A
{
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
public static void main(String args[])
{
int data=50;//instance variable
}
}

Java Type casting and Type conversion


Widening or Automatic Type Conversion
Widening conversion takes place when two data types are automatically converted. This happens
when:
When we assign value of a smaller data type to a bigger data type.
For Example, in java the numeric data types are compatible with each other but no automatic
conversion is supported from numeric type to char or boolean. Also, char and boolean are not
compatible with each other.

//Java Variable Example: Widening


public class Simple
{
public static void main(String[] args)
{
int a=10;
float f=a;
System.out.println(a);
System.out.println(f);
}
}
Narrowing or Explicit Conversion
If we want to assign a value of larger data type to a smaller data type we perform explicit type casting or
narrowing.
This is useful for incompatible data types where automatic conversion cannot be done.
Here, target-type specifies the desired type to convert the specified value to.
//Java Variable Example: Narrowing (Typecasting)
public class Simple
{
public static void main(String[] args)
{
float f=10.5f;
//int a=f;//Compile time error
int a=(int)f;
System.out.println(f);
System.out.println(a);
}
}

OPERATORS IN JAVA

Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.
There are many types of operators in Java which are given below:

o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.

Java Operator Precedence


Operator Category Precedence
Type

Unary postfix expr++ expr--

prefix ++expr --expr +expr -expr ~ !

Arithmetic multiplicative */%

additive +-

Shift shift << >> >>>


Relational comparison < > <= >= instanceof

equality == !=

Bitwise bitwise AND &

bitwise ^
exclusive OR

bitwise |
inclusive OR

Logical logical AND &&

logical OR ||

Ternary ternary ?:

Assignment assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=

Java Control Statements


Java compiler executes the code from top to bottom. The statements in the code are executed
according to the order in which they appear. Java provides statements that can be used to control
the flow of Java code. Such statements are called control flow statements. It is one of the
fundamental features of Java, which provides a smooth flow of program.

Java provides three types of control flow statements.

Decision Making statements


if statements
switch statement
Loop statements
do while loop
while loop
for loop
for-each loop
Jump statements
break statement
continue statement

Decision-Making statements:
As the name suggests, decision-making statements decide which statement to execute and when.
Decision-making statements evaluate the Boolean expression and control the program flow
depending upon the result of the condition provided. There are two types of decision-making
statements in Java, i.e., If statement and switch statement.

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. In Java, there are four types of if-statements

Simple if statement
if-else statement
if-else-if ladder
Nested if-statement
Let's understand the if-statements one by one.

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.

if(condition)
{
statement 1; //executes when condition is true
}

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.

if(condition)
{
statement 1; //executes when condition is true
}
else{
statement 2; //executes when condition is 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.
if(condition 1)
{
statement 1; //executes when condition 1 is true
}
else
{
if(condition 2)
{
statement 2; //executes when condition 2 is true
}
else
{
if(condition 2)
{
statement 2; //executes when condition 2 is true
}
else
{
statement 2; //executes when all the conditions are false
}
}
}
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.

if(condition 1)
{
statement 1; //executes when condition 1 is true
if(condition 2)
{
statement 2; //executes when condition 2 is true
}
else
{
statement 2; //executes when condition 2 is false
}
}
Switch Statement:
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.
*Note:
1. The case variables can be int, short, byte, char, or enumeration. String type is also supported
since version 7 of Java
2. Cases cannot be duplicate
3. Default statement is executed when any of the case doesn't match the value of expression. It is
optional.
4. Break statement terminates the switch block when the condition is satisfied. It is optional, if
not used, next case is executed.
5. 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.
switch (expression)
{
case value1:
statement1;
break;
case value2:
statement2;
break;

.
.
.
case valueN:
statementN;
break;
default:
default statement;
}

Loop Statements

if 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.
Loops are three types , They are
1. for loop

2. while loop
3. do-while loop

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.
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.
for(initialization, condition, increment/decrement)
{
//block of statements}
}
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.
Initialization
while(condition)
{
//looping statements
increment/decrement
}

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.
Initialization;
do
{
//statements
increment/decrement;
} while (condition);
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.

1. break statement
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.

The break statement example with for loop

BreakExample.java
public class BreakExample
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
for(int i = 0; i<= 10; i++)
{
System.out.println(i);
if(i==6)
{
break;
}
}
}
}

Output:
0
1
2
3
4
5
6
2 Continue 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.
public class ContinueExample
{
public static void main(String[] args)
{
// TODO Auto-generated method stub

for (int j = i; j<=5; j++)


{
if(j == 4) {
continue;
}
System.out.println(j);
}

}
}

Output:

0
1
2
3
5
Enums

An enum is a special "class" that represents a group of constants (unchangeable variables, like
final variables).

Enum in java is a data type that contains fixed set of constants.

Java Enums can be thought of as classes which have a fixed set of constants (a variable that does
not change). The Java enum constants are static and final implicitly. It is available since JDK 1.5.

Enums are used to create our own data type like classes. The enum data type (also known as
Enumerated Data Type) is used to define an enum in Java. Unlike C/C++, enum in Java is more
powerful. Here, we can define an enum either inside the class or outside the class.

Java Enum internally inherits the Enum class, so it cannot inherit any other class, but it can
implement many interfaces. We can have fields, constructors, methods, and main methods in
Java enum.

 Enum improves type safety


 Enum can be easily used in switch
 Enum can be traversed
 Enum can have fields, constructors and methods
 Enum may implement many interfaces but cannot extend any class because it internally
extends Enum class

enum Level {
LOW,
MEDIUM,
HIGH
}
access enum constants with the dot syntax:
Level myVar = Level.MEDIUM;

Example 1:
class EnumExample1{
//defining the enum inside the class
public enum Season { WINTER, SPRING, SUMMER, FALL }
//main method
public static void main(String[] args) {
//traversing the enum
for (Season s : Season.values())
System.out.println(s);
}}
Output:
WINTER
SPRING
SUMMER
FALL
Example 2
class EnumExample1{
//defining enum within class
public enum Season { WINTER, SPRING, SUMMER, FALL }
//creating the main method
public static void main(String[] args) {
//printing all enum
for (Season s : Season.values()){
System.out.println(s);
}
System.out.println("Value of WINTER is: "+Season.valueOf("WINTER"));
System.out.println("Index of WINTER is: "+Season.valueOf("WINTER").ordinal());
System.out.println("Index of SUMMER is: "+Season.valueOf("SUMMER").ordinal());

}}
Output:
WINTER
SPRING
SUMMER
FALL
Value of WINTER is: WINTER
Index of WINTER is: 0
Index of SUMMER is: 2
Example 3:
enum Level {
LOW,
MEDIUM,
HIGH
}

public class Main {


public static void main(String[] args) {
Level myVar = Level.MEDIUM;

switch(myVar) {
case LOW:
System.out.println("Low level");
break;
case MEDIUM:
System.out.println("Medium level");
break;
case HIGH:
System.out.println("High level");
break;
}
}
}
Output:
Medium level

Wrapper classes in Java


The wrapper class in Java provides the mechanism to convert primitive into object and object
into primitive.

Since J2SE 5.0, autoboxing and unboxing feature convert primitives into objects and objects into
primitives automatically. The automatic conversion of primitive into an object is known as
autoboxing and vice-versa unboxing.

Use of Wrapper classes in Java


Java is an object-oriented programming language, so we need to deal with objects many times
like in Collections, Serialization, Synchronization, etc. Let us see the different scenarios, where
we need to use the wrapper classes.

Change the value in Method: Java supports only call by value. So, if we pass a primitive value, it
will not change the original value. But, if we convert the primitive value in an object, it will
change the original value.
Serialization: We need to convert the objects into streams to perform the serialization. If we
have a primitive value, we can convert it in objects through the wrapper classes.

Synchronization: Java synchronization works with objects in Multithreading.


java.util package: The java.util package provides the utility classes to deal with objects.

Collection Framework: Java collection framework works with objects only. All classes of the
collection framework (ArrayList, LinkedList, Vector, HashSet, LinkedHashSet, TreeSet,
PriorityQueue, ArrayDeque, etc.) deal with objects only.

The eight classes of the java.lang package are known as wrapper classes in Java. The list of eight
wrapper classes are given below:

Primitive Type Wrapper class


boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
Autoboxing
The automatic conversion of primitive data type into its corresponding wrapper class is known as
autoboxing.

Since Java 5, we do not need to use the valueOf() method of wrapper classes to convert the
primitive into objects.

Wrapper class Example: Primitive to Wrapper

public class WrapperExample1


{
public static void main(String args[])
{
//Converting int into Integer
int a=20;
Integer i=Integer.valueOf(a);//converting int into Integer explicitly
Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internally
System.out.println(a+" "+i+" "+j);
}
}
Output:
20 20 20

Primitive Type Wrapper class


boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double

Unboxing
The automatic conversion of wrapper type into its corresponding primitive type is known as
unboxing. It is the reverse process of autoboxing. Since Java 5, we do not need to use the
intValue() method of wrapper classes to convert the wrapper type into primitives.

Wrapper class Example: Wrapper to Primitive


//Java program to convert object into primitives
//Unboxing example of Integer to int
public class WrapperExample2{
public static void main(String args[]){
//Converting Integer to int
Integer a=new Integer(3);
int i=a.intValue();//converting Integer to int explicitly
int j=a;//unboxing, now compiler will write a.intValue() internally

System.out.println(a+" "+i+" "+j);


}}
Output:
333

Java User Input


The Scanner class is used to get user input, and it is found in the java.util package.
To use the Scanner class, create an object of the class and use any of the available methods found
in the Scanner class documentation.
In our example, we will use the nextLine() method, which is used to read Strings:
Input Types
In the example above, we used the nextLine() method, which is used to read Strings. To read
other types, look at the table below:

Method Description

nextBoolean() Reads a boolean value from the user

nextByte() Reads a byte value from the user

nextDouble() Reads a double value from the user

nextFloat() Reads a float value from the user

nextInt() Reads a int value from the user


nextLine() Reads a String value from the user

nextLong() Reads a long value from the user

nextShort() Reads a short value from the user

import java.util.Scanner; // Import the Scanner class

class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); // Create a Scanner object

System.out.println("Enter username");
String userName = myObj.nextLine(); // Read user input
System.out.println("Username is: " + userName); // Output user input
}
}

import java.util.Scanner;

class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);

System.out.println("Enter name, age and salary:");

// String input
String name = myObj.nextLine();

// Numerical input
int age = myObj.nextInt();
double salary = myObj.nextDouble();
// Output input by user
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Salary: " + salary);
}
}
Program to add two non-integer numbers
import java.util.Scanner;
public class JavaExample
{
public static void main(String[] args)
{
double num1, num2, sum;
Scanner sc = new Scanner(System.in);
System.out.print("Enter First Number: ");
num1 = sc.nextDouble();

System.out.print("Enter Second Number: ");


num2 = sc.nextDouble();

sc.close();
sum = num1 + num2;
System.out.println("Sum of "+num1+" and "+num2+" is: "+sum);
}
}
Java Console Class
The Java Console class is be used to get input from console. It provides methods to read texts
and passwords.
If you read password using Console class, it will not be displayed to the user.

The java.io.Console class is attached with system console internally. The Console class is
introduced since 1.5.
String text=System.console().readLine();
System.out.println("Text is: "+text);

Java Console class methods

Method Description

Reader reader() It is used to retrieve the reader object associated with the console

String readLine() It is used to read a single line of text from the console.

char[] readPassword() It is used to read password that is not being displayed on the
console.

Console format(String fmt, It is used to write a formatted string to the console output stream.
Object... args)

Console printf(String format, It is used to write a string to the console output stream.
Object... args)

PrintWriter writer() It is used to retrieve the PrintWriter object associated with the
console.

void flush() It is used to flushes the console.


How to get the object of Console

import java.io.Console;
class ReadStringTest
{
public static void main(String args[])
{
Console c=System.console();

System.out.println("Enter your name: ");


String n=c.readLine();
System.out.println("Welcome "+n);
}
}
Output

Enter your name: Nakul Jain


Welcome Nakul Jain

Java Console Example to read password


import java.io.Console;
class ReadPasswordTest
{
public static void main(String args[])
{
Console c=System.console();

System.out.println("Enter password: ");


char[] ch=c.readPassword();
String pass=String.valueOf(ch);//converting char array into string

System.out.println("Password is: "+pass);


}
}
Output
Enter password:
Password is: 123

Java Dates
Java does not have a built-in Date class, but we can import the java.time package to work with
the date and time API. The package includes many date and time classes. For example:

Class Description
LocalDate Represents a date (year, month, day (yyyy-MM-dd))

LocalTime Represents a time (hour, minute, second and nanoseconds (HH-mm-


ss-ns))

LocalDateTime Represents both a date and a time (yyyy-MM-dd-HH-mm-ss-ns)

DateTimeFormatter Formatter for displaying and parsing date-time objects

Display Current Date


To display the current date, import the java.time.LocalDate class, and use its now() method:

import java.time.LocalDate; // import the LocalDate class


public class Main {
public static void main(String[] args) {
LocalDate myObj = LocalDate.now(); // Create a date object
System.out.println(myObj); // Display the current date
}
}

Display Current Time


To display the current time (hour, minute, second, and nanoseconds), import the
java.time.LocalTime class, and use its now() method:

import java.time.LocalTime; // import the LocalTime class


public class Main {
public static void main(String[] args) {
LocalTime myObj = LocalTime.now();
System.out.println(myObj);
}
}
JAVA ARRAY
An array is a collection of similar type of elements which has contiguous memory location.

Java array is an object which contains elements of a similar data type. Additionally, The
elements of an array are stored in a contiguous memory location. It is a data structure where we
store similar elements. We can store only a fixed set of elements in a Java array.

Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element
is stored on 1st index and so on.

Unlike C/C++, we can get the length of the array using the length member. In C/C++, we need to
use the sizeof operator.

Advantages
Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
Random access: We can get any data located at an index position.
Disadvantages
Size Limit: We can store only the 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 which grows automatically.

Types of Array in java


There are two types of array.

Single Dimensional Array


Multidimensional Array
Single Dimensional Array in Java
Syntax to Declare an Array in Java

dataType[] arr; (or)


dataType []arr; (or)
dataType arr[];

Instantiation of an Array in Java


arrayRefVar=new datatype[size];

Example we are going to declare, instantiate, initialize and traverse an array.

class Testarray
{
public static void main(String args[])
{
int a[]=new int[5];//declaration and instantiation

a[0]=10;//initialization
a[1]=20;
a[2]=70;
a[3]=40;
a[4]=50;

//traversing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}
}

Declaration, Instantiation and Initialization of Java Array


We can declare, instantiate and initialize the java array together by:

int a[]={33,3,4,5};//declaration, instantiation and initialization

class Testarray1{
public static void main(String args[]){
int a[]={33,3,4,5};//declaration, instantiation and initialization
//printing array
for(int i=0;i<a.length;i++)//length is the property of array
System.out.println(a[i]);
}}
Output:
33
3
4
5
For-each Loop for Java Array
We can also print the Java array using for-each loop. The Java for-each loop prints the array
elements one by one. It holds an array element in a variable, then executes the body of the loop.

syntax:

for(data_type variable:array){
//body of the loop
}

class Testarray1{
public static void main(String args[]){
int arr[]={33,3,4,5};
//printing array using for-each loop
for(int i:arr)
System.out.println(i);
}}
Output:
33
3
4
5

Passing Array to a Method in Java


We can pass the java array to method so that we can reuse the same logic on any array.

class Testarray2{
//creating a method which receives an array as a parameter
static void min(int arr[]){
int min=arr[0];
for(int i=1;i<arr.length;i++)
if(min>arr[i])
min=arr[i];
System.out.println(min);
}

public static void main(String args[]){


int a[]={33,3,4,5};//declaring and initializing an array
min(a);//passing array to method
}}
Output:
3

Anonymous Array in Java


Java supports the feature of an anonymous array, so you don't need to declare the array while
passing an array to the method.
public class TestAnonymousArray{
//creating a method which receives an array as a parameter
static void printArray(int arr[]){
for(int i=0;i<arr.length;i++)
System.out.println(arr[i]);
}

public static void main(String args[]){


printArray(new int[]{10,22,44,66});//passing anonymous array to method
}}
Test it Now
Output:

10
22
44
66

Returning Array from the Method


We can also return an array from the method in Java.

//Java Program to return an array from the method


class TestReturnArray{
//creating method which returns an array
static int[] get(){
return new int[]{10,30,50,90,60};
}

public static void main(String args[]){


//calling method which returns an array
int arr[]=get();
//printing the values of an array
for(int i=0;i<arr.length;i++)
System.out.println(arr[i]);
}}
Output:
10
30
50
90
60

ArrayIndexOutOfBoundsException
The Java Virtual Machine (JVM) throws an ArrayIndexOutOfBoundsException if length of the
array in negative, equal to the array size or greater than the array size while traversing the array.
public class TestArrayException{
public static void main(String args[]){
int arr[]={50,60,70,80};
for(int i=0;i<=arr.length;i++){
System.out.println(arr[i]);
}
}}
Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at TestArrayException.main(TestArrayException.java:5)
50
60
70
80

Multidimensional Arrays
In Java, multidimensional arrays are actually arrays of arrays. These, as you mightexpect, look
and act like regular multidimensional arrays. However, as you will see there are a couple of
subtle differences. To declare a multidimensional array variable,specify each additional index
using another set of square brackets. For example, the following declares a two-dimensional
array variable called twoD.
int twoD[][] = new int[4][5];

This allocates a 4 by 5 array and assigns it to twoD. Internally this matrix is implemented as an
array of arrays of int.
// Demonstrate a two-dimensional array.

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


{
int twoD[][]= new int[4][5];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<5; j++) output:
{ 01234
twoD[i][j] = k; k++; 56789
} 10 11 12 13 14
15 16 17 18 19
for(i=0; i<4; i++)
{
for(j=0; j<5; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}
Method Overloading
Ex1
class OverloadDemo
{
void test()
{
System.out.println("No parameters");
}

// Overload test for one integer parameter.


void test(int a)
{
System.out.println("a: " + a);
}

// Overload test for two integer parameters.


void test(int a, int b)
{
System.out.println("a and b: " + a + " " + b);
}

// Overload test for a double parameter


double test(double a)
{
System.out.println("double a: " + a); return a*a;
}

class Overload {
public static void main(String args[])
{
OverloadDemo ob = new OverloadDemo();
double result;
// call all versions of test()
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): " + result);
}
}
Ex2
class OverloadDemo
{
void test()
{
int a=5,b=6,c;
c=a+b;
System.out.println("No parameters "+c+"\n");
}

// Overload test for one iint nteger parameter.


void test(int a, int b)
{
int c=a+b;
System.out.println("a+b " + c+"\n");
}

// Overload test for two integer parameters.


void test(int a, int b, int c)
{
System.out.println("a+b+c " + c);
}

class Overload {
public static void main(String args[])
{
OverloadDemo ob = new OverloadDemo();

// call all versions of test()


ob.test();
ob.test(10, 20);
ob.test(10,20,30);

}
}
Constructor overloading
Ex1
class Box {
double width; double height; double depth;
// This is the constructor for Box.
Box()
{
width = -1;
height = -1;
depth = -1;
}

// This is the constructor for Box.


Box(double w, double h, double d)
{
width = w; height = h; depth = d;
}

// compute and return volume


double volume()
{
return width * height * depth;
}

}
class BoxDemo
{
public static void main(String args[])
{
// declare, allocate, and initialize Box objects
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
double vol;

// get volume of first box


vol = mybox1.volume();
System.out.println("Volume is " + vol);

// get volume of second box


vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
Ex2
class HelloWorld {
int sno;
String sname;
HelloWorld(int sno,String sname)
{
this.sno=sno;
this.sname=sname;
}
public static void main(String[] args)
{
HelloWorld h=new HelloWorld(10,"ABC");
System.out.println(h.sno+" "+h.sname);

HelloWorld h1=new HelloWorld(11,"AddC");


System.out.println(h1.sno+" "+h1.sname);
}
}
Argument Passing Techniques
1. Call by Value
class Test
{
void meth(int i, int j)
{
i *= 2;
j /= 2;
}
}
class CallByValue
{
public static void main(String args[])
{
Test ob = new Test();
int a = 15, b = 20;
System.out.println("a and b before call: " + a + " " + b); ob.meth(a, b);
System.out.println("a and b after call: " + a + " " + b);
}
}

Call by reference means we call a method by passing reference (location of the variable) in a
parameter. In Java, primitive data types (Int, float, double, Boolean, char, etc.) are always passed
as values and Non-Primitive data types (class, object, array, string, and interface) are always
passed as a reference.

2. Call by Reference
Ex1
class CaRef
{
int data=50;
void change(CaRef op)
{
op.data=op.data+100;//changes will be in the instance variable
}
public static void main(String args[])
{
CaRef op=new CaRef ();
System.out.println("before change "+op.data);
op.change(op);//passing object
System.out.println("after change "+op.data);
}
}
Ex2
class Test {
int a, b;
Test(int i, int j) {
a = i; b = j;
}
// pass an object
void meth(Test o)
{
o.a*= 2;
o.b/= 2;
}
}
class PassObjRef {
public static void main(String args[])
{
Test ob = new Test(15, 20);
System.out.println("ob.a and ob.b before call: " + ob.a + " " + ob.b); ob.meth(ob);
System.out.println("ob.a and ob.b after call: " + ob.a + " " + ob.b);
}
}
Recursive Ex1
➢ Java supports recursion.
➢ Recursion is the process of defining something in terms of itself.
➢ A method that calls itself is said to be recursive.
➢ When a method calls itself, new local variables and parameters are allocated storage on the
stack, and the method code is executed with these new variables from the start.
➢ As each recursive call returns, the old local variables and parameters are removed from the
stack.
➢ The main advantage to recursive methods is that they can be used to create clearer and simpler
versions of several algorithms than can their iterative relatives. Ex: QuickSort and AI related
problems
➢ When writing recursive methods, we must have an if statement somewhere to force the
method to return without the recursive call being executed.
➢ Recursive versions of many routines may execute a bit more slowly than the iterative
equivalent because of the added overhead of the additional method calls.

class Factorial
{
// this is a recursive method
int fact(int n)
{
int fact;
if(n==1)
return 1;
else
{
fact = fact(n-1) * n;
return fact;
}
}
}

class Recursion
{
public static void main(String args[])
{
Factorial f = new Factorial();
System.out.println("Factorial of 3 is " + f.fact(3));
System.out.println("Factorial of 4 is " + f.fact(4));
System.out.println("Factorial of 5 is " + f.fact(5));
}
}
ACCESS CONTROL METHODS / ACCESS MODIFIERS IN JAVA

There are two types of modifiers in Java: access modifiers and non-access modifiers.

The access modifiers in Java specifies the accessibility or scope of a field, method, constructor,
or class. We can change the access level of fields, constructors, methods, and class by applying
the access modifier on it.

There are four types of Java access modifiers:

Private: The access level of a private modifier is only within the class. It cannot be accessed
from outside the class.

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.

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.

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.

There are many non-access modifiers, such as static, abstract, synchronized, native, volatile,
transient, etc.

Access within within outside package outside


Modifier class package by subclass only package

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y
1) Private access modifier is accessible only within the class.

class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}

public class Simple{


public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}

In the above program


we have created two classes A and Simple.
A class contains private data member and private method.
We are accessing these private members from outside the class, so there is a
compile-time error.
2) Default: The default modifier is accessible only within package. It cannot
be accessed from outside the package. It provides more accessibility than
private. But, it is more restrictive than protected, and public.

//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}

//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}

In the above example, we created two packages pack and mypack.


We are accessing the A class from outside its package, since A class is not public, so it cannot be
accessed from outside the package.
3) Protected
The protected access modifier is accessible within package and outside the package but
through inheritance only.

The protected access modifier can be applied on the data member, method and
constructor. It can't be applied on the class.

It provides more accessibility than the default modifer.

//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}

//save by B.java
package mypack;
import pack.*;

class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}

In the above example, we created the two packages pack and mypack. The A class of pack
package is public, so can be accessed from outside the package. But msg method of this package
is declared as protected, so it can be accessed from outside the class only through inheritance.
4) Public The public access modifier is accessible everywhere. It has the widest scope
among all other modifiers.
//save by A.java

package pack;
public class A{
public void msg(){System.out.println("Hello");}
}

//save by B.java
package mypack;
import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
This Reference
*this keyword
this always refers to the currently executing object.
There are two uses with the this keyword.

1. To resolve the name collisions between instance variables and local variables
2. To explicitly call a constructor from another constructor

1. Instance Variable Hiding


To resolve the name collisions between instance variables and local variables
a) when a local variable has the same name as an instance variable, the local variable hides the
instance variable.
b) To resolve this name conflicts, we use this.

class HelloWorld
{
int sno;
String sname;
HelloWorld(int sno,String sname)
{
this.sno=sno;
this.sname=sname;
}
public static void main(String[] args)
{
HelloWorld h=new HelloWorld(10,"ABC");
System.out.println(h.sno+" "+h.sname);

HelloWorld h1=new HelloWorld(11,"AddC");


System.out.println(h1.sno+" "+h1.sname);
}
}
2. To explicitly call a constructor from another constructor

a) We can use this to call a constructor from another constructor. This is called a Explicit
constructor invocation.
b) this() should be the first statement inside a constructor.

class Box
{
double width; double height; double depth;
Box()
{
System.out.println("Defualt constructor");
}
// This is the constructor for Box.
Box(double w,double h, double d)
{
// calling default constructor this();
System.out.println("Constructing Box"); width = 10;
height = 10;
depth = 10;
}
}
Garbage Collection
➢ In Java, objects are allocated memory dynamically using new operator. But memory de-
allocation happens automatically.
➢ In Java, Garbage collection is the technique through which the memory de-allocation will
happen automatically.
Working of Garbage Collection
a) The job of the Garbage collector is to identify the unused objects and delete them from
memory.
b) Garbage collector checks the objects which do not have any reference and deletes them from
memory.
c) Garbage collector runs periodically during the program execution. But there is no guarantee
when a Garbage collector runs.
d) The garbage collector runs periodically, checking for objects that are no longer referenced by
any running state or indirectly through other referenced objects.
e) Garbage collector calls finalize( ) method just before it runs.
gc() method
1. The gc() method is used to invoke the garbage collector to perform cleanup processing.
2. The gc() is found in System and Runtime classes.
public static void gc(){ }
Example
public class MemoryTest
{
public static void main(String args[])
{
Runtime r=Runtime.getRuntime();
System.out.println("Total Memory: "+r.totalMemory());
System.out.println("Free Memory: "+r.freeMemory());
for(int i=0;i<100;i++)
{
new MemoryTest();
}
System.out.println("After creating 100 instance, Free Memory: "+r.freeMemory());
System.gc();
System.out.println("After gc(), Free Memory: "+r.freeMemory());
}
}
finalize( ) method / finalization
a) By using finalize() method or finalization, we can define specific actions that will occur when
an object is just about reclaimed by the Garbage collector.
b) To add a finalizer to a class, we simply define the finalize( ) method. The Java run time calls
that method whenever it is about to recycle an object of that class.
c) Inside the finalize( ) method, you will specify those actions that must be performed before an
object is destroyed.
The finalize( ) method has this general form:
protected void finalize( )
{
// finalization code here
}
Static
Static is used to access a member by itself, without reference to a specific instance. When a
member is declared static, it can be accessed before any objects of its class are created, and
without reference to any object.
Things can be declared as static
1. Variables
2. Methods
3. Static blocks
4. Nested classes
Things cannot be declared as static
1. Local variables
2. classes
3. constructor
static variables (class variables)
➢ Instance variables declared as static are, essentially, global variables.
➢ When objects of its class are declared, no copy of a static variable is made.
➢ Instead, all instances of the class share the same static variable.
static methods
Methods declared as static have several restrictions:
➢ They can only directly call other static methods.
➢ They can only directly access static data.
➢ They cannot refer to this or super in any way.
Static blocks (OR) static initialization block
➢ Static blocks are used to initialize the static variables.
➢ Static block gets executed exactly once, when the class is first loaded.
// Demonstrate static variables, methods, and blocks.

class UseStatic Order:


{ Static variables
static int a = 3; Static blocks
static int b; Static methods (first main()
static void meth(int x) then other methods)
{
System.out.println("x = " + x);
System.out.println("a = " + a);
System.out.println("b = " + b);
} Output:
static Inside the same class, we can access
{ static members directly
System.out.println("Static block initialized.");
b = a * 4; Outside the class, we can access the
} static members, using the format:
public static void main(String args[]) { meth(42);
} Classname.variable
} Classname.method( )
Nested and Inner classes
Defining a class inside another class is known as nested class.
Nested classes are 4 types in Java :
1. Inner class (Non-static Nested class)
2. Method-Local Inner class
3. Static Nested class
4. Anonymous Inner class

1. Inner class
➢An inner class is a non-static nested class.
➢It has access to all of the variables and methods of its outer class, including private members
➢We can create an instance of an Inner class only through the object of the outer class.

// Demonstrate Inner class.


class Outer
{
private int x = 7;
class Inner{ void meth()
{
System.out.println("x = " + x);
}
}
public static void main(String args[])
{
Outer ou = new Outer();
Outer.Inner in = ou.new Inner();
in.meth();
}
}
2. Method-Local Inner class
➢We can define a nested class inside a method or any block scope (loops).
➢We must create the instance of the inner class somewhere inside the method but after the
inner class definition.

// Demonstrate method-local nested class.


class Outer
{
void display()
{
class Nest{
void meth()
{
System.out.println("Hello");
}
}
Nest in = new Nest(); in.meth();
}
public static void main(String args[]) { Outer ou = new Outer(); ou.display();
}
}
3. Static Nested class
A static nested class is one that has the static modifier applied.
// Demonstrate Static Nested class.
class Outer {
private int x = 7;
static class Inner{ void meth() {
System.out.println("x = " + x);
}
}
public static void main(String args[]) { Inner in = new Inner(); in.meth();
}
}
with static variable without static variable
Java static property is shared to all objects. EX1:
class Student{
Example of static variable int rollno;//instance variable
//Java Program to demonstrate the use of static String name;
variable String college ="ITS";//static variable
class Student{ //constructor
int rollno;//instance variable Student(int r, String n)
String name; {
static String college ="ITS";//static variable rollno = r;
//constructor name = n;
Student(int r, String n) }
{ //method to display the values
rollno = r; void display ()
name = n; {
} System.out.println(rollno+" "+name+"
//method to display the values "+college);
void display () }
{ }
System.out.println(rollno+" "+name+" //Test class to show the values of objects
"+college); class TestStaticVariable1
} {
} public static void main(String args[])
//Test class to show the values of objects {
public class TestStaticVariable1 Student s1 = new Student(111,"Karan");
{ Student s2 = new Student(222,"Aryan");
public static void main(String args[]) //we can change the college of all objects by
{ the single line of code
Student s1 = new Student(111,"Karan"); //Student.college="VBIT";
Student s2 = new Student(222,"Aryan"); s1.display();
//we can change the college of all objects by s2.display();
the single line of code }
//Student.college="VBIT"; }
s1.display();
s2.display();
}
}
Ex2: Ex2:
//Java Program to illustrate the use of static class Counter{
variable which int count=0;//will get memory each time when
//is shared with all objects. the instance is created
class Counter2{ Counter(){
static int count=0;//will get memory only once count++;//incrementing value
and retain its value System.out.println(count);
}
Counter2(){ public static void main(String args[]){
count++;//incrementing the value of static //Creating objects
variable Counter c1=new Counter();
System.out.println(count); Counter c2=new Counter();
} Counter c3=new Counter();
public static void main(String args[]){ }
//creating objects }
Counter2 c1=new Counter2();
Counter2 c2=new Counter2();
Counter2 c3=new Counter2();
}
}
Ex3:
class A{
static int a=40;//non static Ex3:
class A{
public static void main(String args[]){ static int a=40;//non static
System.out.println(a);
} public static void main(String args[]){
} System.out.println(a);
Output: 40 }
Ex 3: }
public class Main { Output: System.out.println(a);
// static variable ^
static int age; 1 error
// static method
static void display() {
System.out.println("Static Method");
}
public static void main(String[] args) {

// access the static variable


age = 30;
System.out.println("Age is " + age);

// access the static method


display();
}
}
Ex 4: From JDK onwards without main
method
class A3{
static{
System.out.println("static block is invoked");
System.exit(0);
}
}
String class
Java API defines String as a class
Two important things about Strings
1. For every string, Java creates an object of type String. Even string constants are actually String
objects.
2. String objects are immutable.
Creation of Strings / Construction of Strings
String are created many ways, but the easiest are two ways :
1) Without new operator String s = “Java”;
2) With new operator
String s = new String(“Java”);
Difference Between the above two ways (OR) Important facts about String and Memory
➢ When a String is created using without new operator, then the string object will be created
inside the separate memory called “String Constant pool”.
➢ When a String is created using new operator, then the string object will be created both heap
memory and inside “String Constant pool”. But the heap memory copy will be referred by the
reference variable.
➢ When creating a string in String constant pool, JVM first checks the pool to see if there is a
similar string exists or not. If exists, no new string will be created, existing one will be reused. If
string does not exist, then JVM will create a new one.
Immutability:
Once a string is created, its contents cannot be altered.
String s = “Java”;
String s1 = new String(“Java”); String s2 = “Java”;
String s3 = new String(“Java”);

String Methods
Important methods in the String class
1. charAt() Returns the character located at the specified index
2. concat() Appends one String to the end of another ( "+" also works)
3. equalsIgnoreCase() Determines the equality of two Strings, ignoring case
4. length() Returns the number of characters in a String
5. replace() Replaces occurrences of a character with a new character
6. substring() Returns a part of a String
7. toLowerCase() Returns a String with uppercase characters converted
8. toString() Returns the value of a String
9. toUpperCase() Returns a String with lowercase characters converted
10. trim() Removes whitespace from the ends of a String
1. public char charAt(int index)
String x = “CARGO";
System.out.println( x.charAt(2) ); Output is : R
2. public String concat(String s)
String x = "taxi";
System.out.println( x.concat(" cab") ); Output is : taxi cab

+ and += operators
String x = "library";
System.out.println( x + " card"); Output is : library card

String x = "Atlantic"; x+= " ocean";


System.out.println( x ); Output is : Atlantic ocean
3. public boolean equals(Object anObject)
Compares this string to the specified object. The result is true if and only if the argument is not
null and is a String object that represents the same sequence of characters as this object.
String x = "Exit";
System.out.println( x.equals("EXIT")); Output is: false
String x = "Exit";
System.out.println( x.equals("Exit")); Output is: true
4. public boolean equalsIgnoreCase(String s)
This is similar to equals() method and it will return true even when characters in the String
objects being compared have differing cases.
String x = "Exit";
System.out.println( x.equalsIgnoreCase("EXIT")); Output is: true
5. public int length()
String x = "01234567";
System.out.println( x.length() ); Output is: 8
6. public String replace(char old, char new)
String x = "oxoxoxox";
System.out.println( x.replace('x', 'X') ); Output is: oXoXoXoX
7. public String substring(int begin)
String x = "0123456789";
System.out.println( x.substring(5) ); Output is: 56789
8. public String substring(int begin, int end)
String x = "0123456789";
System.out.println( x.substring(5, 8)); Output is: 567
9. public String toLowerCase()
String x = "A New Moon";
System.out.println( x.toLowerCase() ); Output is: a new moon
10. public String toUpperCase()
String x = "A New Moon";
System.out.println( x.toUpperCase() ); Output is: A NEW MOON
11. public String trim()
String x = " hi ";
System.out.println( x.trim()); Output is: hi
12. public String toString()
All objects in Java must have a toString() method, which typically returns a String that in some
meaningful way describes the object in question.
String x = "big surprise";
System.out.println( x.toString() ); Output is: big surprise

Write a Java program to demonstrate String class and its methods


// Demonstrating some String methods.
class StringDemo {
public static void main(String args[]) { String strOb1 = "First String"; String strOb2 = "Second
String"; String strOb3 = strOb1;
System.out.println("Length of strOb1: " +strOb1.length());
System.out.println("Char at index 3 in strOb1: " +strOb1.charAt(3));

if(strOb1.equals(strOb2))
System.out.println("strOb1 == strOb2");
else
System.out.println("strOb1 != strOb2");

if(strOb1.equals(strOb3)) System.out.println("strOb1 == strOb3");


else
System.out.println("strOb1 != strOb3");
}
}
String arrays
We can have arrays of strings, just like we can have arrays of any other type of object.
// Demonstrate String arrays.
class StringDemo {
public static void main(String args[])
{
String str[] = { "one", "two", "three" };
for(int i=0; i<str.length; i++)
System.out.println(str[i]);
}
}
Immutability
class HelloWorld {
public static void main(String[] args) {
String s=new String("Hello");
s.concat(" VBIT");
System.out.println(s); }}
class HelloWorld { class HelloWorld {
public static void main(String[] public static void main(String[]
args) { args) {
String s="Hello"; String s=new String("Hello");
String s1="Hello"; String s1= new
System.out.println(s==s1); String("Hello");
} System.out.println(s==s1);
} }
}
Java StringBuffer Class
Java StringBuffer class is used to create mutable (modifiable) String objects. The StringBuffer
class in Java is the same as String class except it is mutable i.e. it can be changed.

Constructor Description

StringBuffer() It creates an empty String buffer with the initial


capacity of 16.

StringBuffer(String It creates a String buffer with the specified string..


str)

StringBuffer(int It creates an empty String buffer with the specified


capacity) capacity as length.

Important methods of StringBuffer class A String that can be modified or changed is


known as mutable String. StringBuffer and StringBuilder classes are used for creating
mutable strings.

Modifier and Method Description


Type

public append(String s) It is used to append the specified string


synchronized with this string. The append() method is
StringBuffer overloaded like append(char),
append(boolean), append(int),
append(float), append(double) etc.

public insert(int offset, It is used to insert the specified string


synchronized String s) with this string at the specified position.
StringBuffer The insert() method is overloaded like
insert(int, char), insert(int, boolean),
insert(int, int), insert(int, float),
insert(int, double) etc.

public replace(int It is used to replace the string from


synchronized startIndex, int specified startIndex and endIndex.
StringBuffer endIndex, String
str)

public delete(int It is used to delete the string from


synchronized startIndex, int specified startIndex and endIndex.
StringBuffer endIndex)
public reverse() is used to reverse the string.
synchronized
StringBuffer

public int capacity() It is used to return the current capacity.

public void ensureCapacity(int It is used to ensure the capacity at least


minimumCapacity) equal to the given minimum.

public char charAt(int index) It is used to return the character at the


specified position.

public int length() It is used to return the length of the


string i.e. total number of characters.

public String substring(int It is used to return the substring from


beginIndex) the specified beginIndex.

public String substring(int It is used to return the substring from


beginIndex, int the specified beginIndex and endIndex.
endIndex)

1) StringBuffer Class append() Method


The append() method concatenates the given argument with this String.
class StringBufferExample
{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java"); //now original string is changed
System.out.println(sb);//prints Hello Java
}
}
2) StringBuffer insert() Method
The insert() method inserts the given String with this string at the given position.
class StringBufferExample2
{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.insert(1,"Java");//now original string is changed
System.out.println(sb);//prints HJavaello
}
}
3) StringBuffer replace() Method
The replace() method replaces the given String from the specified beginIndex and endIndex.
class StringBufferExample3{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.replace(1,3,"Java");
System.out.println(sb);//prints HJavalo
}
}
4) StringBuffer delete() Method
The delete() method of the StringBuffer class deletes the String from the specified
beginIndex to endIndex.
class StringBufferExample4{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb);//prints Hlo
}
}
5) StringBuffer reverse() Method
The reverse() method of the StringBuilder class reverses the current String.
class StringBufferExample5{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb);//prints olleH
}
}
6) StringBuffer capacity() Method
The capacity() method of the StringBuffer class returns the current capacity of the
buffer. The default capacity of the buffer is 16. If the number of character increases
from its current capacity, it increases the capacity by (oldcapacity*2)+2. For
example if your current capacity is 16, it will be (16*2)+2=34.

class StringBufferExample6{
public static void main(String args[]){
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
}
}
7) StringBuffer ensureCapacity() method
The ensureCapacity() method of the StringBuffer class ensures that the given capacity is the
minimum to the current capacity. If it is greater than the current capacity, it increases the
capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be
(16*2)+2=34.
class StringBufferExample7{
public static void main(String args[]){
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity());//default 16
sb.append("Hello");
System.out.println(sb.capacity());//now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity());//now (16*2)+2=34 i.e (oldcapacity*2)+2
sb.ensureCapacity(10);//now no change
System.out.println(sb.capacity());//now 34
sb.ensureCapacity(50);//now (34*2)+2
System.out.println(sb.capacity());//now 70
}
}
String Buffer is Mutable Ex:
class HelloWorld {
public static void main(String[] args) {
StringBuffer s=new StringBuffer("Hello");
s.append(" VBIT");
System.out.println(s);
}
}

No. String StringBuffer

1) The String class is immutable. The StringBuffer class is


mutable.

2) String is slow and consumes StringBuffer is fast and


more memory when we consumes less memory when
concatenate too many strings we concatenatet strings.
because every time it creates
new instance.

3) String class overrides the StringBuffer class doesn't


equals() method of Object override the equals() method of
class. So you can compare the Object class.
contents of two strings by
equals() method.
4) String class is slower while StringBuffer class is faster while
performing concatenation performing concatenation
operation. operation.

5) String class uses String StringBuffer uses Heap memory


constant pool.
Command-Line Arguments
1) By using, command-line arguments, we can pass information into a program when we run it.
2) A command-line argument is the information that directly follows the program’s name on the
command line when it is executed.
3) A Java application can accept any number of arguments from the command line.
4) Command Line arguments are stored as strings in a String array passed to the args parameter
of main( ).
5) The first command-line argument is stored at args[0], the second at args[1], and so on.

Example:
// Display all command-line arguments.
class CommandLine
{
public static void main(String args[])
{
for(int i=0; i<args.length; i++)
System.out.println("args[" + i + "]: " + args[i]);
}
}
javac CommandLine.java
java CommandLine this is a test 10 -20
args[0]: this
args[1]: is
args[2]: a
args[3]: test
args[4]: 100
args[5]: -1

You might also like