JAVA UNIT 1
JAVA UNIT 1
UNIT-I Introduction
Object Oriented concepts-History of Java-Java buzzwords-JVM architecture-Data types-
Variables-Scope and lifetime 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.
OBJECT ORIENTED CONCEPTS
Object oriented thinking and Java Basics- Need for oop paradigm, summary of oop concepts,
coping with complexity, abstraction mechanisms. A way of viewing world – Agents,
responsibility, messages, methods, History of Java, Java buzzwords, data types, variables,
scope and lifetime of variables, arrays, operators, expressions, control statements, type
conversion and casting, simple java program, concepts of classes, objects, constructors,
methods, access control, this keyword, garbage collection, overloading methods and
constructors, method binding, inheritance, overriding and exceptions, parameter passing,
recursion, nested and inner classes, exploring string class.
OBJECT ORIENTED THINKING
When computers were first invented, programming was done manually by toggling in a
binary machine instructions by use of front panel.
As programs began to grow, high level languages were introduced that gives the
programmer more tools to handle complexity.
The first widespread high level language is FORTRAN. Which gave birth to structured
programming in 1960’s. The Main problem with the high level language was they have no
specific structure and programs becomes larger, the problem of complexity also increases.
So C became the popular structured oriented language to solve all the above problems.
However in SOP, when project reaches certain size its complexity exceeds. So in 1980’s a
new way of programming was invented and it was OOP. OOP is a programming
methodology that helps to organize complex programs through the use of inheritance,
encapsulation & polymorphism.
NEED FOR OOP PARADIGM
Traditionally, the structured programming techniques were used earlier.
There were many problems because of the use of structured programming technique.
The structured programming made use of a top-down approach.
To overcome these problems the object oriented programming concept was created.
The object oriented programming makes use of bottom-up approach.
The class is the repository for behavior associated with an object. That is all objects
that are instances of same class can perform the same actions.
Classes are organized into a singly rooted tree structure, called inheritance hierarchy.
OOP CONCEPTS
OOP stands for Object-Oriented Programming. OOP is a programming paradigm in which
every program is follows the concept of object. In other words, OOP is a way of writing
programs based on the object concept.
The object-oriented programming paradigm has the following core concepts.
Class
Object
Encapsulation
Inheritance
Polymorphism
Abstraction
Class
Class is a blue print which is containing only list of variables and methods and no memory is
allocated for them. A class is a group of objects that has common properties.
Object
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.
Example: A dog is an object because it has states like color, name, breed, etc. as
well as behaviors like wagging the tail, barking, eating, etc.
Encapsulation
Encapsulation is the process of combining data and code into a single unit.
In OOP, every object is associated with its data and code.
In programming, data is defined as variables and code is defined as methods.
The java programming language uses the class concept to implement encapsulation.
Inheritance
Inheritance is the process of acquiring properties and behaviors from one object to
another object or one class to another class.
In inheritance, we derive a new class from the existing class. Here, the new class
In the inheritance concept, the class which provides properties is called as parent class
and the class which recieves the properties is called as child class.
Person
name,
designation
learn(),
walk
(),
eat()
Abstraction
Abstraction is hiding the internal details and showing only essential functionality.
In the abstraction concept, we do not show the actual implementation to the end user,
instead we provide only essential things.
For example, if we want to drive a car, we does not need to know about the internal
functionality like how wheel system works? how brake system works? how music
system works? etc.
The problem with C, C++ and most other languages is that, they are designed to compile
on specific targeted CPU (i.e. they are platform dependent), but java is platform
Independent which can run on a variety of CPU’s under different environments.
The secondary factor that motivated the development of java is to develop the applications
that can run on Internet. Using java we can develop the applications which can run on
internet i.e. Applet. So java is a platform Independent Language used for developing
programs which are platform Independent and can run on internet.
Simple
Java programming language is very simple and easy to learn, understand, and code.
Most of the syntaxes in java follow basic programming language C and object-
oriented programming concepts are similar to C++.
In a java programming language, many complicated features like pointers, operator
overloading, structures, unions, etc. have been removed.
One of the most useful features is the garbage collector it makes java more simple.
Secure
Java is said to be more secure programming language because it does not have pointers
concept.
java provides a feature "applet" which can be embedded into a web application.
The applet in java does not allow access to other parts of the computer, which keeps away
Java soft people have introduced JIT (Just in Time ) compiler, to enhance the speed of
execution.
So now in JVM, both interpreter and JIT compiler work together to run the program.
Distributed
Information is distributed on various computers on a network.
Using Java, we can write programs, which capture information and distribute it to the client.
This is possible because Java can handle the protocols like TCP/IP and UDP.
Dynamic
Java is said to be dynamic because the java byte code may be dynamically updated on a running
system and it has a dynamic memory allocation and deallocation (objects and garbage
collector).
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).
What is JVM
It is:
What it does
o Loads code
o Verifies code
o Executes code
o Provides runtime environment
JVM provides definitions for the:
o Memory area
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) 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
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.
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.
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.
Note: Float data type can represent up to 7 digits accurately after decimal point.
Double data type can represent up to 15 digits accurately after decimal point.
Character Data Type
Character data type are represents a single character like a, P, &, *,..etc.
VARIABLES
Variable is a name given to a memory location where we can store different values of the same
data type during the program execution.
The following are the rules to specify a variable name...
A variable name may contain letters, digits and underscore symbol
Variable name should not start with digit.
Keywords should not be used as variable names.
Variable name should not contain any special symbols except underscore(_).
Variable name can be of any length but compiler considers only the first 31
characters of the variable name.
Declaration of Variable
Declaration of a variable tells to the compiler to allocate required amount of memory with
specified variable name and allows only specified datatype values into that memory location.
Syntax: datatype variablename;
Example : int a;
Syntax : data_type variable_name_1,
variable_name_2,...; Example : int a, b;
Initialization of a variable:
Syntax: datatype variablename = value;
Example : int a = 10;
Syntax : data_type variable_name_1=value, variable_name_2 = value;
Example : int a = 10, b = 20;
Local Variables
Variables declared inside the methods or constructors or blocks are called as local
variables.
The scope of local variables is within that particular method or constructor or block in
which they have been declared.
Local variables are allocated memory when the method or constructor or block in
which they are declared is invoked and memory is released after that particular method
or constructor or block is executed.
Access modifiers cannot be assigned to local variables.
It can’t be defined by a static keyword.
Local variables can be accessed directly with their name.
Progrm
class LocalVariables
{
public void show()
{
int a = 10;
System.out.println("Inside show method, a = " + a);
}
public void display()
{
int b = 20;
System.out.println("Inside display method, b = " + b);
//System.out.println("Inside display method, a = " + a); // error
}
public static void main(String args[])
{
LocalVariables obj = new LocalVariables();
obj.show();
} obj.display();
}
Instance Variables:
Variables declared outside the methods or constructors or blocks but inside the class
are called as instance variables.
The scope of instance variables is inside the class and therefore all methods,
constructors and blocks can access them.
Instance variables are allocated memory during object creation and memory is released
during object destruction. If no object is created, then no memory is allocated.
For each object, a separate copy of instance variable is created.
Heap memory is allocated for storing instance variables.
Access modifiers can be assigned to instance variables.
It is the responsibility of the JVM to assign default value to the instance variables as per the
type of
Variable.
Instance variables can be called directly inside the instance area.
Instance variables cannot be called directly inside the static area and necessarily requires
an object reference for calling them.
Program
class InstanceVariable
{
int x = 100;
public void show()
{
System.out.println("Inside show method, x = "
+ x); x = x + 100;
}
public void display()
{
System.out.println("Inside display method, x = " + x);
}
public static void main(String args[])
{
ClassVariables obj = new ClassVariables();
obj.show();
obj.display();
}
}
Static variables
Static variables are also known as class variable.
Static variables are declared with the keyword ‘static ‘ .
A static variable is a variable whose single copy in memory is shared by all the
objects, any modification to it will also effect other objects.
Static keyword in java is used for memory management, i.e it saves memory.
Static variables gets memory only once in the class area at the time of class loading.
Static variables can be invoked without the need for creating an instance of a class.
Static variables contain values by default. For integers, the default value is 0. For
Booleans, it is false. And for object references, it is null.
Syntax: static datatype variable name;
Example: static int x=100;
Syntax: classname.variablename;
Example
class Employee
{
static int
empid=500; static
void emp1()
{
empid++;
System.out.println("Employee id:"+empid);
}
}
class Sample
{
public static void main(String args[])
{
Employee.emp1()
;
Employee.emp1()
;
Employee.emp1()
;
Employee.emp1()
;
Employee.emp1()
;
Employee.emp1()
;
}
}
ARRAYS
An array is a collection of similar data values with a single name.
An array can also be defined as, a special type of variable that holds multiple values of
the same data type at a time.
In java, arrays are objects and they are created dynamically using new operator.
Every array in java is organized using index values.
The index value of an array starts with '0' and ends with 'zise-1'.
We use the index value to access individual elements of an array.
In java, there are two types of arrays and they are as follows.
One Dimensional Array
Multi Dimensional Array
Multidimensional Array
In java, we can create an array with multiple dimensions. We can create 2-
dimensional, 3- dimensional, or any dimensional array.
In Java, multidimensional arrays are arrays of arrays.
To create a multidimensional array variable, specify each additional index using
another set of square brackets.
Syntax
data_type array_name[ ][ ] = new
data_type[rows][columns]; (or)
data_type[ ][ ] array_name = new data_type[rows][columns];
When an array is initialized at the time of declaration, it need not specify the size of the
array and use of the new operator.
Here, the size is automatically decided based on the number of values that are initialized.
Example
class Twodarray
{
public static void main(String args[])
{
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
{
System.out.print(arr[i][j]+" ");
}
System.out.println();
}
}
}
OPERATORS
An operator is a symbol that performs an operation. An operator acts on some variables called
operands to get the desired result.
Example: a + b
Here a, b are operands and + is operator.
Types of Operators
1. Arithmetic operators
2. Relational operators
3. Logical operators
4. Assignment operators
5. Increment or Decrement operators
6. Conditional operator
7. Bit wise operators
1. Arithmetic Operators: Arithmetic Operators are used for mathematical calculations.
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modular
2. Relational Operators: Relational operators are used to compare two values and return a
true or false result based upon that comparison. Relational operators are of 6 types
Operator Description
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
== Equal to
!= Not equal to
1. Logical AND (&&) : Logical AND is denoted by double ampersand characters (&&).it is
used to check the combinations of more than one conditions. if any one condition false the
complete condition becomes false.
Truth table of Logical AND
Condition1 Condition2 Condition1 && Condition2
True True True
True False False
False True False
False False False
check the opposite result of any given test condition. i.e, it makes a true condition false and
false condition true.
Truth table of Logical NOT
Condition1 !Condition2
True False
False True
Example of Logical Operators
class LogicalOp
{
public static void main(String[] args)
{
int x=10;
System.out.println(x==10 &&
x>=5)); System.out.println(x==10
|| x>=5)); System.out.println ( !
( x==10 ));
}
}
+= Addition Assignment x + = y x= x + y
-= Addition Assignment x - = y x= x - y
*= Addition Assignment x * = y x= x * y
/= Addition Assignment x / = y x= x / y
%= Addition Assignment x % = y x= x % y
5: Increment And Decrement Operators : The increment and decrement operators are very
useful. ++ and == are called increment and decrement operators used to add or subtract.
Both are unary operators.
The syntax of the operators is given below.
These operators in two forms :prefix (++x) and postfix(x++).
++<variable name> --<variable name>
<variable name>++ <variable name>--
Operator Meaning
++x Pre Increment
--x Pre Decrement
x++ Post Increment
x-- Post Decrement
Where
1 : ++x : Pre increment, first increment and then do the operation.
2 : - -x : Pre decrement, first decrements and then do the operation.
3 : x++ : Post increment, first do the operation and then increment.
4 : x- - : Post decrement, first do the operation and then decrement.
Example
class Increment
{
public static void main(String[] args)
{
int var=5;
System.out.println
(var++);
System.out.println
(++var);
System.out.println (var--
); System.out.println (--
var);
}
}
6 : Conditional Operator: A conditional operator checks the condition and executes the
statement depending on the condition. Conditional operator consists of two symbols.
1 : question mark (?).
2 : colon ( : ).
Syntax: condition ? exp1 : exp2;
It first evaluate the condition, if it is true (non-zero) then the “exp1” is evaluated, if the
condition is false (zero) then the “exp2” is evaluated.
Example :
class ConditionalOperator
{
public static void main(String[] args)
{
int februaryDays = 29;
String result;
result = (februaryDays == 28) ? "Not a leap year" : "Leap year";
System.out.println(result);
}
}
7. Bitwise Operators:
Bitwise operators are used for manipulating a data at the bit level, also called as
bit level programming. Bit-level programming mainly consists of 0 and 1.
They are used in numerical Computations to make the calculation process faster.
The bitwise logical operators work on the data bit by bit.
Starting from the least significant bit, i.e. LSB bit which is the rightmost bit, working
towards the MSB (Most Significant Bit) which is the leftmost bit.
A list of Bitwise operators as follows…
Operator Meaning
& Bitwise AND
| Bitwise OR
^ Bitwise XOR
~ Bitwise Complement
<< Left Shift
>> Right Shift
CONTROL STATEMENTS
In java, the default execution flow of a program is a sequential order.
But the sequential order of execution flow may not be suitable for all situations.
Sometimes, we may want to jump from line to another line, we may want to skip a
part of the program, or sometimes we may want to execute a part of the program
again and again.
To solve this problem, java provides control statements.
Types of Control Statements
if statement in java
In java, we use the if statement to test a condition and decide the execution of a block of
statements based on that condition result.
The if statement checks, the given condition then decides the execution of a block of
statements. If the condition is True, then the block of statements is executed and if it is
False, then the block of statements is ignored.
Syntax
if(condtion)
{
if-block of statements;
}
statement after if-block;
Example
public class IfStatementTest
{
public static void main(String[] args)
{
int x=10;
if(x>0)
x++;
System.out.println("x value is:"+x);
}
}
In the above execution, the number 12 is not divisible by 5. So, the condition becomes False
and the condition is evaluated to False. Then the if statement ignores the execution of its block
of statements.
if-else statement in java
In java, we use the if-else statement to test a condition and pick the execution of a
}
else
{
true-block of statements;
false-block of statements;
Example
public class IfElseStatementTest
{
public static void main(String[] args)
{
int a=29;
if(a %
2==0)
System.out.println("Even Number is :"+a);
else System.out.println("Odd Number is :"+a);
}
}
Nested if statement in java
Writing an if statement inside another if-statement is called nested if statement.
Syntax
if(condition_1)
{
if(condition_2)
{
inner if-block of statements;
...
}
...
}
Exampl
e
public class NestedIfStatementTest
{
public static void main(String[] args)
{
int num=1;
if(num<10)
{
if(num==1)
{
System.out.print("The value is equal to 1);
}
els
e
{ System.out.print("The value is greater than 1");
}
}
els
e
{
System.out.print("The value is greater than 10");
}
System.out.print("Nested if - else statement ");
}
}
Switch
Using the switch statement, one can select only one option from more number of options
very easily.
In the switch statement, we provide a value that is to be compared with a value associated
with each option. Whenever the given value matches the value associated with an option,
the execution starts from that option.
In the switch statement, every option is defined as a case.
Syntax:
switch (expression)
{
case value1: // statement sequence
break;
case value2: // statement sequence
break;
….
case valueN:
}
Example
class SampleSwitch
{
public static void main(String args[])
{
char color
='g';
switch(color )
{
case 'r':
System.out.println("RED") ;
break ; case 'g':
System.out.println("GREEN") ;
break ; case 'b':
System.out.println("BLUE") ;
break ; case 'w':
System.out.println("WHITE") ; break ;
default:
System.out.println("No color") ;
}
}
}
2. Iteration Statements
The java programming language provides a set of iterative statements that are used to
execute a statement or a block of statements repeatedly as long as the given condition
is true.
The iterative statements are also known as looping statements or repetitive statements.
Java provides the following iterative statements.
1.while statement
2. do-while statement
3. for statement
4. for-each statement
while statement in java
The while statement is used to execute a single statement or block of statements repeatedly as
long as the given condition is TRUE. The while statement is also known as Entry control
looping statement.
Syntax
while(condition)
{
// body of loop
Exampl }
e
// body
}
If only one statement is being repeated, there is no need for the curly braces.
In for-statement, the execution begins with the initialization statement. After the
initialization statement, it executes Condition. If the condition is evaluated to true, then the
block of statements executed otherwise it terminates the for-statement. After the block
of statements execution, the modification statement gets executed, followed by condition
again.
Example
public class ForTest
{
public static void main(String[] args)
{
for(int i = 0; i < 10; i++)
{
System.out.println("i = " + i);
}
System.out.println("Statement after for!");
}
}
3. Jump Statements
The java programming language supports jump statements that used to transfer execution
control from one line to another line.
The java programming language provides the following jump statements.
1. break statement
2. continue statement
break
When a break statement is encountered inside a loop, the loop is terminated and program
control resumes at the next statement following the loop.
Example
class BreakStatement
{
public static void main(String args[] )
{
int i;
i=1;
while(true)
{
if(i >10)
break;
System.out.print(i+"
"); i++;
}
}
}
Continue
This command skips the whole body of the loop and executes the loop with the next iteration.
On finding continue command, control leaves the rest of the statements in the loop and goes
back to the top of the loop to execute it with the next iteration (value).
Example
/* Print Number from 1 to 10 Except 5 */
class NumberExcept
{
public static void main(String args[] )
{
int i;
for(i=1;i<=10;i++)
{
if(i==5)
continue;
System.out.print(i +"
");
}
}
}
TYPE CONVERSION AND CASTING
Type Casting
When a data type is converted into another data type by a programmer using the casting
operator while writing a program code, the mechanism is known as type casting.
In typing casting, the destination data type may be smaller than the source data type
when
converting the data type to another data type, that’s why it is also called narrowing
conversion.
Syntax
destination_datatype = (target_datatype)variable;
Progra
m
public class NarrowingTypeCastingExample
{
public static void main(String args[])
{
double d = 166.66;
int i = (int)d;
System.out.println("Before conversion: "+d);
System.out.println("After conversion into int type: "+i);
}
}
Output
Before conversion: 166.66
After conversion into int type: 166
Type Conversion
If a data type is automatically converted into another data type at compile time is known
as type conversion.
The conversion is performed by the compiler if both data types are compatible with each
other.
Remember that the destination data type should not be smaller than the source type.
It is also known as widening conversion of the data type.
Example
int a = 20;
Float b;
b = a; // Now the value of variable b is 20.000
Progra
m
public class WideningTypeCastingExample
{
public static void main(String[] args)
{
int x = 7;
float y = x;
System.out.println("After conversion, float value "+y);
}
}
Output
:
After conversion, the float value is: 7.0
Documentation Section
The documentation section is an important section but optional for a Java program.
It includes basic information about a Java program. The information includes the author's
name, date of creation, version, program name, company name, and description of the
program. It improves the readability of the program. Whatever we write in the documentation
section, the Java compiler ignores the statements during the execution of the program. To
write the statements in the documentation section, we use comments.
Comments there are three types
1. Single-line Comment: It starts with a pair of forwarding slash
WHAT IS JVM
Java Virtual Machine is the heart of entire java program execution process. It is responsible
for taking the .class file and converting each byte code instruction into the machine language
instruction that can be executed by the microprocessor.
Creating a Class
In java, we use the keyword class to create a class. A class in java contains properties as
variables and behaviors as methods.
Syntax
class className
{
data members
declaration; methods
definition;
}
The ClassName must begin with an alphabet, and the Upper-case letter is preferred.
The ClassName must follow all naming rules.
Example
Here is a class called Box that defines three instance variables: width, height, and
depth. class Box
{
double width;
double
height;
double depth;
void
volume()
{
………………….
}
}
OBJECT
In java, an object is an instance of a class.
Objects are the instances of a class that are created to use the attributes and methods of a
class.
All the objects that are created using a single class have the same properties and methods.
Example
Box mybox = new Box();
The new operator dynamically allocates memory for an object.
Example
class Box
{
double width;
double
height;
double depth;
}
class BoxDemo
{
public static void main(String args[])
{
Box mybox = new
Box(); double vol;
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
vol = mybox.width * mybox.height * mybox.depth;
System.out.println("Volume is " + vol);
}
}
METHODS
A method is a block of statements under a name that gets executes only when it is called.
Every method is used to perform a specific task. The major advantage of methods is
code re- usability (define the code once, and use it many times).
In a java programming language, a method defined as a behavior of an object. That means,
every method in java must belong to a class.
Every method in java must be declared inside a class.
Every method declaration has the following characteristics.
returnType - Specifies the data type of a return value.
name - Specifies a unique name to identify it.
parameters - The data values it may accept or recieve.
{ } - Defienes the block belongs to the method.
Creating a method
A method is created inside the class
Syntax
class ClassName
{
returnType methodName( parameters )
{
// body of method
}
}
Calling a
method
In java, a method call precedes with the object name of the class to which it belongs
Class Box
{
double width, height, depth;
void volume()
{
System.out.print("Volume is ");
System.out.println(width * height * depth);
}
}
class BoxDemo3
{
public static void main(String args[])
{
Box mybox1 = new
Box(); Box mybox2 =
new Box();
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth =
9;
mybox1.volume()
;
mybox2.volume()
;
}
}
CONSTRUCTORS
Constructor in Java is a special member method which will be called automatically by
the JVM whenever an object is created for placing user defined values in place of
default values.
In a single word constructor is a special member method which will be called
automatically whenever object is created.
The purpose of constructor is to initialize an object called object initialization.
Initialization is a process of assigning user defined values at the time of allocation of
memory space.
Syntax
ClassName()
{
.......
.......
}
Types Of Constructors
Based on creating objects in Java constructor are classified in two types. They are
1. Default or no argument Constructor
2. Parameterized constructor
1. Default Constructor
A constructor is said to be default constructor if and only if it never take any parameters.
If any class does not contain at least one user defined constructor then the system will
create a default constructor at the time of compilation it is known as system defined
default constructor.
Note: System defined default constructor is created by java compiler and does not have any
statement in the body part. This constructor will be executed every time whenever an object
is created if that class does not contain any user defined constructor.
Example
class Test
{
int a, b;
Test()
{
a=10;
b=20;
System.out.println("Value of a: "+a);
System.out.println("Value of b: "+b);
}
}
class TestDemo
{
public static void main(String args[])
{
Test t1=new Test();
}
}
2. Parameterized Constructor
If any constructor contain list of variables in its signature is known as paremetrized constructor.
A parameterized constructor is one which takes some parameters.
Example
class Test
{
int a, b;
Test(int n1, int n2)
{
a=n1;
b=n2;
System.out.println("Value of a = "+a);
System.out.println("Value of b = "+b);
}
}
class TestDemo
{
public static void main(String args[])
{
Test t1=new Test(10, 20);
}
}
The following table depicts all built-in methods of String class in java.
S.No Method Description
1 charAt(int) Finds the character at given index
2 length() Finds the length of given string
3 compareTo(String) Compares two strings
4 compareToIgnoreCase(String) Compares two strings, ignoring case
5 concat(String) Concatenates the object string with argument string.
6 contains(String) Checks whether a string contains sub-string
7 contentEquals(String) Checks whether two strings are same
8 equals(String) Checks whether two strings are same
9 equalsIgnoreCase(String) Checks whether two strings are same, ignoring case
10 startsWith(String) Checks whether a string starts with the specified
string
11 isEmpty() Checks whether a string is empty or not
12 replace(String, String) Replaces the first string with second string
replaceAll(String, String) Replaces the first string with second string at all
13 occurrences.
Example
public class JavaStringExample
{
public static void main(String[] args)
{
String title = "Java Programming";
String siteName = "String Handling Methods";
System.out.println("Length of title: " + title.length());
System.out.println("Char at index 3: " + title.charAt(3));
System.out.println("Index of 'T': " + title.indexOf('T'));
System.out.println("Empty: " + title.isEmpty());
System.out.println("Equals: " + siteName.equals(title));
System.out.println("Sub-string: " + siteName.substring(9,
14)); System.out.println("Upper case: " +
siteName.toUpperCase());
}
}
StringBuffer class
StringBuffer class is used to make mutable string objects, Which means they can be modified
after creation. This represents the growable and writable character sequence. This class gives
us the flexibility to alter our String; it is also thread-safe, i.e., it cannot provide the flexibility
of accessing multiple threads simultaneously.
Constructors of StringBuffer class
StringBuffer(): This constructor helps us to create an empty StringBuffer of 16
characters having its initial capacity.
StringBuffer(String str): This constructor will create a StringBuffer with the specified
String.
StringBuffer(int cap): This constructor will accept an integer argument that sets the
size of the buffer.
insert(int index, String str): This method will insert one String into another. It will
insert the String the particular index position defined in the function.
reverse(): This function will reverse the characters available in the StringBuffer object.
replace(int start, int last, String s): This function will replace the character from the
start index to the last index passed in the method parameter.
capacity(): This function will return the capacity of the StringBuffer object.
delete(int start, int end): This method will delete the String from the specified index
passed in the argument list.
Must Read: Java System Out Println and Hashcode Method in Java.
Examples
Code 1
public class Ex21 {
public static void main(String[] args) {