Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
11 views

All about Java

Java

Uploaded by

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

All about Java

Java

Uploaded by

chandukurra666
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 91

Introduction of Java:

JAVA was developed by James Gosling at Sun Microsystems Inc in the year 1995, later
acquired by Oracle Corporation. It is a simple programming language. Java makes writing,
compiling, and debugging programming easy. It helps to create reusable code and modular
programs. Java is a class-based, object-oriented programming language and is designed to
have as few implementation dependencies as possible. A general-purpose programming
language made for developers to write once run anywhere that is compiled Java code can run
on all platforms that support Java. Java applications are compiled to byte code that can run
on any Java Virtual Machine. The syntax of Java is similar to c/c++.

History:
Java’s history is very interesting. It is a programming language created in 1991. James
Gosling, Mike Sheridan, and Patrick Naughton, a team of Sun engineers known as the Green
team initiated the Java language in 1991. Sun Microsystems released its first public
implementation in 1996 as Java 1.0. It provides no-cost -run-times on popular platforms.
Java1.0 compiler was re-written in Java by Arthur Van Hoff to strictly comply with its
specifications. With the arrival of Java 2, new versions had multiple configurations built for
different types of platforms.

In 1997, Sun Microsystems approached the ISO standards body and later formalized Java,
but it soon withdrew from the process. At one time, Sun made most of its Java
implementations available without charge, despite their proprietary software status. Sun
generated revenue from Java through the selling of licenses for specialized products such as
the Java Enterprise System.

On November 13, 2006, Sun released much of its Java virtual machine as free, open-source
software. On May 8, 2007, Sun finished the process, making all of its JVM’s core code
available under open-source distribution terms.
Java programming language is named JAVA. Why?

After the name OAK, the team decided to give a new name to it and the suggested words
were Silk, Jolt, revolutionary, DNA, dynamic, etc. These all names were easy to spell and
fun to say, but they all wanted the name to reflect the essence of technology. In accordance
with James Gosling, Java the among the top names along with Silk, and since java was a
unique name so most of them preferred it.
Java is the name of an island in Indonesia where the first coffee(named java coffee) was
produced. And this name was chosen by James Gosling while having coffee near his office.
Note that Java is just a name, not an acronym.

Java Terminology

Before learning Java, one must be familiar with these common terms of Java.

1. Java Virtual Machine(JVM): This is generally referred to as JVM. There are three
execution phases of a program. They are written, compile and run the program.

Java Virtual
Java Compiler
Machine
Program

 Writing a program is done by a java programmer like you and me.


 The compilation is done by the JAVAC compiler which is a primary Java compiler
included in the Java development kit (JDK). It takes the Java program as input and
generates bytecode as output.
 In the Running phase of a program, JVM executes the bytecode generated by the
compiler.

Java
ByteCode Machine code
interpreter
Now, we understood that the function of Java Virtual Machine is to execute the bytecode
produced by the compiler. Every Operating System has a different JVM but the output they
produce after the execution of bytecode is the same across all the operating systems. This is
why Java is known as a platform-independent language.

2. Bytecode in the Development process:


As discussed, the Javac compiler of JDK compiles the java source code into bytecode so that
it can be executed by JVM. It is saved as .class file by the compiler. To view the bytecode,
a disassembler like javap can be used.

3. Java Development Kit(JDK):


While we were using the term JDK when we learn about bytecode and JVM. So, as the name
suggests, it is a complete Java development kit that includes everything including compiler,
Java Runtime Environment (JRE), java debuggers, java docs, etc. For the program to execute
in java, we need to install JDK on our computer in order to create, compile and run the java
program.

4. Java Runtime Environment (JRE):


JDK includes JRE. JRE installation on our computers allows the java program to run,
however, we cannot compile it. JRE includes a browser, JVM, applet supports, and plugins.
For running the java program, a computer needs JRE.

5. Garbage Collector:
In Java, programmers can’t delete the objects. To delete or recollect that memory JVM has
a program called Garbage Collector. Garbage Collectors can recollect the objects that are not
referenced. So Java makes the life of a programmer easy by handling memory management.
However, programmers should be careful about their code whether they are using objects
that have been used for a long time. Because Garbage cannot recover the memory of objects
being referenced.
6. ClassPath:
The classpath is the file path where the java runtime and Java compiler look for .class files
to load. By default, JDK provides many libraries. If you want to include external libraries
they should be added to the classpath.

Primary/Main Features of Java

1. Platform Independent:
Compiler converts source code to bytecode and then the JVM executes the bytecode
generated by the compiler. This bytecode can run on any platform be it Windows, Linux, or
macOS which means if we compile a program on Windows, then we can run it on Linux and
vice versa. Each operating system has a different JVM, but the output produced by all the
OS is the same after the execution of bytecode. That is why we call java a platform-
independent language.
2. Object-Oriented Programming Language:
Organizing the program in the terms of collection of objects is a way of object-oriented
programming, each of which represents an instance of the class.
The four main concepts of Object-Oriented programming are:

 Abstraction (Its essential feature & without including bedground details)


 Encapsulation (wrapping up of data & method into single unit)
 Inheritance (new class derived from ,ain/super class on e class object acquire the
properties of another class objects)
 Polymorphism: Polymorphism means ability to take more than one Form. Ex:
Shape
3. Simple:
Java is one of the simple languages as it does not have complex features like pointers,
operator overloading, multiple inheritances, and Explicit memory allocation.

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

5. Secure:
In java, we don’t have pointers, so we cannot access out-of-bound arrays i.e it
shows ArrayIndexOutOfBound Exception if we try to do so. That’s why several security
flaws like stack corruption or buffer overflow are impossible to exploit in Java. Also java
programs run in an environment that is independent of the os(operating system) environment
which makes java programs more secure .

6. Distributed:
We can create distributed applications using the java programming language. Remote
Method Invocation and Enterprise Java Beans are used for creating distributed applications
in java. The java programs can be easily distributed on one or more systems that are
connected to each other through an internet connection.

7. Multithreading:
Java supports multithreading. It is a Java feature that allows concurrent execution of two or
more parts of a program for maximum utilization of the CPU.

8. Portable:
As we know, java code written on one machine can be run on another machine. The platform-
independent feature of java in which its platform-independent bytecode can be taken to any
platform for execution makes java portable.
9. High Performance:
Java architecture is defined in such a way that it reduces overhead during the runtime and at
some time java uses Just In Time (JIT) compiler where the compiler compiles code on-
demand basics where it only compiles those methods that are called making applications to
execute faster.

10. Dynamic flexibility:


Java being completely object-oriented gives us the flexibility to add classes, new methods
to existing classes and even create new classes through sub-classes. Java even supports
functions written in other languages such as C, C++ which are referred to as native methods.

