JAVA UNIT 1
JAVA UNIT 1
UNIT – I
Introduction: Review of Object Oriented Concepts – History of Java – Java
Buzzwords – JVM Architecture – Data Types – Variables – Scope and Life Time of
Variables – Arrays – Operators – Control Statements – Type Conversion and Casting –
Simple Java Program – Constructors – Methods – Static Block – Static Data – Static
Method String and String Buffer Classes.
Class
Class is a user-defined data type. Class is a collection of data members and
member functions. It can be created using the keyword “class”.
Inheritance
Deriving a new class (Sub Class) from an old class (Super Class) is called Inheritance. It
provides code reusability. It is used to achieve runtime polymorphism.
Benefits of Inheritance
1. One of the key benefits of inheritance is to minimize the amount of duplicate code
in an application by sharing common code amongst several subclasses.
2. Inheritance can also make application code more flexible to change because classes
that inherit from a common superclass can be used interchangeably. If the return
type of a method is superclass
3. Reusability - facility to use public methods of a base class without rewriting the same.
4. Extensibility - extending the base class logic as per the business logic of the
derived class.
Polymorphism
When one task is performed in different ways i.e. known as polymorphism.
For example: to draw different shapes using the same method.
In Java, we use method overloading and method overriding to achieve polymorphism.
Abstraction
Hiding internal details and showing functionality is known as abstraction.
For example: phone call, we don't know the internal processing.
In Java, we use abstract classes and interfaces to achieve abstraction.
Encapsulation
Binding (or wrapping) code and data together into a single unit is known as
encapsulation.
For example: a capsule, is wrapped with different medicines.
A Java class is an example of encapsulation.
***************************
History of JAVA
• Java Standard Edition: - Java Standard Edition, also known as J2SE / JSE is the java platform (Any
hardware or software environment in which a program runs is known as a platform.) for developing
client-side application which runs on desktop, and applets which run on web browser.
Core Java + JDBC is the part of Java Standard Edition (J2SE / JSE).
• Java Enterprise Edition : - Java Enterprise Edition, also known as J2EE / JEE is the java platform
built on the top of Java SE , which is used to develop enterprise- oriented server applications.(Server side
applications include servlets, which are java programs that are similar to applets but run on a server
rather than a client.)
Servlets + JSPs are the part of Java Enterprise Edition.
• Java Micro Edition: - Java Micro Edition, also known as J2ME / JME is the java platform which is
also built on Java SE. It is mainly used to develop mobile applications.
• Java FX: - Java FX, also known as Java Flex is used to develop rich internet applications. It uses
light-weight user interface API.
1. Simple
2. Object-Oriented
3. Portable
4. Platform-independent
5. Secured
6. Robust
7. Architecture neutral
8. Dynamic
9. Interpreted
10. High Performance
11. Multithreaded
12. Distributed
1. Simple
Java is very easy to learn, and its syntax is simple, clean, and easy to understand.
2. 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.
Basic concepts of OOPs are:
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
3. Portable
Java is portable because it allows you to carry the Java bytecode to any platform. It doesn't
require any implementation.
4. Platform – Independent
Java is a write-once, run-anywhere language.
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,Write Once
and Run Anywhere (WORA) which means that we can develop applications on one environment (OS) and
run on any other environment without doing any modification in the code.
Below diagram explains the platform independence feature of Java-Portable.
5. Secured
Java is best known for its security.
Java is secured because of the following
o No explicit Pointer
o Run inside a virtual machine sandbox
o Classloader
o Bytecode Verifier
o Security Manager
6. Robust
Java is robust because:
It uses strong memory management.
There is a lack of pointers.
Java provides automatic garbage collection.
There are exception-handling and the type checking mechanism in Java.
7. Architecture Neutral
Java is architecture-neutral because there are no implementation-dependent features,
for example, the size of primitive types is fixed.
8. Dynamic
Java is a dynamic language.
It supports the dynamic loading of classes.
It means classes are loaded on demand.
10. High Performance
Java is faster than other traditional interpreted programming languages because Java
bytecode is "close" to native code.
11. Multithreaded
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.
12. Distributed
Java is distributed because it facilitates users to create distributed applications in Java.
RMI and EJB are used for creating distributed applications.
***********************
Loads code
Verifies code
Executes code
Provides runtime environment
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.
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.
JVM provides definitions for the:
Memory area
Class file format
Register set
Garbage-collected heap
Fatal error reporting etc.
JVM Architecture
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.
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.
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.
PC (program counter) register contains the address of the Java virtual machine instruction
currently being executed.
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.
4. 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.
Data types specify the different sizes and values that can be stored in the variable. There are two
types of data types in Java:
1. Primitive data types: The primitive data types include boolean, char, byte, short, int, long,
float and double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces,
and Arrays.
The double data type in Java is a primitive data type that represents double-precision 64-bit
IEEE 754 floating-point numbers. Its default value is 0.0d.
Char Data Type
The char data type in Java is a primitive data type that represents a single 16-bit Unicode
character. It can store any character from the Unicode character set, that allows Java to support
internationalization and representation of characters from various languages and writing
systems.
Type Size Minimum value Maximum value
Byte One byte -128 127
Short Two bytes -32,768 32,767
Int Four bytes -2,147,483,648 2,147,483,647
Long Eight - 9,223,372,036,854,77
bytes 5,
9,223,372,036,854,775, 807
8
08
For example, you might create a Person class to represent a person, with variables for the
person's name, age, and address, and methods to set and get these values.
Interface
An interface defines a contract for what a class implementing the interface must provide,
without specifying how it should be implemented.
Interfaces are used to achieve abstraction and multiple inheritance in Java, allowing
classes to be more flexible and reusable.
Arrays
that allow you to store multiple values of the same type in a single variable.
Arrays have a fixed size, which is specified when the array is created, and can be accessed
using an index.
Arrays are commonly used to store lists of values or to represent matrices and other
multi-dimensional data structures.
Enum
Java also includes other non-primitive data types, such as enums and collections.
Enums are used to define a set of named constants, providing a way to represent a fixed
set of values.
Collections are a framework of classes and interfaces that provide dynamic data
structures such as lists, sets, and maps, which can grow or shrink in size as needed.
JAVA Variables
A variable is an identifier that denotes a storage location used to store a data value.
Variable names may consist of alphabets, digits, the underscore( _ ) and dollar
characters, subject to the following conditions:
They must not begin with a digit.
Uppercase and lowercase are distinct.
It should not be a keyword.
White space is not allowed.
Variable names can be of any length.
Declaration of variable
It is called an instance variable because its value is instance-specific and is not shared
among instances.
Instance variables are created when an object is created with the use of the keyword
‘new’ and destroyed when the object is destroyed.
Instance variables hold values that must be referenced by more than one method,
constructor or block, or essential parts of an object’s state that must be present
throughout the class.
The instance variables are visible for all methods, constructors and block in the class. It
is recommended to make these variables as private. However, visibility for subclasses
can be given for these variables with the use of access modifiers.
Booleans it is false,
Constants in Java
A constant is a variable which cannot have its value changed after declaration. It uses the 'final'
keyword.
Syntax
Modifier final dataType variableName = value;
Arrays
An array is a collection of similar type of elements which has 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.
Types of Array
There are two types of array.
One Dimensional Array
Multidimensional Array
Creating An Array
Creation of array includes three steps:
1. Declare the array
2. Create memory locations
3. Put values into the memory locations.
Array length : In java, all arrays store the allocated size in a variable named length.
To know the size of an array, it can be accessed as
arrayname.length
RELATIONAL OPERATORS
❖ Compares two quantities depending on their relation.
❖ Java supports six relational operators.
Operator Meaning
< is less than
<= is less than or equal to
> is greater than
>= is greater than or equal to
== is equal to
!= is not equal to
A simple relational expression contains only one relational operator and is of the
following form:
ae-1 relational operator ae-2
where ae-1 and ae-2 are arithmetic expressions
LOGICAL OPERATORS
ASSIGNMENT OPERATORS
Used to assign the value of an expression to a variable.
Assignment operators are usually in the form “=”.
v op=exp;
CONDITIONAL OPERATORS
❖ The character pair ?: is used for conditional operator.
❖ It is also called as ternary operator.
General Form exp1 ? exp2: exp3
where exp1, exp2, exp3 are expressions
The operator ?: works as follows
exp1 is evaluated first, if its is true then the exp2 is evaluated. If
exp1 is false, exp3 is evaluated
BITWISE OPERATORS:
Bitwise operators are used to manipulate data at values of bit level.
These operators are used for testing the bits, or shifting them to the right or left.
❖ Bitwise operators may not to float or double.
Operator Meaning
& Bitwise AND
! Bitwise OR
^ Bitwise exclusive OR
~ One’s complement
<< Shift left
>> Shift right
>>> Shift right with zero fill
SPECIAL OPERATORS
❖ Java supports special operators
➢ Instance of operator
➢ Dot operator (or) member selection operator (.)
✓ Instance of operator:
❖ Instance of operator is an object reference operator.
❖ Allow us to determine whether the object belongs to a particular class or not.
❖ Return true, if the object on the left-hand side is an instance of the class
given on the right-hand side.
Dot operator
The dot operator (.) is used to access the instance variables and methods of class
objects.
It is also used to access classes and sub packages from a package.
if statement
switch statement
Conditional operator statement
IF Statement
The if statement is a powerful decision making statement and is used to control the
flow of execution of statements.
General form if (test expression)
if (degree = = “BCA”)
{
points = points+500;
}
else
{
Points = points + 100;
}
if (test condition1)
{
if (test condition2)
{
True
blockstatements-1;
}
else
{
False block
statement-2;
}
}
else
{
False block statements-3;
} Example
Statement-x; if (gender == “female”)
{
if (balance>5000)
{
Bonus = 0.03 *
balance;
}
else
{
Bonus = 0.02 *
balance;
}
}
else
{
Bonus = 0.01 * balance;
}
balance=balance + bonus;
4.Else if ladder
Else If ladder is a chain of ifs in which the statement associated with each else is an if.
The condition is evaluated from the top to downwards.
➢ As soon as the condition is true, then the statements associated with it are executed and
the control is transferred to the statement -x.
➢ When all the n condition is false, then the final else containing the default- statement
will be executed.
General form
If (condition-1)
statement-1; else if (condition-2)
statement -2; else if (condition-3)
statement -3;
…..
else if (condition n)
statement -n;
else
default-statement;
Example
If (marks>79)
grade=”honors”;
else if (marks>79)
grade=”first”;
else if (marks>79)
grade=”second”;
else if (marks>79)
grade=”third”;
else
grade=”fail”; // Default-stmt System.out.println(“grade=”+grade);
The default is an option case; it will be executed if the value of the expression does not match with any of
the case values.
If not present, no action takes place when all matches fail and the control goes to the statement –x.
General form
switch(expression)
{
case value-1:
block-1
break; case value-2:
block-2
break; case value-3:
block-3
break;
Example
switch(expression)
{
case ‘1’:
System.out.println(“Monday”);
break; case ‘2’:
System.out.println(“Tuesday”);
break; case ‘3’:
System.out.println(“Wednesday”);
break;
………..
……….
default:
default-block break;
}
statement-x;
case ‘4’:
System.out.println(“Thursday”);
break;
………………
………………..
default:
System.out.println (“WRONG INPUT”);
break;
}
System.out.println(“ WELCOME TO THIS WEEK”.
3.CONDITIONAL OPERATORS
❖ The character pair ?: is used for conditional operator.
❖ It is also called as ternary operator.
General Form exp1 ? exp2: exp3 where exp1, exp2, exp3 are expressions
Example:
If(x<0)
Flag=0;
Else
Flag=1;
Flag =(x<0) ? 0 :1;
while statement
do-while statement
for statement
while statement
The while loop loops through a block of code as long as a specified condition is true.
Syntax
while (condition) {
In the example below, the code in the loop will run, over and over again, as long as a variable (i) is less
than 5:
Example
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
do-while statement:
The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if th
condition is true, then it will repeat the loop as long as the condition is true.
Syntax
do {
// code block to be executed
while (condition);
The example below uses a do/while loop. The loop will always be executed at least once, even if the
condition is false, because the code block is executed before the condition is tested:
Example
int i = 0;
do {
System.out.println(i);
i++;
Statement 1 is executed (one time) before the execution of the code block.
Statement 3 is executed (every time) after the code block has been executed.
Example
for (int i = 0; i < 5; i++) {
System.out.println(i);
Jump Statements
In java, the jump statements are used to terminate a block or take the execution control to the next
iteration. Java provides the following jump statements.
break
continue
return
break:
Example
for (int i = 0; i < 10; i++) {
if (i == 4) {
break;
System.out.println(i);
}
CONTINUE:
The continue statement breaks one iteration (in the loop), if a specified condition occurs, and
continues with the next iteration in the loop.
Example
for (int i = 0; i < 10; i++) {
if (i == 4) {
continue;
System.out.println(i);
Return Statement
the return statement is used for returning a value when the execution of the block is completed.
Syntax:
The syntax of a return statement is the return keyword is followed by the value to be returned.
return returnvalue;
EXAMPLE:
int x=30;
float y;
y=x; // y==30.000000.
float x;
byte y;
...
...
y=(byte)x; //converting float(source) data type into byte(target) data type
1. In type casting, a data type is converted Whereas in type conversion, a data type
s.NO TYPE CASTING TYPE CONVERSION
into another data type by a programmer is converted into another data type by a
using casting operator. compiler.
Type casting takes place during the Whereas type conversion is done at the
5.
program design by programmer. compile time.
Type casting is also called narrowing Whereas type conversion is also called
conversion because in this, the widening conversion because in this, the
6.
destination data type may be smaller destination data type can not be smaller
than the source data type. than the source data type.
Type casting is more efficient and Whereas type conversion is less efficient
8.
reliable. and less reliable.
A java program may contain many classes, of which only one class should contains main() method.
Documentation section
Package statements
Import statements
Interface statements
Class Definations
Main Method Class
{
Main Method Definations
}
Documentation section:
Syntax:
//This is single line comment
Java Multi Line Comment:
The multi line comment is used to comment multiple lines of code.
Syntax:
/*
This is
multi
line
comment
*/
Java Documentation Comment:
The documentation comment is used to create documentation API. To create documentation API, you
need to use javadoc tool.
Syntax:
/**
This is
documentation
comment
*/
Package statement:
This is the first statement in java file. This statement declares a package name and informs the compiler
that the class defined here belongs to this package.
Ex: - package student
Import statements:
This is the statement after the package statement. It is similar to # include in c/c++.
Ex: import java.lang.String
The above statement instructs the interpreter to load the String class from the lang package. Note:
• Import statement should be before the class definitions.
• A java file can contain N number of import statements.
Interface statements:
An interface is like a class but includes a group of method declarations.
Note: Methods in interfaces are not defined just declared.
Class definitions:
Java is a true oop, so classes are primary and essential elements of java program. A program can have
multiple class definitions.
To create a simple Java program, we need to create a class that contains the main method. Let's understand
the requirement first.
Requirements:
For executing any Java program, the following software or application must be properly installed.
o Install the JDK if you don't have installed it, download the JDK and install it.
o Set path of the jdk/bin directory. http://www.javatpoint.com/how-to-set-path-in-java
o Create the Java program
o Compile and run the Java program
class Simple
{
public static void main(String args[])
{
System.out.println("Hello Java");
}
}
Save the above file as Simple.java.
To compile: javac Simple.java
To execute: java Simple
Output:
Hello Java
Compilation Flow:
When we compile Java program using javac tool, the Java compiler converts the source code into byte
code.
Introduction of classes:
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:
Fields
Methods
Constructors
Blocks
Nested class and interface
General form of class:
A class is declared by use of the class keyword.
class ClassName
{
VariableDeclaration-1; VariableDeclaration-2; VariableDeclaration-3;
VariableDeclaration-n;
The data, or variables, defined within a class are called instance variables. The code is contained within
methods. Collectively, the methods and variables defined within a class are called members of the class.
Example:
class Demo
{
int x=5;
void display()
{
System.out.println(“x value is: ”+x);
}}
Creating Objects:
An object in Java is essentially a block of memory that contains space to store all the instance variables.
Creating an object also known as instantiating an object. Objects in Java are created using the new
operator. The new operator creates an object of the specified class and returns a reference to that
object.
Syntax for object creation:
classname objectname; //declares a variable to hold the object reference
objectname = new classname( ); // Assigns the object reference to the variable
class Demo
{
int x;
int display()
{
System.out.println("X value is: "+x); return 0;
}
public static void main(String args[])
{
Demo D1=new Demo(); //creating objects
D1.x=10;
D1.display();
}
}
Output:
X value is: 10
METHODS IN JAVA:
A method is a block of code or collection of statements or a set of code grouped together to perform a
certain task or operation. It is used to achieve the reusability of code. We write a method once and use it
many times.
Syntax
int − returntype
a, b − formalparameters
int a, int b − list ofparameters
Method Declaration
The method declaration provides information about method attributes, such as visibility, return-type, name,
and arguments. It has six components that are known as method header,
Method Signature: Every method has a method signature. It is a part of the method declaration. It
includes the method name and parameter list.
Access Specifier: Access specifier or modifier is the access type of the method. It specifies the visibility of
the method. Java provides four types of access specifier:
o Public: The method is accessible by all classes when we use public specifier in our application.
o Private: When we use a private access specifier, the method is accessible only in the classes in
which it is defined.
o Protected: When we use protected access specifier, the method is accessible within the same
package or subclasses in a different package.
o Default: When we do not use any access specifier in the method declaration, Java uses default
access specifier by default. It is visible only from the same package only.
Return Type: Return type is a data type that the method returns. It may have a primitive data type, object,
collection, void, etc. If the method does not return anything, we use void keyword.
Method Name: It is a unique name that is used to define the name of a method. It must be corresponding
to the functionality of the method. Suppose, if we are creating a method for subtraction of two numbers, the
method name must be subtraction(). A method is invoked by its name.
Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of parentheses.
It contains the data type and variable name. If the method has no parameter, left the parentheses blank.
Method Body: It is a part of the method declaration. It contains all the actions to be performed. It is
enclosed within the pair of curly braces.
Types of Method
There are two types of methods in Java:
o Predefined Method
o User-defined Method
Predefined Method
In Java, predefined methods are the method that is already defined in the Java class libraries is known as
predefined methods. It is also known as the standard library method or built-in method. We can directly
use these methods just by calling them in the program at any point. Some pre-defined methods
are length(), equals(), compareTo(), sqrt(), etc.
Each and every predefined method is defined inside a class. Such as print() method is defined in
the java.io.PrintStream class. It prints the statement that we write inside the method. For
example, print("Java"), it prints Java on the console.
Example:
In the above example, we have used three predefined methods main(), print(), and max(). We have used
these methods directly without declaration because they are predefined. The print() method is a method
of PrintStream class that prints the result on the console. The max() method is a method of the Math class
that returns the greater of two numbers.
User-defined Method
The method written by the user or programmer is known as a user-defined method. These methods are
modified according to the requirement.
Let's create a user defined method that checks the number is even or odd. First, we will define the method.
import java.util.Scanner;
public class EvenOdd
{
public static void main (String args[])
{
//creating Scanner class object
Scanner scan=new Scanner(System.in);
System.out.print("Enter the number: ");
//reading value from user
int num=scan.nextInt();
//method calling
findEvenOdd(num);
}
//user defined method
public static void findEvenOdd(int num)
{
//method body
if(num%2==0)
System.out.println(num+" is even");
else
System.out.println(num+" is odd");
}
}
Output:
Enter the number: 45 num is odd
CONSTRUCTORS
NSTRUCTORS
A constructor is a special method that is used to initialize objects.
The constructor is called when an object of a class is created.
It can be used to set initial values for object
The constructor name and the class name should be the same.
The constructor doesn’t have a return type.
All classes have constructors by default.
Types of Constructor
There are 2 types of constructor
Default constructor: is the type of constructor with out any argument.
Parameterized Constructor: is a constructor with one or more argument.
1. Default Constructor
A constructor without parameters is called a default constructor.
Default constructor is invoked if there is no constructor available in the class.
Syntax
Class_name(){
//code
}
Example
class Bike1{
Bike1()
{
System.out.println("Bike is created");
}
public static void main(String args[]){ Bike1
b=new Bike1 ();
}
}
2. Parameterized Constructor
A constructor which has a specific number of parameters is called a parameterized
constructor.
The parameterized constructor is used to provide different values to distinct objects.
Syntax
Class_name(Parameters)
{
//code
}
Example
classStudent4
{
int id; Stringname;
Student4(int i,String n)
{
id = i;
name = n;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[])
{
Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
s1.display();
s2.display();
}}
Output:
111Kara
222Arya
Static Keyword in JAVA
Static Method
If we apply a static keyword with any method, it is known as a static method.
A static method belongs to the class rather than the object of a class.
A static method can be invoked without the need for creating an instance of
a class.
A static method can access static data members and can change their value of it.
Example
Static method
If you apply static keyword with any method, it is known as static method.
A static method belongs to the class rather than the object of a class.
A static method can be invoked without the need for creating an instance of a
class.
A static method can access static data member and can change the value of it.
Static Block
Java supports a special block, called a static block (also called static clause) that
can be used for static initialization of a class.
Code inside the static block is executed only once.
Static block executes automatically when the class is loaded in memory.
Example
class A2
{
static{System.out.println("static block is invoked");
}
public static void main(String args[])
{
System.out.println("Hello main");
}
}
Output:
static block is invoked
Hello main
A constructor is used to initialize the state of an A method is used to expose the behavior of an
object. object.
A constructor must not have a return type. A method must have a return type.
The Java compiler provides a default constructor The method is not provided by the compiler in
if you don't have any constructor in a class. any case.
The constructor name must be same as the class The method name may or may not be same as the
name. class name.
**********************
String
Strings are the type of objects that can store the character of values and in Java.
A string acts the same as an array of characters.
For example:
char[] ch={'j','a','v','a','t','p','o','i','n','t'};
String s=new String(ch); ssame as:
Strings="javatpoint";
EXAMPLE:
public class StringExample {
public static void main(String args[])
{
String str = new String("example");
System.out.println(str);
}
}
Java String class provides a lot of methods to perform operations on strings such as compare(),
concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc.
Creating a String
There are two ways to create a string in Java
1. String Literal
2. Using new Keyword
1. String Literal
No new objects are created if it exists already in the string constant pool
Example:
String demoString = “GeeksforGeeks”;
2. Using new Keyword
String s = new String(“Welcome”);
In such a case, JVM will create a new string object in normal (non-pool) memory
String Buffer Class in Java
StringBuffer is a class in Java that represents a mutable sequence of characters.
It provides an alternative to the immutable String class, allowing you to modify the
contents of a string without creating a new object every time.
String creates strings of fixed_length
In stringbuffer class we can insert characters and substrings in the middle of a string, or
append another string to the end
Constructors of StringBuffer class
1. StringBuffer(): creates an empty string buffer with an initial capacity of 16.
2. StringBuffer(String str): creates a string buffer with the specified string.
3. StringBuffer(int capacity): creates an empty string buffer with the specified capacity as
length.
Syntax
Hello, World!
String class is slower while performing concatenation StringBuffer class is faster while performing
operation. concatenation operation.
String class uses String constant pool. StringBuffer uses Heap memory
*************************