11. Sandbox Execution:


Java programs run in a separate space that allows user to execute their applications without
affecting the underlying system with help of a bytecode verifier. Bytecode verifier also
provides additional security as its role is to check the code for any violation of access.

12. Write Once Run Anywhere:


As discussed above java application generates a ‘.class’ file which corresponds to our
applications(program) but contains code in binary format. It provides ease t architecture-
neutral ease as bytecode is not dependent on any machine architecture. It is the primary
reason java is used in the enterprising IT industry globally worldwide.

13. Power of compilation and interpretation:


Most languages are designed with purpose either they are compiled language or they are
interpreted language. But java integrates arising enormous power as Java compiler compiles
the source code to bytecode and JVM executes this bytecode to machine OS-dependent
executable code.
Java Tokens

In Java, the program contains classes and methods. Further, the methods contain the
expressions and statements required to perform a specific operation. These statements and
expressions are made up of tokens. In other words, we can say that the expression and
statement is a set of tokens. The tokens are the small building blocks of a Java program that
are meaningful to the Java

compiler. Further, these two components contain variables, constants, and operators. In this
section, we will discuss what is tokens in Java.
What is token in Java?

The Java compiler breaks the line of code into text (words) is called Java tokens. These are
the smallest element of the Java program

. The Java compiler identified these words as tokens. These tokens are separated by the
delimiters. It is useful for compilers to detect errors. Remember that the delimiters are not
part of the Java tokens.
Types of Tokens

Java token includes the following:

o Keywords
o Identifiers
o Literals
o Operators
o Separators
o Comments

Keywords:

These are the pre-defined reserved words of any programming language. Each keyword has
a special meaning. It is always written in lower case. Java provides the following keywords:

01. abstract 02. boolean 03. byte 04. break 05. class

06. case 07. catch 08. char 09. continue 10. default

11. do 12. double 13. else 14. extends 15. final

16. finally 17. float 18. for 19. if 20. implements

21. import 22. instanceof 23. int 24. interface 25. long

26. native 27. new 28. package 29. private 30. protected

31. public 32. return 33. short 34. static 35. super

36. switch 37. synchronized 38. this 39. thro 40. throws

41. transient 42. try 43. void 44. volatile 45. while

46. assert 47. const 48. enum 49. goto 50. strictfp

Identifier:

Identifiers are used to name a variable, constant, function, class, and array. It usually defined
by the user. It uses letters, underscores, or a dollar sign as the first character. The label is also
known as a special kind of identifier that is used in the goto statement. Remember that the
identifier name must be different from the reserved keywords. There are some rules to declare
identifiers are:
o The first letter of an identifier must be a letter, underscore or a dollar sign. It cannot start
with digits but may contain digits.
o The whitespace cannot be included in the identifier.

Identifiers are case sensitive.

o PhoneNumber
o PRICE
o radius
o a
o a1
o _phonenumber
o $circumference
o jagged_array
o 12radius //invalid

Literals:

In programming literal is a notation that represents a fixed value (constant) in the source code.
It can be categorized as an integer literal, string literal, Boolean literal, etc. It is defined by the
programmer. Once it has been defined cannot be changed. Java provides five types of literals
are as follows:

o Integer
o Floating Point
o Character
o String
o Boolean

Literal Type

23 int

9.86 double

false, true boolean

'K', '7', '-' char

"javatpoint" String

null any reference type


Operators:

In programming, operators are the special symbol that tells the compiler to perform a special
operation. Java provides different types of operators that can be classified according to the
functionality they provide. There are eight types of operators in Java

, are as follows:
o Arithmetic Operators
o Assignment Operators
o Relational Operators
o Unary Operators
o Logical Operators
o Ternary Operators
o Bitwise Operators
o Shift Operators

Operator Symbols

Arithmetic +,-,/,*,%

Unary ++ , - - , !

Assignment = , += , -= , *= , /= , %= , ^=

Relational ==, != , < , >, <= , >=

Logical && , ||

Ternary (Condition) ? (Statement1) : (Statement2);

Bitwise &,|,^,~

Shift << , >> , >>>

Separators: The separators in Java is also known as punctuators. There are nine separators
in Java, are as follows:

o Square Brackets []: It is used to define array elements. A pair of square brackets
represents the single-dimensional array, two pairs of square brackets represent the two-
dimensional array.
o Parentheses (): It is used to call the functions and parsing the parameters.
o Curly Braces {}: The curly braces denote the starting and ending of a code block.
o Comma (,): It is used to separate two values, statements, and parameters.
o Assignment Operator (=): It is used to assign a variable and constant.
o Semicolon (;): It is the symbol that can be found at end of the statements. It separates
the two statements.
o Period (.): It separates the package name form the sub-packages and class. It also
separates a variable or method from a reference variable.

Comments: Comments

allow us to specify information about the program inside our Java code. Java compiler
recognizes these comments as tokens but excludes it form further processing. The Java
compiler treats comments as whitespaces. Java provides the following two types of
comments:
o Line Oriented: It begins with a pair of forwarding slashes (//).
o Block-Oriented: It begins with /* and continues until it founds */.

Java Constant
As the name suggests, a constant is an entity in programming that is immutable.
In other words, the value that cannot be changed. In this section, we will learn
about Java constant and how to declare a constant in Java.
What is constant?

Constant is a value that cannot be changed after assigning it. Java does not directly
support the constants. There is an alternative way to define the constants in Java
by using the non-access modifiers static and final.

How to declare constant in Java?

In Java, to declare any variable as constant, we use static and final modifiers. It is
also known as non-access modifiers. According to the Java naming
convention the identifier name must be in capital letters.

Static and Final Modifiers

o The purpose to use the static modifier is to manage the memory.


o It also allows the variable to be available without loading any instance of the
class in which it is defined.
o The final modifier represents that the value of the variable cannot be
changed. It also makes the primitive data type immutable or unchangeable.

The syntax to declare a constant is as follows:

1. static final datatype identifier_name=value;

For example, price is a variable that we want to make constant.

1. static final double PRICE=432.78;

Where static and final are the non-access modifiers. The double is the data type
and PRICE is the identifier name in which the value 432.78 is assigned.

In the above statement, the static modifier causes the variable to be available
without an instance of its defining class being loaded and the final modifier makes
the variable fixed.

Here a question arises that why we use both static and final modifiers to declare
a constant?

If we declare a variable as static, all the objects of the class (in which constant is
defined) will be able to access the variable and can be changed its value. To
overcome this problem, we use the final modifier with a static modifier.

When the variable defined as final, the multiple instances of the same constant
value will be created for every different object which is not desirable.
When we use static and final modifiers together, the variable remains static and
can be initialized once. Therefore, to declare a variable as constant, we use both
static and final modifiers. It shares a common memory location for all objects of
its containing class.

Why we use constants?


The use of constants in programming makes the program easy and understandable
which can be easily understood by others. It also affects the performance because
a constant variable is cached by both JVM and the application.

Points to Remember:

o Write the identifier name in capital letters that we want to declare as constant.
For example, MAX=12.
o If we use the private access-specifier before the constant name, the value of
the constant cannot be changed in that particular class.
o If we use the public access-specifier before the constant name, the value of
the constant can be changed in the program.

Let's see some examples in which we have used constants.

Example 1: Declaring Constant as Private

import java.util.Scanner;
public class ConstantExample1
{
//declaring constant
private static final double PRICE=234.90;
public static void main(String[] args)
{
int unit;
double total_bill;
System.out.print("Enter the number of units you have used: ");
Scanner sc=new Scanner(System.in);
unit=sc.nextInt();
total_bill=PRICE*unit;
System.out.println("The total amount you have to deposit is: "+total_bill);
}
1. }

Output:

Declaring Constant as Public

In the following example, we have declared constant PI as public. Inside the main()
method, we have assigned 3.15 in the constant PI. After that, we have invoked the
printValue() method. When we execute the program, it shows an error cannot
assign a value to the final variable PI.

public class ConstantExample2


{
//declaring PI as constant
public static final double PI= 3.14;
public static void main(String[] args)
{
printValue();
//trying to assign 3.15 in the constant PI
PI = 3.15;
printValue();
}
void printValue()
{
System.out.print("The value of PI cannot be changed to " + PI);
}
}
Java Tokens

In Java, the program contains classes and methods. Further, the methods contain the
expressions and statements required to perform a specific operation. These statements and
expressions are made up of tokens. In other words, we can say that the expression and
statement is a set of tokens. The tokens are the small building blocks of a Java program that
are meaningful to the Java

compiler. Further, these two components contain variables, constants, and operators. In this
section, we will discuss what is tokens in Java.
What is token in Java?

The Java compiler breaks the line of code into text (words) is called Java tokens. These are
the smallest element of the Java program

. The Java compiler identified these words as tokens. These tokens are separated by the
delimiters. It is useful for compilers to detect errors. Remember that the delimiters are not
part of the Java tokens.
Types of Tokens

Java token includes the following:

o Keywords
o Identifiers
o Literals
o Operators
o Separators
o Comments

Keywords:

These are the pre-defined reserved words of any programming language. Each keyword has
a special meaning. It is always written in lower case. Java provides the following keywords:

01. abstract 02. boolean 03. byte 04. break 05. class

06. case 07. catch 08. char 09. continue 10. default

11. do 12. double 13. else 14. extends 15. final

16. finally 17. float 18. for 19. if 20. implements

21. import 22. instanceof 23. int 24. interface 25. long

26. native 27. new 28. package 29. private 30. protected

31. public 32. return 33. short 34. static 35. super

36. switch 37. synchronized 38. this 39. thro 40. throws

41. transient 42. try 43. void 44. volatile 45. while

46. assert 47. const 48. enum 49. goto 50. strictfp
Identifier:

Identifiers are used to name a variable, constant, function, class, and array. It usually defined
by the user. It uses letters, underscores, or a dollar sign as the first character. The label is also
known as a special kind of identifier that is used in the goto statement. Remember that the
identifier name must be different from the reserved keywords. There are some rules to declare
identifiers are:

o The first letter of an identifier must be a letter, underscore or a dollar sign. It cannot start
with digits but may contain digits.
o The whitespace cannot be included in the identifier.

Identifiers are case sensitive.

o PhoneNumber
o PRICE
o radius
o a
o a1
o _phonenumber
o $circumference
o jagged_array
o 12radius //invalid

Literals:

In programming literal is a notation that represents a fixed value (constant) in the source code.
It can be categorized as an integer literal, string literal, Boolean literal, etc. It is defined by the
programmer. Once it has been defined cannot be changed. Java provides five types of literals
are as follows:

o Integer
o Floating Point
o Character
o String
o Boolean
Literal Type

23 int

9.86 double

false, true boolean

'K', '7', '-' char

"javatpoint" String

null any reference type

Data Types in Java

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.

Java Primitive Data Types

In Java language, primitive data types are the building blocks of data manipulation. These are
the most basic data types available in Java language.

o boolean data type


o byte data type
o char data type
o short data type
o int data type
o long data type
o float data type
o double data type

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

There are two types of data types in Java: primitive and non-primitive.

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.

Types of Variables

There are three types of variables in Java:

o local variable
o instance variable
o static variable
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.

Ex: 1

Java Variable Example: Add Two Numbers

public classSimple
{
public static void main(String[] args)
{
int a=10;
int b=10;
int c=a+b;
System.out.println(c);
}
}
Out Put: 20
Ex: 2Java Variable Example: Widening

public classSimple
{
public static void main(String[] args)
{
int a=10;
float f=a;
System.out.println(a);
System.out.println(f);
}
}

Output: 10

10.0

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.

Operator Type Category Precedence

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 = += -= *= /= %= &= ^= |= <<= >>= >>>=

Unary Operator

The Java unary operators require only one operand. Unary operators are used to perform
various operations i.e.
o incrementing/decrementing a value by one
o negating an expression
o inverting the value of a boolean

Java Unary Operator Example: ++ and --

public class OperatorExample


{
public static void main(String args[])
{
int x=10;
System.out.println(x++);//10 (11)
System.out.println(++x);//12
System.out.println(x--);//12 (11)
System.out.println(--x);//10
}
}

Output:

10
12
12
10

Java Arithmetic Operators

Java arithmetic operators are used to perform addition, subtraction, multiplication, and
division. They act as basic mathematical operations.
Java Arithmetic Operator Example

public class OperatorExample


{
public static void main(String args[])
{
int a=10;
int b=5;
System.out.println(a+b);//15
System.out.println(a-b);//5
System.out.println(a*b);//50
System.out.println(a/b);//2
System.out.println(a%b);//0
}
}

Output:

15
5
50
2
0

Left Shift Operator

The Java left shift operator << is used to shift all of the bits in a value to the left side of a
specified number of times.

Java Left Shift Operator Example

public class OperatorExample


{
public static void main(String args[])
{
System.out.println(10<<2);//10*2^2=10*4=40
System.out.println(10<<3);//10*2^3=10*8=80
System.out.println(20<<2);//20*2^2=20*4=80
System.out.println(15<<4);//15*2^4=15*16=240
}
}

Output: Output:

40
80
80
240

Right Shift Operator

The Java right shift operator >> is used to move the value of the left operand to right by the
number of bits specified by the right operand.

Right Shift Operator Example

public OperatorExample
{
public static void main(String args[])
{
System.out.println(10>>2);//10/2^2=10/4=2
System.out.println(20>>2);//20/2^2=20/4=5
System.out.println(20>>3);//20/2^3=20/8=2
}
}

Output:

2
5
2

Java AND Operator Example: Logical && and Bitwise &

The logical && operator doesn't check the second condition if the first condition is false. It
checks the second condition only if the first one is true.
The bitwise & operator always checks both conditions whether first condition is true or false.

public class OperatorExample


{
public static void main(String args[])
{
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a<c);//false && true = false
System.out.println(a<b&a<c);//false & true = false
}
}

Output:

false
false

Java OR Operator Example: Logical || and Bitwise |

The logical || operator doesn't check the second condition if the first condition is true. It checks
the second condition only if the first one is false.

public class OperatorExample


{
public static void main(String args[])
{
int a=10;
int b=5;
int c=20;
System.out.println(a>b||a<c);//true || true = true
System.out.println(a>b|a<c);//true | true = true
//|| vs |
System.out.println(a>b||a++<c);//true || true = true
System.out.println(a);//10 because second condition is not checked
System.out.println(a>b|a++<c);//true | true = true
System.out.println(a);//11 because second condition is checked
}
}
Output:

true
true
true
10
true
11

Java Ternary Operator

Java Ternary operator is used as one line replacement for if-then-else statement and used a lot
in Java programming. It is the only conditional operator which takes three operands.

Java Ternary Operator Example

public class OperatorExample


{
Public static void main(String args[])
{
int a=2;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}
}

Output:

Assignment Operator

Java assignment operator is one of the most common operators. It is used to assign the value
on its right to the operand on its left.

Java Assignment Operator Example

public class OperatorExample


{
public static void main(String args[])
{
int a=10;
int b=20;
a+=4;//a=a+4 (a=10+4)
b-=4;//b=b-4 (b=20-4)
System.out.println(a);
System.out.println(b);
}
}

Output:

14
16

INPUT AND OUTPUT STATEMENTS:


An input/output statement or IO statement is a portion of a program that instructs a
computer how to read and process information. It pertains to gather information from an
input device, or sending information to an output device.

System.out.println() or
System.out.print() or
System.out.printf()
Scanf()
Cin>>

Difference between println(), print() and printf()

 print() - It prints string inside the quotes.


 println() - It prints string inside the quotes similar like print() method. Then the cursor
moves to the beginning of the next line.
 printf() - It provides string formatting (similar to printf in C/C++ programming).
Input

Java provides different ways to get input from the user. However, the user using the object
of Scanner class. To get the input.
In order to use the object of Scanner,
we need to import java.util.Scanner
package.

Import java.util.Scanner:
Class Input
{
Public static void main(String args[])
{
Scanner input = new Scanner(System.in)// creating new obj-----
System.out.prinln(“enter an integer”);
Int number=input.nectInt();
System.out.println(“you entered” +number);
Input.class();
}
}
Output:
enter an integer:
23
You entered
23

Type Casting

The process of converting the value of one data type (int, float, double, etc.) to another data
type is known as typecasting.
In Java, there are 13 types of type conversion. However, in this tutorial, we will only focus
on the major 2 types.

1. Widening Type Casting


2. Narrowing Type Casting

Widening Type Casting

In Widening Type Casting, Java automatically converts one data type to another data type.

class main
{
Public static void main(String args[])
{
int num=10;
System.ou.println(“the integer value is:”+num );
double data=num; //convert into double type
System.out.println(“then double value is:”+data”);
}
}

Output

The integer value: 10


The double value: 10.0

In the above example, we are assigning the int type variable named num to a double type
variable named data.
Here, the Java first converts the int type data into the double type. And then assign it to
the double variable.
In the case of Widening Type Casting, the lower data type (having smaller size) is
converted into the higher data type (having larger size). Hence there is no loss in data. This is
why this type of conversion happens automatically.
Narrowing Type Casting

In Narrowing Type Casting, we manually convert one data type into another using the
parenthesis.

Example: Converting double into an int

class main
{
Public static void main(String args[])
{
double num=10.99;
System.out.println(the double value is:” +num);
int data=(int)num; //manually…….
System.out.println(the double value is:” +data);
}
}

Output

The double value: 10.99


The integer value: 10

Enum Data Type:

The Enum in Java is a data type which contains a fixed set of constants and enum is a
keyword

It can be used for days of the week (SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
THURSDAY, FRIDAY, and SATURDAY) , directions (NORTH, SOUTH, EAST, and
WEST),
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.
class EnumExample1
{
public enum Season { WINTER, SPRING, SUMMER, FALL } //defining enum within c
lass

public static void main(String[] args) //creating the main method


{
//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:2

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;
}

}
The output will be:

Medium level

Conditional statements:
Conditional statements are mostly used in decision-making scenarios which means these
statements take a decision on the basis of some conditions. The conditional statements are also
referred as branching statements because the program takes a decision based on the result of the
assessed condition.

o if statement
o if-else statement
o if-else-if ladder
o nested if statement
if Statement:
The Java if statement tests the condition. It executes the if block if condition is true. If the given condition is
satisfied it will execute the true block statement only

Example Program:

public class IfExample


{
public static void main(String[] args)
{
//defining an 'age' variable
int age=18;
//checking the age
if(age>18)
{
System.out.print("You are eligible to vote");
}
}
}

if-else Statement
The Java if-else statement also tests the condition. It executes the if block if condition is true otherwise else
block is executed. It will execute either true block statement or false block statements.
Example Program:1

public class IfExample


{
public static void main(String[] args)
{
//defining an 'age' variable
int age=20;
//checking the age
if(age>18)
{
System.out.print("You are eligible to vote");
}
Else
{
System.out.println(“You are not eligible to vote”);
}
}
}
Output:
25
You are eligible to vote
if-else-if ladder Statement
The if-else-if ladder statement executes one condition from multiple statements. If the first condition is satisfy
it will execute the statement otherwise it will execute the next condition.

if(condition1)
{
//code to be executed if condition1 is true
}
else if(condition2)
{
//code to be executed if condition2 is true
}
else if(condition3)
{
//code to be executed if condition3 is true
}
...
Else
{
//code to be executed if all the conditions are false
}

Example Program:

public class IfElseIfExample


{
public static void main(String[] args)
{
int marks=65;

if(marks<50)
{
System.out.println("fail");
}
else if(marks>=50 && marks<60)
{
System.out.println("D grade");
}
else if(marks>=60 && marks<70)
{
System.out.println("C grade");
}
else if(marks>=70 && marks<80)
{
System.out.println("B grade");
}
else if(marks>=80 && marks<90)
{
System.out.println("A grade");
}
else if(marks>=90 && marks<100)
{
System.out.println("A+ grade");
}
else
{
System.out.println("Invalid!");
}
}
}

Output:

C Grade

Nested if statement:
The nested if statement represents the if block within another if block. Here, the inner if block condition
executes only when outer if block condition is true.
if(condition)
{
//code to be executed
if(condition)
{
//code to be executed
}
}

Example:
public class JavaNestedIfExample2
{
public static void main(String[] args)
{
//Creating two variables for age and weight
int age=25;
int weight=48;
//applying condition on age and weight
if(age>=18)
{
if(weight>50)
{
System.out.println("You are eligible to donate blood");
}
else
{
System.out.println("You are not eligible to donate blood");
}
}
else
{
System.out.println("Age must be greater than 18");
}
}
}

Output: 16

You are not eligible to donate blood


Switch Statement
The Java switch statement executes one statement from multiple conditions. It is like if-else-if ladder
statement. The switch statement works with byte, short, int, long, enum types, String and some wrapper types
like Byte, Short, Int, and Long. Since Java 7, you can use strings in the switch statement.

Syntax:
switch(expression)
{
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
………
default:
code to be executed if all cases are not matched;
}

Example program:
public class SwitchMonthExample
{
public static void main(String[] args)
{
//Specifying month number
int month=7;
String monthString="";
//Switch statement
switch(month)
{
//case statements within the switch block
case 1: monthString="1 - January";
break;
case 2: monthString="2 - February";
break;
case 3: monthString="3 - March";
break;
case 4: monthString="4 - April";
break;
case 5: monthString="5 - May";
break;
case 6: monthString="6 - June";
break;
case 7: monthString="7 - July";
break;
case 8: monthString="8 - August";
break;
case 9: monthString="9 - September";
break;
case 10: monthString="10 - October";
break;
case 11: monthString="11 - November";
break;
case 12: monthString="12 - December";
break;
default:System.out.println("Invalid Month!");
}
//Printing month of the given number
System.out.println(monthString);
}
}

Out put:
3 – March
Iteration Statements:

For Loop:
Iteration statements are used to execute a particular set of instructions repeatedly
until a particular condition is met or for a fixed number of iterations.
• The initialization statement is executed only once.
• Then, the test expression is evaluated. If the test expression is evaluated to
false, the for loop is terminated.
• However, if the test expression is evaluated to true, statements inside the
body of the for loop are executed,
• and the update expression is updated.
• Again the test expression is evaluated.
This process goes on until the test expression is false. When the test expression is
false, the loop terminates.
Example : Display numbers from 1 to 5
class Main
{
public static void main(String[] args)
{
int n = 5;
for (int i = 1; i <= n; ++i)
{
System.out.println(i);
}
}
}

Ex: 2---Display Sum of n Natural Numbers


class Main
{
public static void main(String[] args)
{
int sum = 0;
int n = 1000;
for(int i = 1; i <= n; ++i)
{
sum += i;
}
System.out.println("Sum = " + sum);
}
}
Output:
Sum = 500500
While Loop:

The Java while loop is used to iterate a part of the program repeatedly until the specified
Boolean condition is true. As soon as the Boolean condition becomes false, the loop
automatically stops.

The while loop is considered as a repeating if statement. If the number of iteration is not fixed,
it is recommended to use the while loop.

Syntax:
while (condition)
{
//code to be executed
Increment / decrement statement
}
Example: Sum of Positive Numbers Only

import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
int sum = 0; // create an object of Scanner class
Scanner input = new Scanner(System.in); // take integer input from the user
System.out.println("Enter a number");
int number = input.nextInt(); // while loop continues // until entered number is positive
while (number >= 0)
{ // add only positive numbers
sum += number;
System.out.println("Enter a number");
number = input.nextInt();
}
System.out.println("Sum = " + sum); input.close();
}
}
Output:
Enter a number
25
Enter a number
9
Enter a number
5
Enter a number
-3
Sum = 39
do-while Loop

The Java do-while loop is used to iterate a part of the program repeatedly, until the specified
condition is true. If the number of iteration is not fixed and you must have to execute the loop
at least once, it is recommended to use a do-while loop.

Java do-while loop is called an exit control loop. Therefore, unlike while loop and for loop,
the do-while check the condition at the end of loop body. The Java do-while loop is executed
at least once because condition is checked after loop body.

Syntax:

Do
{
//code to be executed / loop body
//update statement
}
While (condition);
In the below example, we print integer values from 1 to 10. Unlike the for loop, we
separately need to initialize and increment the variable used in the condition (here, i).
Otherwise, the loop will execute infinitely.

public class DoWhileExample


{
public static void main(String[] args)
{
int i=1;
do
{
System.out.println(i);
i++;
}
while(i<=10);
}
}

Output:

10
For-each loop in Java

The Java for-each loop or enhanced for loop is introduced since J2SE 5.0.
It provides an alternative approach to traverse the array or collection in
Java.
It is mainly used to traverse the array or collection elements.
The advantage of the for-each loop is that it eliminates the possibility of
bugs and makes the code more readable.
It is known as the for-each loop because it traverses each element one by
one.
The drawback of the enhanced for loop is that it cannot traverse the elements in
reverse order.

you do not have the option to skip any element because it does not work on an
index basis. Moreover, you cannot traverse the odd or even elements only.

For-each is another array traversing technique like for loop, while loop, do-while loop
introduced in Java5.

 It starts with the keyword for like a normal for-loop.


 Instead of declaring and initializing a loop counter variable, you declare a
variable that is the same type as the base type of the array, followed by a colon,
which is then followed by the array name.
 In the loop body, you can use the loop variable you created rather than using an
indexed array element.

 It’s commonly used to iterate over an array or a Collections class (eg, ArrayList).

Syntax:
for (type var : array)
{
statements using var;
}

is equivalent to:

for (int i=0; i<arr.length; i++)


{
type var = arr[i];
statements using var;
}

For-each loop Example: Traversing the collection elements


import java.util.*;
class ForEachExample2
{
public static void main(String args[])
{
//Creating a list of elements
ArrayList<String> list=new ArrayList<String>();
list.add("vimal");
list.add("sonoo");
list.add("ratan");
for(String s:list) //traversing the list of elements using for-each loop
{
System.out.println(s);
}
}
}
Output:
vimal
ratan
sonoo
ratan

Jump Statements in Java


Introduction:
Jumping statements are control statements that transfer execution control from one point to
another point in the program. There are two Jump statements that are provided in the Java
programming language:
1. Break statement.
2. Continue statement.
Or

The execution of a Java program is done in sequential order. Looping statements like for,
while, and do-while are used to execute a set of statements repeatedly. If such an execution
were to continue, it would go on forever. This can be prevented by adding appropriate
terminating conditions to the loop or by implementing jump statements. A jump statement
helps transfer the control of a program from one line of the code to another and skip the ones
in between.

1.Break Statement:
In java, the break statement is used to terminate the execution of the
nearest looping statement or switch statement. The break statement is widely used with the
switch statement, for loop, while loop, do-while loop.

Syntax:
break;

When a break statement is found inside a loop, the loop is terminated, and the control
reaches the statement that follows the loop. here is an example:

For( )//
For( ) {
{ For ( )
break;
} {
break;
import java.io.*; }
class Break
}
{
public static void main(String[] args)
{
int n = 10;
for (int i = 0; i < n; i++)
{
if (i == 6)
break;
System.out.println(i);
}
}
}
Output:
0
1
2
3
4
5

Example: 2
public class Break2
{
public static void main(String args[])
{
int i = 3;
switch(i)
{
case 1:
System.out.println("One");
break;
case 2:
System.out.println("Two");
break;
case 3:
System.out.println("Three");
break;
case 4:
System.out.println("Four");
break;
default:
System.out.println("Other");
}
}
}
Output :
Three

Goto:
The goto keyword is a commonly used jump statement in C/C++. However, Java uses
break statements to perform the same function as goto. Labels can be used to identify blocks
of code in Java. Any valid identifier followed by a semicolon represents a label. We can
break out of a labelled block by mentioning the label name after the break keyword.

Example: nested loop


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

// label for outer loop


outer:
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
if (j == 2)
break outer;
System.out.println(" value of j = " + j);
}
} // end of outer loop
} // end of main()
}

Output:
0
1
2

Example:2
class myClass
{
public static void main( String args[] )
{
label:
for (int i=0;i<6;i++)
{
if (i==3)
{
break label; // exits the loop when it reaches 3
}
System.out.println(i);
}
}
}
0
1
2

Continue statement:
Continue is a jump statement used when a loop’s current iteration is
to be skipped. It allows the control to temporarily exit the loop and ignore the remaining
statements that follow. After this jump, the control immediately moves with the next
iteration of the same loop.

public class Continue


{
public static void main(String args[])
{
For( )
for (int i = 10; i > 0 ;i--)
{
{
if (i%2 == 0) continue;
continue;
System.out.print(i+ " ");
}
}
}
}
Output:
9 7 5 3 1
Return statement:
The return keyword is used to transfer a program’s control
from a method back to the one that called it. Since the control jumps from one
part of the program to another, return is also a jump statement.

public class Return


{
public static int add(int a, int b)
{
int sum = a+b;
return sum;
}
public static void main(String[] args)
{
int x = 5, y = 10;
int sum = add(x, y);
System.out.println("Sum of a and b: " + sum);
}
}
Output:
Sum of a and b : 15
Note:
Qns.
What is the difference between the break and continue statement?
A break statement terminates its loop and resumes execution out of it. On the other hand, a
continue statement temporarily exits the loop and resumes with the next iteration.
Qns.
Is goto used in Java?
Unlike C/C++, Java does not use goto as a jump statement, but still considers it a
keyword. This means that it cannot be used as an identifier. The use of goto in
Java makes the code complex and difficult to understand. Hence, the break
statement handles the function of goto in a simpler way.
Printing Pattern Using Nested loops:
Introduction:
Pattern programs are patterns/designs/symbols consisting of numbers, alphabets or symbols
in a particular form. These kinds of pattern are solved using looping structures.

Design Patterns are introduced by architect Christopher Alexander and are used as best practices
for various other software developers’ commonly faced problems while creating software.

What is Pattern Printing Programs?


Pattern programs are patterns/ designs/ symbols
consisting of numbers, alphabets or symbols in a particular form. These kinds of pattern are
solved using looping structures.

Why study Pattern Printing Programs?


Pattern programs best means to study the working of looping structures in general
purpose programming languages.
Its helps beginners visualize how every iteration in a loop works.
Also popularly asked in campus placements & job interviews.

Advantages of Design Pattern in Java:

Design Patterns are a very popular problem-solving technique among software


developers.
It contains all the solutions for common software problems while developing and designing
software and has well-described solutions.

The codes are a re-usable form of a solution to the problem.

It is flexible and contains templates to solve while designing a system or application.

This helps in designing smart and flexible codes as per project requirements with suitable
objects, classes, loosely coupled codes, quick understanding strictures and many more.

Unwanted codes and problems can be easily identified and changed helpless work to
testers and maintainers of the application.

Client and end-users feel the interface more user-friendly and provide a good user
experience while working or using an application or software.

Why Should we use Design Pattern in Java?

In the IT industry, coding and application design, and structure play a key role in the
success of the application or software.

This jobs of designing effective software with easy and simple patterns can be done
using design patterns in java.
Many hugs and robust designs can be maintained and executed quickly because of
design patterns.

It identifies the common mistakes in coding in the phase of design and reduces the
cost of ownership.

Scope:
Design Patterns are very popular and are used by many professional companies
worldwide to design and develop software programs and application.

It has high industrial usage and helps design, test, maintain, and reuse the coding for
multiple processes.

It’s easy to fix the issue at any phase of the application due to its easy-to-understand
stricture to identify the code of the problem with suitable solutions to fix it.

It deals with dynamics change at runtime and class scopes at the time of built.

Note :
when two classes or modules or components have low dependency on each other is called as
loosely coupled codes.

Example:1
class ptr1
{
public static void main(String args[])
{
int i,j;
for(i=1;i<=5;i++)
{
for(j=1;j<=i;j++)
{
System.out.print("* ");
}
System.out.println();
}
}
}
Output:
*
**
***
****
*****

Example: 2
class ptr2
{
public static void main(String args[])
{
int i,j;
for(i=5;i>=1;i--)
{
for(j=1;j<=i;j++)
{
System.out.print("* ");
}
System.out.println();
}
}
}

Output:
*****
****
***
**
*

Arrays:
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.
type var-name[];
OR
type[] var-name;

Disadvantages:

Size Limit:

We can store only the fixed size of elements in the array. It doesn't grow its size at runtime.

Types of Array in java

There are two types of array.

o Single Dimensional Array


o Multidimensional Array

Single Dimensional Array:

One Dimensional Array in java is always used with only one subscript ([]).One
Dimensional Array in java is always used with only one subscript ( []). A one-dimensional
array behaves likes a list of variables. You can access the variables of an array by using an
index in square brackets preceded by the name of that array. Index value should be an
integer. Before using the array, we must declare it.

type var-name[];
OR
type[] var-name;

Example Program:1

class OnedimenisionaArray
{
public static void main(String[] args)
{
int[] arr; // declares an Array of integers.
arr = new int[5]; // allocating memory for 5 integers.
arr[0] = 10; // initialize the first elements of the array
arr[1] = 20; // initialize the second elements of the array
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
// accessing the elements of the specified array
for (int i = 0; i < arr.length; i++)
System.out.println("Element at index " + i + " : " + arr[i]);
}
}

Output:
Element at index 0 : 10
Element at index 1 : 20
Element at index 2 : 30
Element at index 3 : 40
Element at index 4 : 50

Multidimensional Arrays:
Multidimensional Arrays can be defined in simple words as array of arrays. Data in
multidimensional arrays are stored in tabular form (in row major order).
data_type[1st dimension][2nd dimension][]..[Nth dimension] array_name = new
data_type[size1][size2]….[sizeN];

 data_type: Type of data to be stored in the array. For example: int, char, etc.
 dimension: The dimension of the array created. For example: 1D, 2D, etc.
 array_name: Name of the array
 size1, size2, …, sizeN: Sizes of the dimensions respectively.

Two dimensional array:


2D array can be defined as an array of arrays. The 2D array is organized as
matrices which can be represented as the collection of rows and columns. The 2d
array represents with two sub scripts.
Initializing 2D Arrays

int arr[2][2] = {0,1,2,3};


int[][] twoD_arr = new int[10][20];

Two – dimensional Array (2D-Array)


Two – dimensional array is the simplest form of a multidimensional array. A two –
dimensional array can be seen as an array of one – dimensional array for easier
understanding.
Representation of 2D array in Tabular Format:
A two – dimensional array can be seen as a table with ‘x’ rows and ‘y’ columns where the
row number ranges from 0 to (x-1) and column number ranges from 0 to (y-1). A two –
dimensional array ‘x’ with 3 rows and 3 columns is shown below:

Example:2
public class TwoDimensional
{
public static void main(String args[])
{
// declaring and initializing 2D array
int arr[][]
= { { 2, 7, 9 }, { 3, 6, 1 }, { 7, 4, 2 } };
// printing 2D array
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
System.out.print(arr[i][j] + " ");

System.out.println();
}
}
}

Output:
279
361
742

Multidimensional array:
Three – dimensional array is a complex form of a
multidimensional array. A three – dimensional array can be seen as an array of two –
dimensional array for easier understanding. Multi-dimensional array represents with three
subscripts. Elements in three-dimensional arrays are commonly referred by x[i][j][k] where
‘i’ is the array number, ‘j’ is the row number and ‘k’ is the column number.
Example:3

class MultiDimensional
{
public static void main(String[] args)
{
int[][][] arr = { { { 1, 2 }, { 3, 4 } },
{ { 5, 6 }, { 7, 8 } } };
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
for (int k = 0; k < 2; k++)
{
System.out.print(arr[i][j][k] + " ");
}
System.out.println();
}
System.out.println();
}
}
}

Output:
12
34
56
78

Strings in java:
String manipulation is the most common part of the java program. String
represents a character of sequence of character/ group of character. That is easiest way to
represent a sequence of character in java by using a character array. String is fixed length
character it does not changed during the execution of a program.
Or
Java, a string is an object that represents a number of character
values. Each letter in the string is a separate character value that makes up the Java string
object. Characters in Java are represented by the char class. Users can write an array of char
values that will mean the same thing as a string.

Char Array Representation:


type var_name [ ] = new type[ ];
Example:
char CharArray[ ] = new char[4];
char CharArray[0] = ‘J’;
char CharArray[1] = ‘a’;
char CharArray[2] = ‘v’;
char CharArray[3] = ‘a’;

String Character Array:


String stringName;
StringName = new String (“String”);
Example:
String firstName;
firstName = new String(“SRIT”);

How to create a string object?

There are two ways to create String object:

1. By string literal
2. By new keyword

1) String Literal:
Java String literal is created by using double quotes. For Example:

String s="SRIT";
Each time you create a string literal, the JVM checks the "string
constant pool" first. If the string already exists in the pool, a reference to the pooled instance
is returned. If the string doesn't exist in the pool, a new string instance is created and placed
in the pool. For example:

1. String s1="csd";
2. String s2="SRIT";//It doesn't create a new instance

In the above example, only one object will be created. Firstly, JVM will not find any string
object with the value "Welcome" in string constant pool that is why it will create a new
object. After that it will find the string with the value "Welcome" in the pool, it will not
create a new object but will return the reference to the same instance.

2.By new keyword:

String s=new String("Welcome");//creates two objects and one reference variable

n such case, JVM

will create a new string object in normal (non-pool) heap memory, and the literal
"Welcome" will be placed in the string constant pool. The variable s will refer to the
object in a heap (non-pool).
Java String Example

public class StringExample


{
public static void main(String args[])
{
String s1="SRIT";//creating string by Java string literal
char ch[]={'A','N','A','N','T','H'};
String s2=new String(ch);//converting char array to string
String s3=new String("CSM and CSD");//creating Java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}
}

Output:
SRIT

ANANTH
CSM and CSD

Example:2

import java.io.*;
import java.lang.*;

class SRIT
{
public static void main(String[] args)
{
// Declare String without using new operator
String s = "SRIT";
// Prints the String.
System.out.println("String s = " + s);
// Declare String using new operator
String s1 = new String("Ananthapur");
// Prints the String.
System.out.println("String s1 = " + s1);
}
}

Output:

String s = SRIT
String s1 = Ananthapur

String Class:

How do you define a string in class?


A string is a class that defines objects that be
represented as a stream of characters. A character array is simply an array of characters
that can be terminated by a null character. In the case of strings, memory is allocated
dynamically.

The java.lang.String class provides many useful methods to perform operations on


sequence of char values.

String class methods

No. Method Description

1 char charAt(int index) It returns char value for the


particular index

2 int length() It returns string length


3 static String format(String format, Object... It returns a formatted string.
args)

4 static String format(Locale l, String format, It returns formatted string with


Object... args) given locale.

5 String substring(int beginIndex) It returns substring for given


begin index.

6 String substring(int beginIndex, int It returns substring for given


endIndex) begin index and end index.

7 boolean contains(CharSequence s) It returns true or false after


matching the sequence of char
value.

8 static String join(CharSequence delimiter, It returns a joined string.


CharSequence... elements)

9 static String join(CharSequence delimiter, It returns a joined string.


Iterable<? extends CharSequence>
elements)

10 boolean equals(Object another) It checks the equality of string


with the given object.

11 boolean isEmpty() It checks if string is empty.

12 String concat(String str) It concatenates the specified


string.

13 String replace(char old, char new) It replaces all occurrences of the


specified char value.

14 String replace(CharSequence old, It replaces all occurrences of the


CharSequence new) specified CharSequence.

15 static String equalsIgnoreCase(String It compares another string. It


another) doesn't check case.

16 String[] split(String regex) It returns a split string matching


regex.

17 String[] split(String regex, int limit) It returns a split string matching


regex and limit.

18 String intern() It returns an interned string.


19 int indexOf(int ch) It returns the specified char value
index.

20 int indexOf(int ch, int fromIndex) It returns the specified char value
index starting with given index.

21 int indexOf(String substring) It returns the specified substring


index.

22 int indexOf(String substring, int It returns the specified substring


fromIndex) index starting with given index.

23 String toLowerCase() It returns a string in lowercase.

24 String toLowerCase(Locale l) It returns a string in lowercase


using specified locale.

25 String toUpperCase() It returns a string in uppercase.

26 String toUpperCase(Locale l) It returns a string in uppercase


using specified locale.

27 String trim() It removes beginning and ending


spaces of this string.

28 static String valueOf(int value) It converts given type into string.


It is an overloaded method.

String Buffer 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.

Constructors of StringBuffer Class

Constructor Description
StringBuffer() It creates an empty String buffer with the initial capacity of
16.

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

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


capacity) length.

Methods of StringBuffer class:

Modifier and Method Description


Type

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


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

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

public replace(int startIndex, It is used to replace the string from specified


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

public delete(int startIndex, It is used to delete the string from specified


synchronized int endIndex) startIndex and endIndex.
StringBuffer

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 equal


minimumCapacity) 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 the
beginIndex) specified beginIndex.

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


beginIndex, int 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("SRIT"); //now original string is changed
System.out.println(sb); //prints Hello Java
}
}

Output:

Hello SRIT

2) StringBuffer insert() Method

he 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
}
}

Output:

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
}
}
Output:
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
}
}
Output:
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
}
}

Output:
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
}
}

Output:
16
16
34

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
}
}

Output:
16
16
34
34
70

StringTokenizer in Java:

The java.util.StringTokenizer class allows you to break a String into tokens. It is simple
way to break a String. It is a legacy class of Java.

It doesn't provide the facility to differentiate numbers, quoted strings, identifiers etc. like
StreamTokenizer class.

In the StringTokenizer class, the delimiters can be provided at the time of creation or one by
one to the tokens.
Constructors of the StringTokenizer Class:

There are 3 constructors defined in the StringTokenizer class.

Constructor Description

StringTokenizer(String str) It creates StringTokenizer with specified string.

StringTokenizer(String str, It creates StringTokenizer with specified string and


String delim) delimiter.

StringTokenizer(String str, It creates StringTokenizer with specified string, delimiter


String delim, boolean and returnValue. If return value is true, delimiter
returnValue) characters are considered to be tokens. If it is false,
delimiter characters serve to separate tokens.

Methods of the StringTokenizer Class:

The six useful methods of the StringTokenizer class are as follows:


Methods Description

boolean hasMoreTokens() It checks if there is more tokens available.

String nextToken() It returns the next token from the StringTokenizer object.

String nextToken(String delim) It returns the next token based on the delimiter.

boolean hasMoreElements() It is the same as hasMoreTokens() method.

Object nextElement() It is the same as nextToken() but its return type is Object.

int countTokens() It returns the total number of tokens.

1.Example of StringTokenizer Class:

Let's see an example of the StringTokenizer class that tokenizes a string "my name is khan"
on the basis of whitespace.
import java.util.StringTokenizer;
public class Simple
{
public static void main(String args[])
{
StringTokenizer st = new StringTokenizer("MyCollege Name SRIT-
Ananthapur"," ");
while (st.hasMoreTokens())
{
System.out.println(st.nextToken());
}
}
}
Output:
My
CollegeName
SRIT-
Ananthapur

2.Example of nextToken(String delim) method of the StringTokenizer class:

import java.util.*;
public class Test
{
public static void main(String[] args)
{
StringTokenizer st = new StringTokenizer("my,name,is,khan");
// printing next token
System.out.println("Next token is : " + st.nextToken(","));
}
}

Output:
Next token is : my

3.Example of hasMoreTokens() method of the StringTokenizer class:

This method returns true if more tokens are available in the tokenizer String otherwise
returns false.

import java.util.StringTokenizer;
public class StringTokenizer1
{
/* Driver Code */
public static void main(String args[])
{
/* StringTokenizer object */
StringTokenizer st = new StringTokenizer("Demonstrating methods from StringTokeni
zer class"," ");
/* Checks if the String has any more tokens */
while (st.hasMoreTokens())
{
System.out.println(st.nextToken());
}
}
}

Output:
Demonstrating
methods
from
StringTokenizer
Class

4.Example of hasMoreElements() method of the StringTokenizer class:

This method returns the same value as hasMoreTokens() method of StringTokenizer class.
The only difference is this class can implement the Enumeration interface.

import java.util.StringTokenizer;
public class StringTokenizer2
{
public static void main(String args[])
{
StringTokenizer st = new StringTokenizer("Hello Everyone we are SRIT College
Students"," ");
while (st.hasMoreElements())
{
System.out.println(st.nextToken());
}
}
}

Output:
HelloEveryone
we
are
SRIT
College
Students

5.Example of nextElement() method of the StringTokenizer class:

nextElement() returns the next token object in the tokenizer String. It can implement
Enumeration interface.

import java.util.StringTokenizer;
public class StringTokenizer3
{
/* Driver Code */
public static void main(String args[])
{
/* StringTokenizer object */
StringTokenizer st = new StringTokenizer("Hello Everyone Welcome to SRIT"," ");
/* Checks if the String has any more tokens */
while (st.hasMoreTokens())
{
/* Prints the elements from the String */
System.out.println(st.nextElement());
}
}
}

Output:
Hello
Everyone
Welcome
to
SRIT

6.Example of countTokens() method of the StringTokenizer class:

This method calculates the number of tokens present in the tokenizer String.

import java.util.StringTokenizer;
public class StringTokenizer3
{
/* Driver Code */
public static void main(String args[])
{
/* StringTokenizer object */
StringTokenizer st = new StringTokenizer("Hello Everyone Welcome to SRIT
Department of CSD and CSM "," ");
/* Prints the number of tokens present in the String */
System.out.println("Total number of Tokens: "+st.countTokens());
}
}

Output:
Total number of Tokens: 10

You might also like