You are on page 1of 83

Java Features

1. Case sensitivity
What is case sensitivity: Case sensitivity is the mechanism in which words can be differ
in meaning based on different use of uppercase and lowercase letters.
2. Java is Simple and platform Independent
The concept of Write-once-run-anywhere (known as the Platform independent) is one of
the important key feature of java language that makes java as the most powerful
language.
3. Java Enabled browsers
Java language is the most powerful language and is widely used in the web application.
Today most of the web browser are java compatible.
Java Tools
4. Java Compiler
To commence with Java programming, we must know the significance of Java Compiler.
5. Java Interpreter
We can run Java on most platforms provided a platform must has a Java interpreter.
6. Java Debugger
Java debugger helps in finding and the fixing of bugs in Java language programs.
7. Java Header File Generator
In Java programming we need to implement some native methods. To implement these
methods Javah generates C header and source files that are used by C programs to
reference an Object's instance variables from native source code.
8. JavaDoc
This tool is used to generate API documentation into HTML format from Java source
code.
9. Applet Viewer
Applet viewer is a command line program to run Java applets.

Introduction

What is case sensitivity


Case sensitivity in Computers

Case Sensitive and case insensitive Languages

Examples

What is case sensitivity: Case sensitivity is the mechanism in which words can be differ in
meaning based on different use of uppercase and lowercase letters. Sometime words can differ in
meaning with the same words while starts with capital letter with lowercase letters.
Case sensitivity in Computers: Case sensitivity is the mechanism by which computer compares
two words to decide whether they are equal, it may or may not consider words equal which only
differ in case.
Case Sensitive and case insensitive Languages: On the basis of case sensitivity, computer
languages can be divided into two parts. Computer languages like C, C++ and java are case
sensitive languages while others are case insensitive like BASIC and Pascal.
Examples:
The Java class Helloworld is a completely different class from the class HelloWorld.
public static void main(String args[]) is totally different from public static void main(string
args[]).
If you compare two strings in a case sensitive way then they are considered different if they
differ only in capitalization e.g. comparing the string by using the method String.compareTo, If
you compare two Strings in a case insensitive way then they are considered equal if they differ
only in capitalization. e.g. comparing the string with String.compareToIgnoreCase,

Java Features
Platform Independent
The concept of Write-once-run-anywhere (known as the Platform independent) is one of the
important key feature of java language that makes java as the most powerful language. Not even
a single language is idle to this feature but java is more closer to this feature. The programs
written on one platform can run on any platform provided the platform must have the JVM.
Simple
There are various features that makes the java as a simple language. Programs are easy to write

and debug because java does not use the pointers explicitly. It is much harder to write the java
programs that can crash the system but we can not say about the other programming languages.
Java provides the bug free system due to the strong memory management. It also has the
automatic memory allocation and deallocation system.
Object Oriented
To be an Object Oriented language, any language must follow at least the four characteristics.

Inheritance : It is the process of creating the new classes and using the behavior of the
existing classes by extending them just to
reuse the existing code and adding the
additional features as needed.
Encapsulation: : It is the mechanism of combining the information and providing the
abstraction.

Polymorphism: : As the name suggest one name multiple form, Polymorphism is the
way of providing the different functionality by the
functions having the same name based on the signatures of the methods.

Dynamic binding : Sometimes we don't have the knowledge of objects about their
specific types while writing our code. It is the way of providing the maximum
functionality to a program about the specific type at runtime.

Advertisement
As the languages like Objective C, C++ fulfills the above four characteristics yet they are not
fully object oriented languages because they are structured as well as object oriented languages.
But in case of java, it is a fully Object Oriented language because object is at the outer most
level of data structure in java. No stand alone methods, constants, and variables are there in java.
Everything in java is object even the primitive data types can also be converted into object by
using the wrapper class.
Robust
Java has the strong memory allocation and automatic garbage collection mechanism. It provides
the powerful exception handling and type checking mechanism as compare to other
programming languages. Compiler checks the program whether there any error and interpreter
checks any run time error and makes the system secure from crash. All of the above features
makes the java language robust.
Distributed
The widely used protocols like HTTP and FTP are developed in java. Internet programmers can
call functions on these protocols and can get access the files from any remote machine on the
internet rather than writing codes on their local system.
Portable
The feature Write-once-run-anywhere makes the java language portable provided that the
system must have interpreter for the JVM. Java also have the standard data size irrespective of

operating system or the processor. These features makes the java as a portable language.
Dynamic
While executing the java program the user can get the required files dynamically from a local
drive or from a computer thousands of miles away from the user just by connecting with the
Internet.
Secure
Java does not use memory pointers explicitly. All the programs in java are run under an area
known as the sand box. Security manager determines the accessibility options of a class like
reading and writing a file to the local disk. Java uses the public key encryption system to allow
the java applications to transmit over the internet in the secure encrypted form. The bytecode
Verifier checks the classes after loading.
Performance
Java uses native code usage, and lightweight process called threads. In the beginning
interpretation of bytecode resulted the performance slow but the advance version of JVM uses
the adaptive and just in time compilation technique that improves the performance.
Multithreaded
As we all know several features of Java like Secure, Robust, Portable, dynamic etc; you will be
more delighted to know another feature of Java which is Multithreaded.
Java is also a Multithreaded programming language. Multithreading means a single program
having different threads executing independently at the same time. Multiple threads execute
instructions according to the program code in a process or a program. Multithreading works the
similar way as multiple processes run on one computer.
Multithreading programming is a very interesting concept in Java. In multithreaded programs
not even a single thread disturbs the execution of other thread. Threads are obtained from the
pool of available ready to run threads and they run on the system CPUs. This is how
Multithreading works in Java which you will soon come to know in details in later chapters.
Interpreted
We all know that Java is an interpreted language as well. With an interpreted language such as
Java, programs run directly from the source code.
The interpreter program reads the source code and translates it on the fly into computations.
Thus, Java as an interpreted language depends on an interpreter program.
The versatility of being platform independent makes Java to outshine from other languages.
The source code to be written and distributed is platform independent.
Another advantage of Java as an interpreted language is its error debugging quality. Due to this
any error occurring in the program gets traced. This is how it is different to work with Java.
Architecture Neutral
The term architectural neutral seems to be weird, but yes Java is an architectural neutral
language as well. The growing popularity of networks makes developers think distributed. In the
world of network it is essential that the applications must be able to migrate easily to different

computer systems. Not only to computer systems but to a wide variety of hardware architecture
and Operating system architectures as well. The Java compiler does this by generating byte code
instructions, to be easily interpreted on any machine and to be easily translated into native
machine code on the fly. The compiler generates an architecture-neutral object file format to
enable a Java application to execute anywhere on the network and then the compiled code is
executed on many processors, given the presence of the Java runtime system. Hence Java was
designed to support applications on network. This feature of Java has thrived the programming
language.

Java Compiler
To commence with Java programming, we must know the significance of Java Compiler. When
we write any program in a text editor like Notepad, we use Java compiler to compile it. A Java
Compiler javac is a computer program or set of programs which translates java source code
into java byte code.
The output from a Java compiler comes in the form of Java class files (with .class extension).
The java source code contained in files end with the .java extension. The file name must be the
same as the class name, as classname.java. When the javac compiles the source file defined in a
.java files, it generates bytecode for the java source file and saves in a class file with a .class
extension.
The most commonly used Java compiler is javac, included in JDK from Sun Microsystems.
Following figure shows the working of the Java compiler:

Once the byte code is generated it can be run on any platform using Java Interpreter (JVM). It
interprets byte code (.class file) and converts into machine specific binary code. Then JVM runs

the binary code on the host machine.


How to use Java Compiler
When you run javac command on the command prompt, it shows the following output.
C:\>javac
Usage: javac <options> <source files>
where possible options include:
-g
Generate all debugging info
-g:none

Generate no debugging info

-g:{lines,vars,source}

Generate only some debugging info

-nowarn

Generate no warnings

-verbose

Output messages about what the compiler is doing

-deprecation
are

Output source locations where deprecated APIs


used

-classpath <path>

Specify where to find user class files and


annotation processors

-cp <path>

Specify where to find user class files and


annotation processors

-sourcepath <path>

Specify where to find input source files

-bootclasspath <path>

Override location of bootstrap class files

-extdirs <dirs>

Override location of installed extensions

-endorseddirs <dirs>

Override location of endorsed standards path

-proc:{none,only}

Control whether annotation processing and/or


compilation is done.

-processor <class1>[,<class2>,<class3>...]
Names of the annotation processors to run;
bypasses default discovery process
-processorpath <path>

Specify where to find annotation processors

-d <directory>

Specify where to place generated class files

-s <directory>

Specify where to place generated source files

-implicit:{none,class}

Specify whether or not to generate class files


for implicitly referenced files

-encoding <encoding>

Specify character encoding used by source files

-source <release>

Provide source compatibility with specified


release

-target <release>

Generate class files for specific VM version

-version

Version information

-help

Print a synopsis of standard options

-Akey[=value]

Options to pass to annotation processors

-X

Print a synopsis of nonstandard options

-J<flag>
C:\>

Pass <flag> directly to the runtime system

Above output shows the different options of javac tool.


Using java compiler to compile java file:
Following example shows how a Compiler works. It compiles the program and gives the Syntax
error, if there is any. Like in this example, we haven't initialized 'a' and we are using it in the next
statement as 'int c=a+b'. That is why its showing a syntax error.
class A{
public static void
main(String[] args){
int a;
int b=2;
int c=a+b;
System.out.println(c);
}
}
Output of program:
C:\Program
Files\Java\jdk1.6.0_01\bin>javac
A.java
A.java:6: variable a might not
have been initialized
int c=a+b;
^
1 error
C:\Program
Files\Java\jdk1.6.0_01\bin>

Now, lets tweak this example. In this we have initialized 'a' as 'int a =2'. Hence, no syntax error
has been detected.
class A{
public static void
main(String[] args) {
int a=2;
int b=2;
int c=a+b;
System.out.println(c);
}
}
Output of program:
C:\Program
Files\Java\jdk1.6.0_01\bin>javac
A.java
C:\Program
Files\Java\jdk1.6.0_01\bin>java A
4

Java Interpreter
We can run Java on most platforms provided a platform must has a Java interpreter. That is why
Java applications are platform independent. Java interpreter translates the Java bytecode into
the code that can be understood by the Operating System. Basically, A Java interpreter is a
software that implements the Java virtual machine and runs Java applications. As the Java
compiler compiles the source code into the Java bytecode, the same way the Java interpreter
translates the Java bytecode into the code that can be understood by the Operating System.
When a Java interpreter is installed on any platform that means it is JVM (Java virtual machine)
enabled platform. It (Java Interpreter) performs all of the activities of the Java run-time system.
It loads Java class files and interprets the compiled byte-code. You would be glad to know that
some web browsers like Netscape and the Internet Explorer are Java enabled. This means that
these browsers contain Java interpreter. With the help of this Java interpreter we download the
Applets from the Internet or an intranet to run within a web browser. The interpreter also serves
as a specialized compiler in an implementation that supports dynamic or "just in time,"

compilation which turns Java byte-code into native machine instructions.


Throughout Java programming, we'll build both, the standalone Java programs and applets.
Sun's Java interpreter is called java. Lets learn how to start a standalone application with it.
Load an initial class and specify it. Some options can also be specified to the interpreter, and any
command-line arguments needed for the application as well:
% java [interpreter options] class name [program arguments]
The class should be specified as a fully qualified class name including the class package, if any.
Note : Moreover, we don't include the .class file extension. Here are a few examples:
% java animals.birds.BigBird
% java test
Once the class is loaded, java follows a C-like convention and searches for the class that
contains a method called main(). If it finds an appropriate main() method, the interpreter starts
the application by executing that method. From there, the application starts additional threads,
reference other classes, and create its user interface.
Now, lets see how to go about an Applet. Although Java applet is a compiled Java code, the Java
interpreter can't directly run them because they are used as part of a larger applications. For this
we use Java Applet Viewer. It is a command line program to run Java applets. It is included in
the SDK. It helps you to test an applet before you run it in a browser. We will learn more about
it later.
The Figure below shows the working of Java Interpreter:

Java Debugger
Java debugger helps in finding and the fixing of bugs in Java language programs. The Java
debugger is denoted as jdb. It works like a command-line debugger for Java classes.
jdb session
The way to start the jdb session is to have jdb launch a new JVM (Java virtual machine) with
the main class. Then the application of the main class is debugged by substituting the command
jdb in command-line. For instance, if the main class of the application is TempClass, the
following command is used to debug it:
% jdb TempClass
There is another way to use jdb i.e.to attach jdb to Java VM which is already running.
There are few options which are used to debug a VM with jdb. These are:
option

purpose

-Xdebug

Enables
debugging in
the VM

Loads inprocess
debugging
libraries and
-Xrunjdwp:transport=dt_socket,server=y,suspend=n
specifies the
kind of
connection to be
made
The following command will run the TempClass application to which the jdb will connect
afterwords.
% java -Xdebug -Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n TempClass
Now the jdb will be attached to the VM in this way: % jdb -attach 8000
You can go through the basic jdb commands that the Java debugger supports.

cont
Ihis command Continues the execution of the debugged application after a breakpoint,
exception, or step.
run
Use run command to start the execution after starting jdb, and setting any necessary
breakpoints, use run command to start the execution . When jdb launches the debugged
application then only this command is available.
print
This command is used to display Java objects and primitive values. The actual value is printed
for the variables or fields of primitive types. For objects, a short description is printed.
Few examples of print command are:
print TempClass.myStaticField
print myObj.myInstanceField
print myObj.myMethod()
dump
This command is similar to print command. For objects, it is used to print the current value of
each field defined in the object including Static and instance fields.
The dump command supports the same set of expressions as the print command.
Exceptions
If any kind of exception occurs in the program, the VM will print an exception trace and exits. It
will only print this exception when there isn't any catch statement in the throwing thread's call
stack.
There is another command to be used to stop the debugged applications at other thrown
exceptions. The command is catch command. For instance, "catch
java.io.FileNotFoundException" or "catch mypackage.BigTroubleException.
Also the ignore command negates the effect of a previous catch command.
help, or ?
The command which helps in displaying the list of recognized commands is the help or ?
command.
threads
This command list the threads that are currently running. The name and current status are printed
for each thread. The index is also printed that can be used for other commands, for example:
4. (java.lang.Thread)0x1 main running
This example shows that the thread index is 4, the thread is an instance of java.lang.Thread, the
thread name is "main", and it is currently running.
thread
This command selects a thread to be the current thread. Some jdb commands are based on the

setting of the current thread. The thread index specifies the thread as explained in the threads
command above.
where
The command where is used to dump the stack of the current thread. Whereas the command
where all is used to dump the stack of all threads in the current thread group. And the where
thread index command is used to dump the stack of the specified thread.
Breakpoints
The way to use Breakpoints is to set it in jdb at line numbers or at the first instruction of a
method, for example:
stop at TempClass:14 (sets a breakpoint at the first instruction for line 14 of the source file
containing TempClass)
stop in TempClass.<init> (<init> identifies the TempClass constructor)
It is essential to specify the argument types whenever we overload any method in order to select
the proper method for a breakpoint. For example, "TempClass.myMethod(int,java.lang.String)",
or "TempClass.myMethod()".
We also use the clear command to remove breakpoints using a syntax as in "clear
TempClass:20" and the cont command continues execution.
Command Line Options
Use jdb in place of the Java application launcher on the command line, it accepts most of the
same options as the java command, which includes -D, -classpath, and -X<option>.
Some more options by jdb:
-sourcepath <dir1:dir2:...>
Uses the given path in searching for source files in the specified path. If this option is not
specified, the default path of "." is used.
-attach <address>
Attaches the debugger to previously running VM using the default connection mechanism.
-launch
As soon as the jdb start sup,launch option launches the debugged application immediately. We
need not to use the run command after using this option.
-Joption
It passes option to the Java virtual machine, where option is one of the options described on the
reference page for the java application launcher. For example, -J-Xms48m sets the startup
memory to 48 megabytes.
Lets tweak an example:
public class Y {
public static int add(int
a, int b)
{
return a+b;
}
public static int

sub(int a, int b)
{
return a-b;
}
public static void
main(String args[])
{
int a = 10;
int b = 20;
int c;
c = add(a, b);
System.out.println(c);
c = sub(a, b);
}

System.out.println(c);

After compiling and running the above program, we will initialize the java debugger and we will
use the Stop command to out a breakpoint. After that we will use run command to start the jdb.
In the similar way we can use other commands as well.
C:\javac>jdb Y
Initializing jdb ...
> stop at Y:6
Deferring breakpoint Y:6.
It will be set after the class is
loaded.
> run
run Y
Set uncaught
java.lang.Throwable
Set deferred uncaught
java.lang.Throwable
>
VM Started: Set deferred
breakpoint Y:6
Breakpoint hit: "thread=main",
Y.add(), line=6 bci=0
6 return a+b;
main[1] where
[1] Y.add (Y.java:6)
[2] Y.main (Y.java:17)
main[1] methods Y
** methods list **
Y <init>()
Y add(int, int)

Y sub(int, int)
Y main(java.lang.String[])
java.lang.Object <init>()
java.lang.Object
registerNatives()
java.lang.Object getClass()
java.lang.Object hashCode()
java.lang.Object
equals(java.lang.Object)
java.lang.Object clone()
java.lang.Object toString()
java.lang.Object notify()
java.lang.Object notifyAll()
java.lang.Object wait(long)
java.lang.Object wait(long, int)
java.lang.Object wait()
java.lang.Object finalize()
java.lang.Object <clinit>()

Javah - Header File Generator


In Java programming we need to implement some native methods. You must be wondering
about what's native methods.
Firstly, The native methods are in pure C code, not C++. The function prototypes are in an
object-oriented form of C which are being provided by javah , but they are still not object
methods.
Secondly, We can call native methods applications only. However due to some security reasons,
we cannot call applets from native methods.
Thirdly, native methods are platform-specific. This is the most important point to remember,
you have to build a dynamically loadable library to link your java application with the native
operating system (Windows OS, Machintosh, Linux, Unix ..). For each native platform your
application targets, a dynamically loadable library is needed to be shipped.. That means any
system-specific code has to be ported along with the java code.
On the other hand, native methods are the only way to use any system features not
provided by the Java Virtual Machine.
To implement these methods Javah generates C header and source files that are used by C
programs to reference an Object's instance variables from native source code. The name of the
header file and the structure declared within it are derived from the name of the class.

By default javah creates a header file for each class listed on the command line and puts the files
in the current directory. As stated above the name of the header file is derived from the name of
the class. If any class inside the package is passed to javah, the package name gets prepended to
both the header file name and the structure name.
Following are some options to use :
-o outputfile
This option concatenates the resulting header or source files for all the classes listed on the
command line into output file.
-help
Print help message for javah usage.
-d directory
This option sets the directory where javah saves the header files or the stub files. Only one of -d
or -o may be used.
-classpath path
Specifies the path javah used to look up classes. Overrides the default or the CLASSPATH
environment variable if it is set. Directories are separated by semi-colons. Thus the general
format for path is:
.;<your_path>
For example:
.;C:\users\dac\classes;C:\tools\java\classes
-stubs
Causes javah to generate C declarations from the Java object file.
-verbose
Indicates verbose output and causes javah to print a message to stdout concerning the status of
the generated files.
-version
Prints out javah version information.

Javadoc
Sun Microsystems has provided a computer software tool known as Javadoc. This tool is used
to generate API documentation into HTML format from Java source code. It is interesting to

know that Javadoc is the industry standard for documenting Java classes.
Javadoc is a program that is already included in JDK. We can use Javadoc to run over the source
code to produce documentation of our classes in the HTML files . We have to tag our code with
by using some comment formats to use javadoc tag on our source code. For instance Javadoc
comments looks like this:
NOTE : To start a Javadoc comments use /** to start, and */ to end, and use tags such as
@param, @return, and @exception in between to describe the workings of a method.
The format is given below to use the Javadoc comments:
/**
* Summary of the sentence.
* information about the
* program, class, method or variable
* then the comment, using as many lines
* as necessary.
*
* zero or more tags to specify any type
* of information, such as parameters and return
* values for a method
*/
Start with comment delimiter (/*) followed by another (*). The next line starts with an asterisk
and write as many line as you want starting with an asterisk. The last line ends with the delimiter
(*/). The first sentence to start with is a "summary sentence" showing the description of the
program, class, method or variable. We can write few more lines if required, but not any blank
lines. After writting the general description, a sequence of tags follows leaving a blank line.
Use different tags to display different situations. The example below shows a Javadoc comment
without tags that describes the variable declared immediately below it:
/**
* The number of employees in a company. This variable must not be
* negative or greater than 200.
*/
public int numEmployees;
One interesting thing to know about Javadoc comments is that we can embed HTML tags to
format the text. For example:
/**
* <B>Java declaration</B>
*/

Lets have a look on Javadoc tags


Tag
@version
@author
@return
@deprecated
@see
@param
@throws
@since
@exception
private
use
Windowtitle
Header
Footer
Bottom
Package
Protected
Classpath
noindex
nohelp
notree

Description
Shows the version number of a class or method.
Shows the Developer name
Documents the return value. This tag should not
be used for constructors or methods defined with a
void return type.
Marks a method as deprecated. Some IDEs will
issue a compilation warning if the method is
called.
Documents an association to another method or
class.
Defines a method parameter. Required for each
parameter.
Documents an exception thrown by a method. A
synonym for @exception introduced in Javadoc
1.2.
Documents when a method was added to a class.
Documents an exception thrown by a method ?
also see @throws.
Displays all classes and members
It creates class and package usage pages
It shows the window title of the document
It includes for header text of the page
It includes footer text for the page
It includes bottom text for the page
Shows package classes and members
shows protected classes and members
Helps to find user class files
doesn't provide the index
doesn't provide the help link
doesn't provide class hierarchy

To document source code developers use certain commenting styles and Javadoc tags. A Java
block comment starting with /** will begin a Javadoc comment block This comment block will
be included in the HTML. Some tags are provided in the above table which begins with an "@"
(at sign).

Java Comments
To comprehend any programming language, there are several kind of comments which are used.
These comments are advantageous in the sense that they make the programmer feel convenient
to grasp the logic of the program. Although these comments are ignored by the Java compiler,
they are included in the program for the convenience of the user to understand it. To provide the
additional information about the code, use comments. These comments give the overview of the
code in the form of the information which is not available in the code itself.
There are three types of comments used in Java. These are:
1. // text
To add a comment to the program, we can use two slashes characters i.e. //. The line starting
from slashes to the end is considered as a comment. We can write only a single line comment use
these slashes. For instance
// This comment extends to the end of the line.
// This type of comment is called a "slash-slash" comment
2. /* text */
To add a comment of more than one line, we can precede our comment using /*. The precise
way to use this is to start with delimiter /* and end with delimiter */. Everything in between
these two delimiters is discarded by the Java compiler. For instance
/* This comment, a "slash-star" comment, includes multiple lines.
* It begins with the slash-star sequence (with no space between
* the '/' and '*' characters) and extends to the star-slash sequence.
*/
Slash-star comments may also be placed between any Java tokens:
int i = /* maximum integer */ Integer.MAX_VALUE;
3. /** documentation */
This is a special type of comment that indicates documentation comment. This type of comment
is readable to both, computer and human. To start the comment, use /** instead of /* and end
with */. This type of comment is a documentation which is interpreted as an official document on
how the class and its public method work. For instance
/**
* These are used to extract documentation from the Java source.
*/

Comments in String Literals


Comments occurring in string literals are not parsed as comments. Like,
String text = "/* This is not a comment */";
Unicode Characters in Comments
Remember that Java still interprets Unicode sequences within comments. For example, Java
compiler processes the Unicode sequence \u002a\u002f (whose codepoints correspond to */) of
the source file, even before comments are processed. So we can use this format for Unicode
characters.
/* This is a comment. \u002a\u002f
String statement = "This is a comment.";
and is lexically equivalent to
/* This is a comment. */
String statement = "/* This is a comment. */";
(The '*' character is Unicode 002A and the '/' character is Unicode 002F).
This also applies to newline characters in slash-slash comments.
For example:
//This is a single line comment \u000a This is code
That is because the \u000a is the Unicode for a new line, here the compiler thinks that you have
added a new line.
This may be useful when declaring more than one thing on a line and you still wish to use // type
comments
int x = 0; //X is the value of the carr \u000a int y=0; //Y is the intrest

Java Keywords
There are few keywords in Java programming language. Remember, we cannot use these
keywords as identifiers in the program. The keywords const and goto are reserved though, they
are not being currently used.
The brief description of each one of the keyword is given below.
abstract
When a class is not to be instantiated, use abstract keyword but rather extended by other classes.
This keyword is used to in a method declaration to declare a method without providing the
implementation.

assert
It is used to define an assert statement. Any boolean condition in a program is declared with the
help of assert statement. The condition is checked at runtime if the program is running with
assertions . If the condition is false, the Java runtime system throws an AssertionError.
boolean
This keyword is used to pertain to an expression or variable that can have only a true or false
value.
byte
This is 8-bit integer. This keyword is used to declare an expression, method return value, or
variable of type byte.
case
This keyword is used to defines a group of statements. The value defined by the enclosing switch
statement should match with the specified value.
catch
This keyword is used to handle the exceptions that occur in a program preceding try keyword.
When the class of the thrown exception is assignment compatible with the exception class
declared by the catch clause then only the code is executed.
char
This Java keyword is used to declare an expression, method return value, or variable of type
character.
class
This keyword is used to define the implementation of a particular kind of object.
const
This keyword has been deprecated from Java programming language.
continue
This keyword is used for the continuation of the program at the end of the current loop body.
default
If the value defined by the enclosing switch statement does not match any value specified by a
case keyword in the switch statement, default keyword is used to define a group of statements to
begin the execution.
do
Used to declare a loop that will iterate a block of statements. The loop's exit condition is
specified with the while keyword. The loop will execute once before evaluating the exit
condition.
double

A 64-bit floating point value. A Java keyword used to declare an expression, method return
value, or variable of type double-precision floating point number.
else
This keyword is used to test the condition. It is used to define a statement or block of statements
that are executed in the case that the test condition specified by the if keyword evaluates to false.
enum
Enumerations extend the base class Enum.This Java keyword is used to declare an enumerated
type.
extends
To specify the superclass in a class declaration, extends keyword is used. It is also used in an
interface declaration to specify one or more superinterfaces.
final
It is used to define an entity once that cannot be altered nor inherited later. Moreover, a final
class cannot be subclassed, a final method cannot be overridden, and a final variable can occur at
most once as a left-hand expression. All methods in a final class are implicitly final.
finally
This keyword is used when the finally block is executed after the execution exits the try block
and any associated catch clauses regardless of whether an exception was thrown or caught.
break
Used to resume program execution at the statement immediately following the current enclosing
block or statement. If followed by a label, the program resumes execution at the statement
immediately following the enclosing labeled statement or block.
strictfp
To get the precise results in Floating point calculations use strictfp keyword regardless of any
operating system and hardware platform.

Java Data Types


Java programming language is a language in which all the variables must be declared first and
then to be used. That means to specify the name and the type of the variable. This specifies that
Java is a strongly-typed programming language. Like
int pedal = 1;

This shows that there exists a field named 'pedal' that holds a data as a numerical value '1'. The
values contained by the variables determines its data type and to perform the operations on it.
There are seven more primitive data types which are supported by Java language
programming in addition to int. A primitive data type is a data type which is predefined in
Java. Following are the eight primitive data types:
int
It is a 32-bit signed two's complement integer data type. It ranges from -2,147,483,648 to
2,147,483,647. This data type is used for integer values. However for wider range of values use
long.
byte
The byte data type is an 8-bit signed two's complement integer. It ranges from -128 to127
(inclusive). We can save memory in large arrays using byte. We can also use byte instead of int
to increase the limit of the code.
short
The short data type is a 16-bit signed two's complement integer. It ranges from -32,768 to
32,767. short is used to save memory in large arrays.
long
The long data type is a 64-bit signed two's complement integer. It ranges from
-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807. Use this data type with larger range
of values.
float
The float data type is a single-precision 32-bit IEEE 754 floating point. It ranges from
1.40129846432481707e-45 to 3.40282346638528860e+38 (positive or negative). Use a float
(instead of double) to save memory in large arrays. We do not use this data type for the exact
values such as currency. For that we have to use java.math.BigDecimal class.
double
This data type is a double-precision 64-bit IEEE 754 floating point. It ranges from
4.94065645841246544e-324d to 1.79769313486231570e+308d (positive or negative). This data
type is generally the default choice for decimal values.
boolean
The boolean data type is 1-bit and has only two values: true and false. We use this data type for
conditional statements. true and false are not the same as True and False. They are defined
constants of the language.
char
The char data type is a single 16-bit, unsigned Unicode character. It ranges from 0 to 65,535.
They are not same as ints, shorts etc.
The following table shows the default values for the data types:

Keyword Description
Byte-length
byte
integer
short

Short integer

int

Integer

long

Long integer

Size/Format
8-bit two's
complement
16-bit two's
complement
32-bit two's
complement
64-bit two's
complement

Single-precision
32-bit IEEE
floating point
Double-precision
double
64-bit IEEE
floating point
16-bit Unicode
char
A single character
character
A boolean value
boolean
true or false
(true or false)
float

When we declare a field it is not always essential that we initialize it too. The compiler sets a
default value to the fields which are not initialized which might be zero or null. However this is
not recommended.

Java Literals
By literal we mean any number, text, or other information that represents a value. This means
what you type is what you get. We will use literals in addition to variables in Java statement.
While writing a source code as a character sequence, we can specify any value as a literal such as
an integer. This character sequence will specify the syntax based on the value's type. This will
give a literal as a result. For instance
int month = 10;
In the above statement the literal is an integer value i.e 10. The literal is 10 because it directly
represents the integer value.
In Java programming language there are some special type of literals that represent numbers,
characters, strings and boolean values. Lets have a closer look on each of the following.

Integer Literals
Integer literals is a sequence of digits and a suffix as L. To represent the type as long integer we
use L as a suffix. We can specify the integers either in decimal, hexadecimal or octal format. To
indicate a decimal format put the left most digit as nonzero. Similarly put the characters as ox to
the left of at least one hexadecimal digit to indicate hexadecimal format. Also we can indicate
the octal format by a zero digit followed by the digits 0 to 7. Lets tweak the table below.
Decimal integer literal of
type long integer
Hexadecimal integer literal
0x4a
of type integer
Octal integer literal of type
057L
long integer
659L

Character Literals
We can specify a character literal as a single printable character in a pair of single quote
characters such as 'a', '#', and '3'. You must be knowing about the ASCII character set. The ASCII
character set includes 128 characters including letters, numerals, punctuations etc. There are few
character literals which are not readily printable through a keyboard. The table below shows the
codes that can represent these special characters. The letter d such as in the octal, hex etc
represents a number.
Escape
\n
\t
\b
\r
\f
\\
\'
\"
\d
\xd
\ud

Meaning
New line
Tab
Backspace
Carriage return
Formfeed
Backslash
Single quotation
mark
Double
quotation mark
Octal
Hexadecimal
Unicode
character

It is very interesting to know that if we want to specify a single quote, a backslash, or a


nonprintable character as a character literal use an escape sequence. An escape sequence uses a
special syntax to represents a character. The syntax begins with a single backslash character.

Lets see the table below in which the character literals use Unicode escape sequence to represent
printable and nonprintable characters both.
Capital letter
A
'\u0030' Digit 0
Double quote
'\u0022'
"
'\u003b' Punctuation ;
'\u0020' Space
Horizontal
'\u0009'
Tab
'u0041'

Boolean Literals
The values true and false are also treated as literals in Java programming. When we assign a
value to a boolean variable, we can only use these two values. Unlike C, we can't presume that
the value of 1 is equivalent to true and 0 is equivalent to false in Java. We have to use the values
true and false to represent a Boolean value. Like
boolean chosen = true;
Remember that the literal true is not represented by the quotation marks around it. The Java
compiler will take it as a string of characters, if its in quotation marks.
Floating-point literals
Floating-point numbers are like real numbers in mathematics, for example, 4.13179, -0.000001.
Java has two kinds of floating-point numbers: float and double. The default type when you write
a floating-point literal is double.
Type

Size

Range

Precision

name bytes bits approximate in decimal digits


float
double

4
8

32

+/- 3.4 * 1038

6-7

308

15

64 +/- 1.8 * 10

A floating-point literal can be denoted as a decimal point, a fraction part, an exponent


(represented by E or e) and as an integer. We also add a suffix to the floating point literal as D, d,
F or f. The type of a floating-point literal defaults to double-precision floating-point.
The following floating-point literals represent double-precision floating-point and floating-point
values.
6.5E+32 (or Double-precision
6.5E32)
floating-point literal
7D

Double-precision
floating-point literal

.01f

Floating-point literal

String Literals
The string of characters is represented as String literals in Java. In Java a string is not a basic data
type, rather it is an object. These strings are not stored in arrays as in C language. There are few
methods provided in Java to combine strings, modify strings and to know whether to strings have
the same value.
We represent string literals as
String myString = "How are you?";
The above example shows how to represent a string. It consists of a series of characters inside
double quotation marks.
Lets see some more examples of string literals:
"" // the empty string
"\"" // a string containing "
"This is a string" // a string containing 16 characters
"This is a " + // actually a string-valued constant expression,
"two-line string" // formed from two string literals
Strings can include the character escape codes as well, as shown here:
String example = "Your Name, \"Sumit\"";
System.out.println("Thankingyou,\nRichards\n");
Null Literals
The final literal that we can use in Java programming is a Null literal. We specify the Null literal
in the source code as 'null'. To reduce the number of references to an object, use null literal. The
type of the null literal is always null. We typically assign null literals to object reference
variables. For instance
s = null;
An this example an object is referenced by s. We reduce the number of references to an object by
assigning null to s. Now, as in this example the object is no longer referenced so it will be
available for the garbage collection i.e. the compiler will destroy it and the free memory will be
allocated to the other object. Well, we will later learn about garbage collection.

Introduction to Java Arrays


In this section you will be introduced to the concept of Arrays in Java Programming language.
You will learn how the Array class in java helps the programmer to organize the same type of
data into easily manageable format.

Program data is stored in the variables and takes the memory spaces, randomly. However, when
we need the data of the same type to store in the contiguous memory allocations we use the data
structures like arrays. To meet this feature java has provided an Array class which abstracts the
array data-structure.
The java array enables the user to store the values of the same type in contiguous memory
allocations. Arrays are always a fixed length abstracted data structure which can not be altered
when required.
The Array class implicitly extends java.lang.Object so an array is an instance of Object.
Structure of Arrays
Now lets study the structure of Arrays in java. Array is the most widely used data structure in
java. It can contain multiple values of the same type. Moreover, arrays are always of fixed length
i.e. the length of an array cannot be increased or decreased.
Lets have a close look over the structure of Array. Array contains the values which are implicitly
referenced through the index values. So to access the stored values in an array we use indexes.
Suppose an array contains "n" integers. The first element of this array will be indexed with the
"0" value and the last integer will be referenced by "n-1" indexed value.
Presume an array that contains 12 elements as shown in the figure. Each element is holding a
distinct value. Here the first element is refrenced by a[0] i.e. the first index value. We have filled
the 12 distinct values in the array each referenced as:
a[0]=1
a[1]=2
...
a[n-1]=n
...
a[11]=12
The figure below shows the structure of an Array more precisely.

Array Declaration
As we declare a variable in Java, An Array variable is declared the same way. Array variable has
a type and a valid Java identifier i.e. the array's type and the array's name. By type we mean the
type of elements contained in an array. To represent the variable as an Array, we use [] notation.
These two brackets are used to hold the array of a variable.
By array's name, we mean that we can give any name to the array, however it should follow the
predefined conventions. Below are the examples which show how to declare an array :int[] array_name; //declares an
array of integers
String[] names;
int[][] matrix; //this is an array
of arrays
It is essential to assign memory to an array when we declare it. Memory is assigned to set the
size of the declared array. for example:
int[] array_name =
new int[5];

Here is an example that creates an array that has 5 elements.


public class Array
{
public static void
main(String[] args)
{
int[] a = new int[5];
}
}

Array Initialization

After declaring an array variable, memory is allocated to it. The "new" operator is used for the
allocation of memory to the array object. The correct way to use the "new" operator is
String names[];
names = new String[10];
Here, the new operator is followed by the type of variable and the number of elements to be
allocated. In this example [] operator has been used to place the number of elements to be
allocated.
Lets see a simple example of an array,
public class Sum
{
public static void main(String[] args)
{
int[] x = new int [101];
for (int i = 0; i<x.length; i++ )
x[i] = i;
int sum = 0;
for(int i = 0; i<x.length; i++)
sum += x[i];
System.out.println(sum);
}
}

In this example, a variable 'x' is declared which has a type array of int, that is, int[]. The
variable x is initialized to reference a newly created array object. The expression 'int[] = new
int[50]' specifies that the array should have 50 components. To know the length of the Array, we
use field length, as shown.
Output for the given program:
C:\tamana>javac
Sum.java
C:\tamana>java
Sum
5050
C:\tamana>

Array Usage
We have already discussed that to refer an element within an array, we use the [] operator. The []
operator takes an "int" operand and returns the element at that index. We also know that the array

indices start with zero, so the first element will be held by the 0 index. For Example :int month = months[4]; //get the 5th month (May)
Most of the times it is not known in the program that which elements are of interest in an array.
To find the elements of interest in the program, it is required that the program must run a loop
through the array. For this purpose "for" loop is used to examine each element in an array. For
example :String months[] =
{"Jan", "Feb", "Mar", "Apr",
"May", "Jun",
"July", "Aug", "Sep",
"Oct", "Nov", "Dec"};
//use the length attribute
to get the number
//of elements in an array
for (int i = 0; i <
months.length; i++ ) {
System.out.println("month:
" + month[i]);

Here, we have taken an array of months which is,


String months[] =
{"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"July", "Aug", "Sep", "Oct", "Nov", "Dec"};
Now, we run a for loop to print each element individually starting from the month "Jan".
for (int i = 0; i < months.length; i++ )
In this loop int i = 0; indicates that the loop starts from the 0th position of an array and goes upto
the last position which is length-1, i < months.length; indicates the length of the array and i++
is used for the increment in the value of i which is i = i+1.
Multi-dimensional arrays
So far we have studied about the one-dimensional and two-dimensional arrays. To store data in
more dimensions a multi-dimensional array is used. A multi-dimensional array of dimension n is
a collection of items. These items are accessed via n subscript expressions. For example, in a
language that supports it, the element of the two-dimensional array x is denoted by x[i,j].
The Java programming language does not really support multi-dimensional arrays. It does,
however, supports an array of arrays. In Java, a two-dimensional array ' x' is an array of onedimensional array : For instance :int[][] x = new int[3][5];

The expression x[i] is used to select the one-dimensional array; the expression x[i][j] is ued to
select the element from that array. The first element of this array will be indexed with the "0"
value and the last integer will be referenced by "length-1" indexed value. There is no array
assignment operator.
Two-dimensional arrays
Two-dimensional arrays are defined as "an array of arrays". Since an array type is a first-class
Java type, we can have an array of ints, an array of Strings, or an array of Objects. For example,
an array of ints will have the type int[]. Similarly we can have int[][], which represents an "array
of arrays of ints". Such an array is said to be a two-dimensional array.
The command
int[][] A = new int[3][4]
declares a variable, A, of type int[][], and it initializes that variable to refer to a newly created
object. That object is an array of arrays of ints. Here, the notation int[3][4] indicates that there
are 3 arrays of ints in the array A, and that there are 4 ints in each of those arrays.
To process a two-dimensional array, we use nested for loops. We already know about for loop. A
loop in a loop is called a Nested loop. That means we can run another loop in a loop.
Notice in the following example how the rows are handled as separate objects.
Code: Java
int[][] a2 = new int[10][5];
// print array in
rectangular form
for (int r=0; r<a2.length;
r++) {
for (int c=0;
c<a2[r].length; c++) {
System.out.print(" "
+ a2[r][c]);
}
System.out.println("");
}

In this example, "int[][] a2 = new int[10][5];" notation shows a two-dimensional array. It


declares a variable a2 of type int[][],and it initializes that variable to refer to a newly created
object. The notation int[10][5] indicates that there are 10 arrays of ints in the array a2, and that
there are 5 ints in each of those arrays.
Copying Arrays
After learning all about arrays, there is still one interesting thing left to learn i.e. copying arrays.
It means to copy data from one array to another. The precise way to copy data from one array to
another is
public static void

arraycopy(Object source,
int
srcIndex,
Object
dest,
int
destIndex,
int
length)

Thus apply system's arraycopy method for copying arrays.The parameters being used are :src the source array
srcIndex start position (first cell to
copy) in the source array
dest the destination array
destIndex start position in the
destination array
length the number of array elements to
be copied
The following program, ArrayCopyDemo(in a .java source file), uses arraycopy to copy some
elements from the copyFrom array to the copyTo array.

public class ArrayCopyDemo{


public static void main(String[] args){
char[] copyFrom = {'a','b','c','d','e','f','g','h','i','j'};
char[] copyTo = new char[5];
System.arraycopy(copyFrom, 2, copyTo, 0, 5);
System.out.println(new String (copyTo));
}
}

In this example the array method call begins the copy of elements from element number 2. Thus
the copy begins at the array element 'c'. Now, the arraycopy method takes the copie element and
puts it into the destination array. The destination array begins at the first element (element 0)
which is the destination array copyTo. The copyTo copies 5 elements : 'c', 'd', 'e', 'f', 'g'. This
method will take "cdefg" out of "abcdefghij", like this :

Operators

Operators are symbols that performs some operations on one or more than one operands. Once
we declare and initialize variables, we can use operators to perform certain tasks like addition,
subtraction etc.
Simple Assignment Operator
=

Simple assignment operator

Arithmetic Operators
+ Additive operator (also used for String concatenation)
- Subtraction operator
* Multiplication operator
/ Division operator
% Remainder operator
Unary Operators
+ Unary plus operator; indicates positive value (numbers are positive without this, however)
- Unary minus operator; negates an expression
++ Increment operator; increments a value by 1
-- Decrement operator; decrements a value by 1
! Logical compliment operator; inverts the value of a boolean
Equality and Relational Operators
== Equal to
!= Not equal to
> Greater than
>= Greater than or equal to
< Less than
<= Less than or equal to
Conditional Operators
&& Conditional-AND
|| Conditional-OR
?: Ternary (shorthand for if-then-else statement)
Type Comparison Operator
instanceof Compares an object to a specified type
Bitwise and Bit Shift Operators
~ Unary bitwise complement

<< Signed left shift


>> Signed right sift
>>> Unsigned right shift
& Bitwise AND
^ Bitwise exclusive OR
| Bitwise inclusive OR
These operators follow some precedence to apply. The table below shows the list of operators
that follow the precedence. Operators with higher precedence are evaluated before operators with
relatively lower precedence. However, Operators on the same line have equal precedence. The
rule to deal with equal precedence operators is that all binary operators except for the assignment
operators are evaluated from left to right; assignment operators are evaluated right to left.
Operators
postfix
unary
multiplicative
additive
shift
relational
equality
bitwise AND
bitwise exclusive
OR
bitwise inclusive
OR
logical AND
logical OR
ternary
assignment

Precedence
expr++,, expr-++expr, --expr, +expr,
-expr ~ !
*/%
+<< >> >>>
< > , <= , >= instanceof
== , !=
&
^
|
&&
||
?:
= , +=, -=, *=, /=, %=,
&=, ^=, |=, <<=, >>=,
>>, >=

Controlling your program


We all know that the execution of the statements in a program takes place from top to bottom.
We will learn how the different kinds of statement have different effects in looping like decision-

making statements (if-then, if-then-else, switch), the looping statements (for, while, do-while),
and the branching statements (break, continue, return) in Java programming language.
Selection
In this section we will learn how to use if-then, if-the else and switch statements in Java
programming. These are the two alternative structure statements in Java.
The if statement
To start with controlling statements in Java, lets have a recap over the control statements in C++.
You must be familiar with the if-then statements in C++. The if-then statement is the most
simpler form of control flow statement. It directs the program to execute a certain section of
code. This code gets executed if and only if the test evaluates to true. That is the if statement in
Java is a test of any boolean expression. The statement following the if will only be executed
when the boolean expression evaluates to true. On the contrary if the boolean expression
evaluates to false then the statement following the if will not only be executed.
Lets tweak the example below:
if (a > 1)
System.out.println("Greater than 1");
if (a < 1)
System.out.println("Less than 1");
In the above example if we declare int a = 1, the statements will show some of the valid boolean
expressions to the if statement.
We are talking about if statements here so we can't forget the else statement here. The if
statement is incomplete without the else statement. The general form of the statement is:
if (condition)
statement1;
else
statement2;
The above format shows that an else statement will be executed whenever an if statement
evaluates to false. For instance,
if (a>1){
System.out.println("greater than 1");
}
else{
System.out.println("smaller than 1");
}
Lets have a look at a slightly different example as shown below:
class compare{
public static void main(String[] args){
int a = 20;

int b = 40;
if (a<b){
System.out.println("a is smaller");
}
else{
System.out.println("b is smaller");
}
}

The above example shows that we have taken two numbers and we have to find the smallest
amongst them. We have applied a condition that if a<b, print 'a is smaller' else print 'b is smaller'.
The following is the output which we will get in the command prompt.
C:\javac>javac
compare.java
C:\javac>java
compare
a is smaller
The switch statement
Sometimes it becomes cumbersome to write lengthy programs using if and if-else statements. To
avoid this we can use Switch statements in Java. The switch statement is used to select multiple
alternative execution paths. This means it allows any number of possible execution paths.
However, this execution depends on the value of a variable or expression. The switch statement
in Java is the best way to test a single expression against a series of possible values and
executing the code.
Here is the general form of switch statement:
switch (expression){
case 1:
code block1
case 2:
code block2
.
.
.
default:
code default;
}
The expression to the switch must be of a type byte, short, char, or int. Then there is a code block
following the switch statement that comprises of multiple case statements and an optional default
statement.
The execution of the switch statement takes place by comparing the value of the expression with
each of the constants. The comparison of the values of the expression with each of the constants

occurs after the case statements. Otherwise, the statements after the default statement will be
executed.
Now, to terminate a statement following a switch statement use break statement within the code
block. However, its an optional statement. The break statement is used to make the computer
jump to the end of the switch statement. Remember, if we won't use break statement the
computer will go ahead to execute the statements associated with the next case after executing
the first statement.
Here is an example which will help you to understand more easily:
switch (P { // assume P is an integer variable
case 1:
System.out.println("The number is 1.");
break;
case 2:
case 4:
case 8:
System.out.println("The number is 2, 4, or 8.");
System.out.println("(That's a power of 2!)");
break;
case 3:
case 6:
case 9:
System.out.println("The number is 3, 6, or 9.");
System.out.println("(That's a multiple of 3!)");
break;
case 5:
System.out.println("The number is 5.");
break;
default:
System.out.println("The number is 7,");
System.out.println(" or is outside the range 1 to 9.");
}
For example the following program Switch, declares an int named week whose value represents
a day out of the week. The program displays the name of the day, based on the value of week,
using the switch statement.
class Switch{
public static void main(String[] args){
int week = 5;
switch (week){
case 1: System.out.println("monday"); break;
case 2: System.out.println("tuesday"); break;
case 3: System.out.println("wednesday"); break;
case 4: System.out.println("thursday"); break;
case 5: System.out.println("friday"); break;
case 6: System.out.println("saturday"); break;

case 7:

System.out.println("sunday"); break;

default: System.out.println("Invalid week");break;


}
}
}

In this case, "friday" is printed to standard output.


C:\javac>javac
Switch.java
C:\javac>java
Switch
friday
One other point to note here is that the body of a switch statement is known as a switch block.
The appropriate case gets executed when the switch statement evaluates its expression.
Iteration
The concept of Iteration has made our life much more easier. Repetition of similar tasks is what
Iteration is and that too without making any errors. Until now we have learnt how to use
selection statements to perform repetition. Now lets have a quick look at the iteration statements
which have the ability to loop through a set of values to solve real-world problems.
The for Statement
In the world of Java programming, the for loop has made the life much more easier. It is used to
execute a block of code continuously to accomplish a particular condition. For statement consists
of tree parts i.e. initialization, condition, and iteration.
initialization : It is an expression that sets the value of the loop control variable. It executes
only once.
condition : This must be a boolean expression. It tests the loop control variable against a target
value and hence works as a loop terminator.
iteration : It is an expression that increments or decrements the loop control variable.
Here is the form of the for loop:
for(initialization; condition; iteration){
//body of the loop
}
For example, a sample for loop may appear as follows:
int i;
for (i=0; i<10; i++)
System.out.println("i = " +i);

In the above example, we have initialized the for loop by assigning the '0' value to i. The test
expression, i < 100, indicates that the loop should continue as long as i is less than 100. Finally,
the increment statement increments the value of i by one. The statement following the for loop
will be executed as long as the test expression is true as follows:
System.out.println("i = " + i);
Well, we can add more things inside a loop. To do so we can use curly braces to indicate the
scope of the for loop. Like,
int i;
for (i=0; i<10; i++) {
MyMethod(i);
System.out.println("i = " + i);
}
There is a simpler way to declare and initialize the variable used in the loop. For example, in the
following code, the variable i is declared directly within the for loop:
for (int i=0; i<100; i++)
System.out.println("i = " +i);
Lets see a simple example which will help you to understand for loop very easily. In this
example we will print 'Hello World' ten times using for loop.
class printDemo{
public static void main(String[] args){
for (int i = 0; i<10; i++){
System.out.println("Hello World!");
}
}
}

Here is the output:


C:\javac>javac
printDemo.java
C:\javac>java
printDemo
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!

Hello World!
After learning how to use a for loop, I would like to introduce another form of for loop to be
used for iteration through collection and arrays. This form has enhanced the working of for loop.
This is the more compact way to use a for loop.
Here we will take an array of 10 numbers.
int[] numbers = {1,2,3,4,5,6,7,8,9,10};
The following program, arrayDemo,displays the usage of for loop through arrays. It shows the
variable item that holds the the current value from the array.
class arrayDemo{
public static void main(String[] args){
int[] numbers = {1,2,3,4,5,6,7,8,9,10};
for (int item : numbers) {
System.out.println("Count is: " + item);
}
}
}

Here is the output of the program


C:\javac>javac
arrayDemo.java
C:\javac>java
arrayDemo
Count is: 1
Count is: 2
Count is: 3
Count is: 4
Count is: 5
Count is: 6
Count is: 7
Count is: 8
Count is: 9
Count is: 10
We would like to suggest to use this form of for loop if possible.
The while and do-while Statements
Lets try to find out what a while statement does. In a simpler language, the while statement
continually executes a block of statements while a particular condition is true. To write a while
statement use the following form:

while (expression) {
statement(s)
}
Lets see the flow of the execution of the while statement in steps:
1. Firstly, It evaluates the condition in parentheses, yielding true or false.
2. Secondly, It continues to execute the next statement if the condition is false and exit the while
statement.
3. Lastly, If the condition is true it executes each of the statements between the brackets and then
go back to step 1.
For example:
// This is the Hello program in Java
class Bonjour{
public static void main (String args[]){
System.out.print("Bonjour "); // Say Hello
int i = 0;
// Declare and initialize loop counter
while (i < args.length){ // Test and Loop
System.out.print(args[i]);
System.out.print(" ");
i = i + 1; // Increment Loop Counter
}
System.out.println(); // Finish the line
}
}

In the above example, firstly the condition will be checked in the parentheses, while
(i<args.length). If it comes out to be true then it will continue the execution till the last line and
will go back to the loop again. However, if its false it will continue the next statement and will
exit the while loop.
The output is as follows:
C:\javac>javac
Bonjour.java
C:\javac>java
Bonjour
Bonjour
The while statement works as to for loop because the third step loops back to the top. Remember,
the statement inside the loop will not execute if the condition is false. The statement inside the
loop is called the body of the loop. The value of the variable should be changed in the loop so
that the condition becomes false and the loop terminates.

Have a look at do-while statement now.


Here is the syntax:
do {
statement(s)
} while (expression);
Lets tweak an example of do-while loop.
class DoWhileDemo{
public static void main (String args[]) {
int i = 0;
do{
System.out.print("Bonjour"); // Say Bonjour
System.out.println(" ");
i = i + 1; // Increment LoopCounter
}while (i < 5);
}
}

In the above example, it will enter the loop without checking the condition first and checks the
condition after the execution of the statements. That is it will execute the statement once and then
it will evaluate the result according to the condition.
The output is as follows:
C:\javac>javac
DoWhileDemo.java
C:\javac>java
DoWhileDemo
Bonjour
Bonjour
Bonjour
Bonjour
Bonjour
You must have noticed the difference between the while and do-while loop. That is the do-while
loop evaluates its expression at the bottom of the loop. Hence, the statement in the do-while loop
will be executed once.
Jumping
Sometimes we use Jumping Statements in Java. Using for, while and do-while loops is not
always the right idea to use because they are cumbersome to read. Using jumping statements like
break and continue it is easier to jump out of loops to control other areas of program flow.

The break Statement


We use break statement to terminate the loop once the condition gets satisfied.
Lets see a simple example using break statement.
class BreakDemo{
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.println(i);
if (i==3) {
break ;
}
}
}
}

In the above example, we want to print 5 numbers from 0 to 1 at first using for loop as shown.
Then we put a condition that 'if i = = 3', the loop should be terminated. To terminate the loop
after satisfying the condition we use break.
It gives the following output:
C:\javac>javac
BreakDemo.java
C:\javac>java
BreakDemo
0
1
2
3
The break statement has two forms: labeled and unlabeled. You saw the labeled form in the
above example i.e. a labeled break terminates an outer statement. However, an unlabeled break
statement terminates the innermost loop like switch, for, while, or do-while statement.
Now observe the example of unlabeled form below. We have used two loops here two print '*'.
In this example, if we haven't use break statement thus the loop will continue and it will give the
output as shown below.
class BreaklabDemo1
{
public static void main(String[] args)
{
for (int i = 0; i < 10; i++) {
System.out.print("\n");
for (int j = 0; j<=i; j++)
{
System.out.print("*");

if (j==5)
{ // break;
}
}
}

Output:
C:\javac>javac
BreaklabDemo1.java
C:\javac>java
BreaklabDemo1
*
**
***
****
*****
******
*******
********
*********
**********
C:\javac>
However in the following example we have used break statement. In this the inner for loop i.e.
"for (int j=0; j<=i; j++)" will be executed first and gets terminated there n then. Then the outer
for loop will be executed i.e. "for (int i=0; i<10; i++)". And it will give the output as shown
below.
class BreaklabDemo{
public static void main(String[] args){
for (int i = 0; i < 10; i++) {
System.out.print("\n ");
for (int j = 0; j<=i; j++){
System.out.print("*");
if (j==5)
break;
}
}
}
}

Output:
C:\javac>javac

BreaklabDemo.java
C:\javac>java
BreaklabDemo
*
**
***
****
*****
******
******
******
******
******
C:\javac>
The continue statement
The continue statement is used in many programming languages such as C, C++, java etc.
Sometimes we do not need to execute some statements under the loop then we use the continue
statement that stops the normal flow of the control and control returns to the loop without
executing the statements written after the continue statement. There is the difference between
break and continue statement that the break statement exit control from the loop but continue
statement keeps continuity in loop without executing the statement written after the continue
statement according to the conditions.
In this program we will see that how the continue statement is used to stop the execution after
that.
Here is the code of the program :
public class Continue{
public static void main(String[] args){
Thread t = new Thread();
int a = 0;
try{
for (int i=1;i<10;i++)
{
if (i == 5)
{
continue;
//control will never reach here (after
the continue statement).
//a = i;
}
t.sleep(1000);
System.out.println("chandan");

System.out.println("Value of a : " + a);


}
}
catch(InterruptedException e){}
}
}
Output of the program :
If we write the code in the given program like this :
if (i == 5 )
{
continue;
a = i;
}
Then the program will generate an error on compile time like :
C:\chandan>javac Continue.java
Continue.java:12: unreachable statement
a = i;
^
1 error
If we write the code in the given program like this :
if (i == 5 )
{
continue;
}
Then the program prints the output like :
C:\chandan>javac
Continue.java
C:\chandan>java
Continue
chandan
Value of a : 0
chandan
Value of a : 0
chandan
Value of a : 0
chandan
Value of a : 0
chandan
Value of a : 0

chandan
Value of a : 0
chandan
Value of a : 0
chandan
Value of a : 0

Classes in Java
Exceptions
There are some kind of errors that might occur during the execution of the program. An
exception is an event that occurs and interrupts the normal flow of instructions. That is
exceptions are objects that store the information about the occurrence of errors. When any kind
of error or unusual condition occurs, these exceptions are being thrown. Any exception used to
occur earlier always resulted in a program crash. However, some programming languages like
java have mechanisms for handling exceptions. This is known as catching exception in Java.
The exceptions that occur in the program can be caught using try and catch block. Remember,
the program will crash if the exception would not be caught. There are three types of exceptions
in Java. These are -:
1. Checked Exceptions
2. The error
3. Runtime exception
Error and Runtime exceptions are known as unchecked exceptions. This chapter covers how to
throw an exception and catch it. A detailed explanation on the types of exceptions and the
advantages of the exceptions.
Basic I/O
In this section we will learn about basic input and out put operations in Java. Different kinds of
sources and destinations are represented by a Stream like disk files, devices, memory arrays etc.
A Stream is a sequence of data. An Input Stream is used by the program to read data from the
source. Similarly, a program uses an Output stream to write data to a destination. It also
supports different kinds of data including simple bytes, primitive data types, objects etc. We will
learn about I/O Steams and how to use them.
Concurrency
Concurrency is generally used to perform multiple tasks simultaneously. In this section we will
learn how to write applications to perform multitasking. There are two types of units of
execution process and threads. Thread is the most important unit in concurrent programming.
There are many processes and threads which are active in a computer system. However only one
threads executes at a time even in systems that only have a single execution core.

Regular expression
The set of strings which are based on common characteristics are shared by each string in the set.
Basically, Regular expressions are a set of strings.
This regular expression as a Java string, becomes "\\\\". That is 4 backslashes to match a single
one. As in literal Java strings the backslash is an escape character. The literal string as a single
backslash is denoted by "\\". In this chapter we will learn to create a syntax for regular
expressions and how to use them.

Inheritance
To know the concept of inheritance clearly you must have the idea of class and its features like
methods, data members, access controls, constructors, keywords this, super etc.
As the name suggests, inheritance means to take something that is already made. It is one of the
most important feature of Object Oriented Programming. It is the concept that is used for
reusability purpose. Inheritance is the mechanism through which we can derived classes from
other classes. The derived class is called as child class or the subclass or we can say the
extended class and the class from which we are deriving the subclass is called the base class or
the parent class. To derive a class in java the keyword extends is used. To clearly understand the
concept of inheritance you must go through the following example.
The concept of inheritance is used to make the things from general to more specific e.g. When
we hear the word vehicle then we got an image in our mind that it moves from one place to
another place it is used for traveling or carrying goods but the word vehicle does not specify
whether it is two or three or four wheeler because it is a general word. But the word car makes a
more specific image in mind than vehicle, that the car has four wheels . It concludes from the
example that car is a specific word and vehicle is the general word. If we think technically to
this example then vehicle is the super class (or base class or parent class) and car is the subclass
or child class because every car has the features of it's parent (in this case vehicle) class.
The following kinds of inheritance are there in java.

Simple Inheritance
Multilevel Inheritance

Pictorial Representation of Simple and Multilevel Inheritance

Simple Inheritance

Multilevel Inheritance

Simple Inheritance
When a subclass is derived simply from it's parent class then this mechanism is known as simple
inheritance. In case of simple inheritance there is only a sub class and it's parent class. It is also
called single inheritance or one level inheritance.
eg.
class A {
int x;
int y;
int get(int p, int q){
x=p; y=q; return(0);
}
void Show(){
System.out.println(x);
}
}
class B extends A{
public static void main(String args[]){
A a = new A();
a.get(5,6);
a.Show();
}
void display(){
System.out.println("B");
}
}

Multilevel Inheritance
It is the enhancement of the concept of inheritance. When a subclass is derived from a derived
class then this mechanism is known as the multilevel inheritance. The derived class is called the
subclass or child class for it's parent class and this parent class works as the child class for it's
just above ( parent ) class. Multilevel inheritance can go up to any number of level.
e.g.

class A {
int x;
int y;
int get(int p, int q){
x=p; y=q; return(0);
}
void Show(){
System.out.println(x);
}
}
class B extends A{
void Showb(){
System.out.println("B");
}
}
class C extends B{
void display(){
System.out.println("C");
}
public static void main(String args[]){
A a = new A();
a.get(5,6);
a.Show();
}
}

Java does not support multiple Inheritance


Multiple Inheritance
The mechanism of inheriting the features of more than one base class into a single class is known
as multiple inheritance. Java does not support multiple inheritance but the multiple inheritance
can be achieved by using the interface.
In Java Multiple Inheritance can be achieved through use of Interfaces by implementing more
than one interfaces in a class.
super keyword
The super is java keyword. As the name suggest super is used to access the members of the super
class.It is used for two purposes in java.
The first use of keyword super is to access the hidden data variables of the super class hidden by
the sub class.
e.g. Suppose class A is the super class that has two instance variables as int a and float b. class B
is the subclass that also contains its own data members named a and b. then we can access the
super class (class A) variables a and b inside the subclass class B just by calling the following
command.

super.member;
Here member can either be an instance variable or a method. This form of super most useful to
handle situations where the local members of a subclass hides the members of a super class
having the same name. The following example clarify all the confusions.
class A{
int a;
float b;
void Show(){
System.out.println("b in super class:
}

" + b);

}
class B extends A{
int a;
float b;
B( int p, float q){
a = p;
super.b = q;
}
void Show(){
super.Show();
System.out.println("b in super class: " + super.b);
System.out.println("a in sub class: " + a);
}

public static void main(String[] args){


B subobj = new B(1, 5);
subobj.Show();
}

Output:
C:\>java B
b in super class: 5.0
b in super class: 5.0
a in sub class: 1
Use of super to call super class constructor: The second use of the keyword super in java is to
call super class constructor in the subclass. This functionality can be achieved just by using the
following command.
super(param-list);
Here parameter list is the list of the parameter requires by the constructor in the super class.
super must be the first statement executed inside a super class constructor. If we want to call the
default constructor then we pass the empty parameter list. The following program illustrates the
use of the super keyword to call a super class constructor.

class A{
int a;
int b;
int c;
A(int p, int q, int r){
a=p;
b=q;
c=r;
}
}
class B extends A{
int d;
B(int l, int m, int n, int o){
super(l,m,n);
d=o;
}
void Show(){
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
public static void main(String args[]){
B b = new B(4,3,8,7);
b.Show();
}
}

Output:
C:\>java B
a=4
b=3
c=8
d=7

Java String Examples


1. Comparing Strings (== operator)
This section describes how two string references are compared. If two String variables
point to the same object then these two variables are called references for the same
object.

2. Creation of StringBuffer
In this section, you will learn how to create a string buffer. Here we have used the
following StringBuffer Constructors.
3. Reading File into a Byte Array
In this section, you will learn how to make a file to be read into a byte array. Here we
have used inputStream constructor to take file as a parameter.
4. Java Count Vowels
In this program you will learn how to count vowels in a String. Here you will be asked to
enter a String of your own choice and then you will get the number of vowels from that
String.
5. Java Display File-Extension
In this program you will learn how to display the file extension of the file. Here you will
be asked to enter the file name and then you will get the extension of the file.
6. Java Change File-Extension
In this program you will learn how to change the file extension of the file. Here you will
be asked to enter the file name whose extension is to be changed and then you will get the
file name with the changed extension.
7. Java String Occurrence in a String
In this program you will learn how to find the occurrence of a String in another String.
Here we have already taken a String.
8. String replaceFirst() Method
In this program you will learn how to replace words in a text. We are going to use
replaceFirst() method of String class in Java. The description of the code is given below
for the usage of the method.
9. String indexOf() Method
In this section, you will get the detailed explanation about the indexOf() method of String
class. We are going to use indexOf() method of String class in Java.
10. String sort() Method
In this program you will learn how to sort words in a String. The sorting will be done in
ascending order. We are going to use sort() method of String class in Java. The
description of the code is given below for the usage of the method.
11. String replaceAll() Method
In this program you will learn how to replace all the words in a String. We are going to
use replaceAll() method of String class in Java. The description of the code is given
below for the usage of the method.

12. String indexOf(int ch)


In this section, you will get the detailed explanation about the indexOf(int ch) method of
String class. We are going to use indexOf(int ch) method of String class in Java.
13. String indexOf(int ch, int fromIndex)
In this section, you will get the detailed explanation about the indexOf(int ch, int
fromIndex) method of String class. We are going to use indexOf(int ch, int fromIndex)
method of String class in Java.
14. String indexOf(String str)
In this section, you will get the detailed explanation about the indexOf(String str) method
of String class. We are going to use indexOf(String str) method of String class in Java.
15. String indexOf(String str, int fromIndex)
In this section, you will get the detailed explanation about the indexOf(String str, int
fromIndex) method of String class. We are going to use indexOf(String str, int
fromIndex) method of String class in Java.
16. String lastIndexOf(int ch)
In this section, you will get the detailed explanation about the lastIndexOf(int ch)
method of String class. We are going to use lastIndexOf(int ch) method of String class in
Java.
17. String lastIndexOf(String str)
In this section, you will get the detailed explanation about the lastIndexOf(String str)
method of String class. We are going to use lastIndexOf(String str) method of String
class in Java.
18. String lastIndexOf(String str, int fromIndex)
In this section, you will get the detailed explanation about the lastindexOf(String str, int
fromIndex) method of String class. We are going to use lastindexOf(String str, int
fromIndex) method of String class in Java.
19. String lastIndexOf(int ch, int fromIndex)
In this section, you will get the detailed explanation about the lastindexOf(int ch, int
fromIndex) method of String class. We are going to use lastindexOf(int ch, int
fromIndex) method of String class in Java.
20. String regionMatches()
In this section, you will get the detailed explanation about the regionMatches() method
of String class. We are going to use regionMatches() method of String class in Java.
21. String substring(int beginIndex)
In this section, you will get the detailed explanation about the substring(int beginIndex)
method of String class. We are going to use substring(int beginIndex) method of String
class in Java.
22. String substring(int beginIndex, int endIndex)
In this section, you will get the detailed explanation about the substring(int beginIndex,

int endIndex) method of String class. We are going to use substring(int beginIndex, int
endIndex) method of String class in Java.
23. String equalsIgnoreCase(String Str)
In this section, you will get the detailed explanation about the
equalsIgnoreCase(String Str) method of String class. We are going to use
equalsIgnoreCase(String Str) method of String class in Java.
24. String Concat()
In this section, you will get the detailed explanation about the Concat() method of String
class. We are going to use Concat() method of String class in Java.
25. String copyValueOf(char[] data, int offset, int count)
In this section, you will get the detailed explanation about the copyValueOf(char[] data,
int offset, int count) method of String class. We are going to use
copyValueOf(char[] data, int offset, int count) method of String class in Java.
26. String getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
In this section, you will get the detailed explanation about the getChars() method of
String class. We are going to use getChars() method of String class in Java.
27. String intern()
In this section, you will get the detailed explanation about the intern() method of String
class. We are going to use intern() method of String class in Java. The description of the
code is given below for the usage of the method.
28. String Determining a Character's Unicode Block
In this section, you will get the detailed explanation about the UnicodeBlock() method of
String class. We are going to use UnicodeBlock() method of String class in Java. The
description of the code is given below for the usage of the method.
29.

Java Compare String (== operator)


30.

31. This section describes how two string references are compared. If two String variables
point to the same object then these two variables are called references for the same
object. So to check this comparison programmatically, == operator is used. If two
variables refers the same object then this operator returns true value and if they don't then
false value is returned. The essential point to remember while comparing strings with this
operator is that it compares the references the two strings are pointing to rather than
comparing the content of the string. The following program uses this operator compare
the two strings. If both strings are equal, it will display a message "The given strings are
equal" otherwise it will show "The given string are not equal".
Description of code:
This is the method that compares an object values and returns Boolean type value either

'true' or 'false'. If it returns 'true' for the both objects, it will be equal otherwise not. Here
in this case you will see that both the strings come out to be same that is because they
have been allocated to the same memory.
public class stringmethod{
public static void main(String[] args){
String string1 = "Hi";
String string2 = new String("Hello");
if (string1 == string2) {
System.out.println("The strings are equal.");
} else {
System.out.println("The strings are unequal.");
}
}
}

32. Output pf the program:


C:\unique>javac
stringmethod.java
C:\unique>java stringmethod
The strings are unequal.
C:\unique

Creation of StringBuffer
In this section, you will learn how to create a string buffer. Here we have used the following
StringBuffer Constructors.
StringBuffer() //Default Constructor with 16 characters set
StringBuffer(String s) //String to String Buffer
StringBuffer(int initialCapacity) //StringBuffer?s with initial Capacity
Description of code:
As mentioned above we have taken three String buffer constructors here. One is the default with
16 characters and other two takes the String buffer and capacity of StringBuffer. Therefore we
get the following output.
public class StringBufferExample{
public static void main(String[] args) {
StringBuffer strBuffer1 = new StringBuffer("Bonjour");

StringBuffer strBuffer2 = new StringBuffer(60);


StringBuffer strBuffer3 = new StringBuffer();
System.out.println("strBuffer1 : " +strBuffer1);
System.out.println("strBuffer2 capacity : " +strBuffer2.capacity());
System.out.println("strBuffer3 capacity : " +strBuffer3.capacity());
}
}

Output of the program:


C:\unique>javac
StringBufferExample.java
C:\unique>java StringBufferExample
strBuffer1 : Bonjour
strBuffer2 capacity : 60
strBuffer3 capacity : 16
C:\unique>

Reading File into ByteArray


In this section, you will learn how to make a file to be read into a byte array. Here we have used
inputStream constructor to take file as a parameter.
Description of code:
In this program we have taken a file which is to be read into an array of byte. We have used
file.length(); method to take the length of the file. And if the file is very large it will give the
message that the file is too large. Then we taken two variables offset and numRead so that the
file could be read from zero. Then the file will be converted to the bytes with the help of
BytesFromFile(new File("test.txt"));.

Here is the code of program:


import
import
import
import

java.io.File;
java.io.InputStream;
java.io.FileInputStream;
java.io.IOException;

public class FileReadInByteArray {


public static byte[] BytesFromFile(File file) throws IOException {
InputStream is = new FileInputStream(file);
long length = file.length();
if (length > Integer.MAX_VALUE) {
System.out.println("Sorry! Your given file is too large.");
System.exit(0);
}
byte[] bytes = new byte[(int)length];
int offset = 0;
int numRead = 0;
while (offset < bytes.length && (numRead=is.read(bytes,
offset, bytes.length-offset)) >= 0) {
offset += numRead;
}
if (offset < bytes.length) {
throw new IOException("Could not completely read file "
+ file.getName());
}
is.close();
return bytes;
}
public static void main(String[] args) {
byte[] byteArray = null;
try {
byteArray = BytesFromFile(new File("test.txt"));
} catch (IOException e) {
e.printStackTrace();
}

if (byteArray != null) {
System.out.println("Your File Content: ");
for (int i=0; i < byteArray.length; i++) {
System.out.print((char)byteArray[i]);
}
}
}

Output of the program:


C:\chandan>javac
FileReadInByteArray.java
C:\chandan>java FileReadInByteArray
Your File Content:
Chandan Kumar Verma
C:\chandan>

Java Count Vowels


In this program you will learn how to count vowels in a String. Here you will be asked to enter a
String of your own choice and then you will get the number of vowels from that String.
Description of the code:
In the program code given below, you will be asked to enter the String first as can be observed
from the method of java.io.*; package which is BufferedReader();. The compiler will read the
String once you enter it through readLine(); method. Then we have taken a variable- count = 0.
Now, we have applied a loop here which will go up to the String's length and will find the
number of vowels one by one as shown in the output.
The code of the program is given below:
import java.lang.String;
import java.io.*;
import java.util.*;
public class CountVowels{
public static void main(String args[])throws IOException{
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the String:");
String text = bf.readLine();
int count = 0;
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (c=='a' || c=='e' || c=='i' || c=='o' || c=='u') {
count++;
}
}
System.out.println("There are" + " " + count + " " + "vowels");
}
}

Output of the program:


C:\unique>javac
CountVowels.java
C:\unique>java CountVowels
Enter the String:
This is a new world
There are 5 vowels

File-Extension
In this program you will learn how to display the file extension of the file. Here you will be
asked to enter the file name and then you will get the extension of the file.
Description of the code:
In the program code given below, you will be asked to enter the file name first as can be
observed from the method of java.io.*; package which is BufferedReader();. The compiler will
read the file name once you enter it through readLine(); method. Then we have declared the
local variables here filename and extension. Now, to find the position of the last dot we have
used a method lastIndexOf(); to get the extension. At the last we have applied show(); method
to get the extension.
The code of the program is given below:
import java.io.*;
import java.lang.String;
public class FileExtension{

public void show(String extension){


System.out.println("Extension is" + " " + extension);
}
public static void main(String args[])throws IOException{
BufferedReader bf =
new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the file name:");
String filenameExtension = bf.readLine();
File filename = new File(filenameExtension);
if(!filename.exists())
{
System.out.println("File does not exist.");
System.exit(0);
}
String extension;
int dotPos = filenameExtension.lastIndexOf(".");
extension = filenameExtension.substring(dotPos);
FileExtension abc = new FileExtension();
abc.show(extension);
}

Output of the program:


C:\unique>javac
FileExtension.java

C:\unique>java FileExtension
Enter the file name:
test.txt
Extension is .txt
C:\unique>

File-Extension
In this program you will learn how to change the file extension of the file. Here you will be
asked to enter the file name whose extension is to be changed and then you will get the file name
with the changed extension..
Description of the code:
In the program code given below, you will be asked to enter the file name with the extension as
can be observed from the method of java.io.*; package which is BufferedReader();. The
compiler will read the file name as oldfileExtension once you enter it through readLine();
method. Then it will check for that filename if it exists or not. If it will find the mentioned
filename then change it by asking you to enter a new fileextension. For this we have used a
constructor and we have passed the newfileExtension to that. Then we have applied renameTo();
to change the filename. Remember we haven't changed the filename here but file extension only.
The code of the program is given below:
import java.io.*;
public class ChangeFileExt{
public static void main(String[] args) throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Please enter the filename with extension to be changed: ")
;
String oldfileExtension = in.readLine();
File oldfile = new File(oldfileExtension);
if(!oldfile.exists())
{
System.out.println("File does not exist.");
System.exit(0);
}
int dotPos = oldfileExtension.lastIndexOf(".");
String strExtension = oldfileExtension.substring(dotPos + 1);
String strFilename = oldfileExtension.substring(0, dotPos);
String newfileExtension = in.readLine();
String strNewFileName = strFilename + "." + newfileExtension;
File newfile = new File(strNewFileName);

boolean Rename = oldfile.renameTo(newfile);


if(!Rename) {
System.out.println("FileExtension hasn't been changed successfully.");
}
else {
System.out.println("FileExtension has been changed successfully.");
}
}

Output of the program:


C:\java-examples>javac ChangeFileExt.java
C:\java-examples>java ChangeFileExt
Please enter the filename with extension to be changed: amit.txt
Enter file extension to change the file type: java
FileExtension has been changed successfully.
C:\sourcecontrol\roseindia\public_html\java\string-examples>

Java String Occurrence in a String


In this program you will learn how to find the occurrence of a String in another String. Here we
have already taken a String.
Description of the code:
In the program code given below, we will find another String from a String which already exists.
Here we have taken two variables- result and len. We have applied a condition here that if length
is greater than zero then it will start searching for the string with the help of the method
base.indexOf();. And once it will find the string at the given position then it will display the
following output.
The code of the program is given below:
import java.util.*;
import java.io.*;
import java.lang.String;
public class StringCount{
public static void main(String args[]){
String searchFor = "is";
String base = "This is the method";
int len = searchFor.length();

int result = 0;
if (len > 0) {
int start = base.indexOf(searchFor);
while (start != -1) {
result++;
start = base.indexOf(searchFor, start+len);
}
}
System.out.println(result);
}

Output of the program:


C:\unique>javac
StringCount.java
C:\unique>java StringCount
2
C:\unique>

String replaceFirst() Method


In this program you will learn how to replace words in a text. We are going to use replaceFirst()
method of String class in Java. The description of the code is given below for the usage of the
method.
Description of the code:
Here, you will get to know about the replaceFirst() method through the following java program.
In the program code given below, we have taken a String. Then we have taken another string that
contains the word to be replaced with. After that we have applied replaceFirst(); method to
replace that word. This method will only replace the word at the first position as shown in the
output.
The code of the program is given below:
public class ReplaceFirstDemo {
public static void main(String[] args) {
String str = "Her name is Tamana and Tamana is a good girl.";
String strreplace = "Sonia";
String result = str.replaceFirst("Tamana", strreplace);
System.out.println(result);
}

Output of the program:


C:\unique>javac ReplaceFirstDemo.java
C:\unique>java ReplaceFirstDemo
Her name is Sonia and Tamana is a good
girl.
C:\unique>

String indexOf() Method


In this section, you will get the detailed explanation about the indexOf() method of String class.
We are going to use indexOf() method of String class in Java. The description of the code is
given below for the usage of the method.
Description of the code:
Here, you will get to know about the indexOf() method through the following java program. In
the program code given below, we have taken a String. To find the index of any character we
have applied indexOf(); method and then we have passed the character in that to find its index as
shown in the output.
The code of the program is given below:
public class stringDemo{
public static void main(String[] args) throws Exception{
String color = "bluegrey";
int index = color.indexOf('e');
System.out.println(index);
}
}

Output of the program:


C:\unique>javac
stringDemo.java
C:\unique>java stringDemo
3

C:\unique>

String sort() Method


In this program you will learn how to sort words in a String. The sorting will be done in
ascending order. We are going to use sort() method of String class in Java. The description of the
code is given below for the usage of the method.
Description of the code:
Here, you will get to know about the sort() method through the following java program. In the
program code given below, we have taken a String. First of all we will convert that string in array
of characters. For this we have used toCharArray(); method. After that we have used sort();
method to sort that array of characters.
The code of the program is given below:
import java.util.*;
import java.io.*;
import java.lang.String;
public class SortWords{
public static void main(String args[]){
String str = "This is my new string";
char[] content = str.toCharArray();
java.util.Arrays.sort(content);
String sorted = new String(content);
System.out.println(content);
}
}

Output of the program:


C:\unique>javc SortWords
C:\unique>java SortWords
Teghiiimnnrssstwy
C:\unique>

String replaceAll() Method


In this program you will learn how to replace all the words in a String. We are going to use
replaceAll() method of String class in Java. The description of the code is given below for the
usage of the method.
Description of the code:
Here, you will get to know about the replaceAll() method through the following java program. In
the program code given below, we have taken a String. Then we have taken another string that
contains the word to be replaced with. After that we have applied replaceAll(); method to
replace that word. This method will replace all the words in a string as shown in the output.
The code of the program is given below:
public class ReplaceDemo {
public static void main(String[] args) {
String str = "Her name is Tamana and Tamana is a good girl.";
String strreplace = "Sonia";
String result = str.replaceAll("Tamana", strreplace);
System.out.println(result);
}
}

Output of the program:


C:\unique>javac ReplaceDemo.java
C:\unique>java ReplaceDemo
Her name is Sonia and Sonia is a good
girl.
C:\unique>

String indexOf(int ch)


In this section, you will get the detailed explanation about the indexOf(int ch) method of String
class. We are going to use indexOf(int ch) method of String class in Java. The description of the
code is given below for the usage of the method.

Description of the code:


Here, you will get to know about the indexOf(int ch) method through the following java
program. In the program code given below, we have taken a String. To find the index of any
character in a string we have applied indexOf() method and then we have passed a character
from the string in that to find its index as shown in the output. You must be observing in the
output that we have also taken the ASCII value of small "b" which is 98. Hence its also giving
the same result.
NOTE: This method returns the index of the first occurrence of the given character within
the string.
Here is the code of the program:
public class indexOfString {
public static void main(String args[]) {
String s = "That was the breaking News";
System.out.println(s);
System.out.println("indexOf(the) -> " + s.indexOf('b'));
System.out.println("indexOf(the) -> " + s.indexOf(98));
}
}

Output of the program:


C:\unique>javac
indexOfString.java
C:\unique>java indexOfString
That was the breaking News
indexOf(the) -> 13
indexOf(the) -> 13
C:\unique>

String indexOf(int ch, int fromIndex)


In this section, you will get the detailed explanation about the indexOf(int ch, int fromIndex)
method of String class. We are going to use indexOf(int ch, int fromIndex) method of String
class in Java. The description of the code is given below for the usage of the method.
Description of the code:

Here, you will get to know about the indexOf(int ch, int fromIndex) method through the
following java program. In the program code given below, we have taken a String. To find the
index of any character in a string we have applied indexOf(int ch, int fromIndex); method and
then we have passed the character from a string in that with the index number to find its index
starting from the specified index as shown in the output. You must be observing in the output that
we have also taken the ASCII value of small "b" which is 98 with the index number. Hence its
also giving the same result.
NOTE: This method returns the index of the first occurrence of the given character,
starting the search at the specified index within the string.
Here is the code of the program:
public class IndexOfChar{
public static void main(String args[]) {
String s = "Honesty is the best Policy";
System.out.println(s);
System.out.println("indexOf(n, 1) -> " + s.indexOf('b', 1));
System.out.println("indexOf(n, 1) -> " + s.indexOf(98, 1));
}
}

Output of the program:


C:\unique>java IndexOfChar
Honesty is the best Policy
indexOf(n, 1) -> 15
indexOf(n, 1) -> 15
C:\unique>

String indexOf(String str)


In this section, you will get the detailed explanation about the indexOf(String str) method of
String class. We are going to use indexOf(String str) method of String class in Java. The
description of the code is given below for the usage of the method.
Description of the code:
Here, you will get to know about the indexOf(String str) method through the following java
program. In the program code given below, we have taken a String. To find the index of a
Substring from a String, we have applied indexOf(String str); method and then we have passed
the Substring from the specified String in that to find its index as shown in the output.

NOTE: This method returns the index of the first occurrence of the given substring within
the string.
Here is the code of the program:
public class StringValue {
public static void main(String args[]) {
String s = "That was the breaking News";
System.out.println(s);
System.out.println("indexOf(the) -> " + s.indexOf("break"));
}
}

Output of the program:


C:\unique>javac
StringValue.java
C:\unique>java StringValue
That was the breaking News
indexOf(the) -> 13
C:\unique>

String indexOf(String str, int fromIndex)


In this section, you will get the detailed explanation about the indexOf(String str, int
fromIndex) method of String class. We are going to use indexOf(String str, int fromIndex)
method of String class in Java. The description of the code is given below for the usage of the
method.
Description of the code:
Here, you will get to know about the indexOf(String str, int fromIndex) method through the
following java program. In the program code given below, we have taken a String. To find the
index of any string we have applied indexOf(String str, int fromIndex); method and then we
have passed the Substring from the specified string with the index number in that to find its
index starting from the specified index number as shown in the output. And if we take index
number to be 23 then we get -1 as a result that shows the given index number doesn't exist in a
string.
NOTE: This method returns the index of the first occurrence of the given substring,
starting at the specified index within the string.

Here is the code of the program:


public class IndexOfStr {
public static void main(String args[]) {
String s = "That was the breaking News";
System.out.println(s);
System.out.println("indexOf(News, 5) -> " + s.indexOf("News", 5));
}
}

Output of the program:


C:\unique>javac IndexOfStr.java
C:\unique>java IndexOfStr
That was the breaking News
indexOf(News, 5) -> 22
C:\unique>javac IndexOfStr.java
C:\unique>java IndexOfStr
That was the breaking News
indexOf(News, 23) -> -1
C:\unique>

String lastIndexOf(int ch)


In this section, you will get the detailed explanation about the lastIndexOf(int ch) method of
String class. We are going to use lastIndexOf(int ch) method of String class in Java. The
description of the code is given below for the usage of the method.
Description of the code:
Here, you will get to know about the lastIndexOf(int ch) method through the following java
program. In the program code given below, we have taken a String. To find the last index of any
character in a string we have applied lastIndexOf(int ch); method and then we have passed a
character from the string in that to find its last index as shown in the output. You must be
observing in the output that we have also taken the ASCII value of small "b" which is 98. Hence
its also giving the same result.
NOTE: This method returns the index of the last occurrence of the given character within
the string.

Here is the code of the program:


public class LastIndexOfCh {
public static void main(String args[]) {
String s = "Honesty is the best Policy";
System.out.println(s);
System.out.println("lastIndexOf(b) -> " + s.lastIndexOf(98));
System.out.println("lastIndexOf(b) -> " + s.lastIndexOf('b'));
}
}

Output of the program:


C:\unique>javac LastIndexOfCh.java
C:\unique>java LastIndexOfCh
Honesty is the best Policy
lastIndexOf(b) -> 15
lastIndexOf(b) -> 15
C:\unique>

String lastIndexOf(String str)


In this section, you will get the detailed explanation about the lastIndexOf(String str) method of
String class. We are going to use lastIndexOf(String str) method of String class in Java. The
description of the code is given below for the usage of the method.
Description of the code:
Here, you will get to know about the lastIndexOf(String str) method through the following java
program. In the program code given below, we have taken a String. To find the last index of a
Substring from the String, we have applied lastIndexOf(String str); method and then we have
passed the Substring in that to find its last index as shown in the output.
NOTE: This method returns the index of the rightmost occurrence of the given substring
within the string.
Here is the code of program:
public class LastIndxOfStr {
public static void main(String args[]) {
String s = "Honesty is the best Policy";

System.out.println(s);
System.out.println("lastIndexOf(the) -> " + s.lastIndexOf("nest"));
}
}

Output of the program:


C:\unique>javac LastIndxOfStr.java
C:\unique>java LastIndxOfStr
Honesty is the best Policy
lastIndexOf(the) -> 2
C:\unique>

String lastIndexOf(String str, int fromIndex)


In this section, you will get the detailed explanation about the lastindexOf(String str, int
fromIndex) method of String class. We are going to use lastindexOf(String str, int fromIndex)
method of String class in Java. The description of the code is given below for the usage of the
method.
Description of the code:
Here, you will get to know about the lastindexOf(String str, int fromIndex) method through the
following java program. In the program code given below, we have taken a String. To find the
last index of a substring from the specified string, we have applied lastindexOf(String str, int
fromIndex) method and then we have passed the substring with the index number to that to find
its index as shown in the output.
NOTE: This method returns the index of the last occurrence of the given substring,
searching backward starting at the specified index within the string .
Here is the code of the program:
public class lastindexofStrInd {
public static void main(String args[]) {
String s = "Java is a wonderful language";
System.out.println(s);
System.out.println("lastIndexOf(ful, 18) = "
+ s.lastIndexOf("ful", 18));
}
}

Output of the program:


C:\unique>javac
lastindexofStrInd.java
C:\unique>java lastindexofStrInd
Java is a wonderful language
lastIndexOf(ful, 18) = 16
C:\unique>

String lastIndexOf(int ch, int fromIndex)


In this section, you will get the detailed explanation about the lastindexOf(int ch, int
fromIndex) method of String class. We are going to use lastindexOf(int ch, int fromIndex)
method of String class in Java. The description of the code is given below for the usage of the
method.
Description of the code:
Here, you will get to know about the lastindexOf(int ch, int fromIndex) method through the
following java program. In the program code given below, we have taken a String. To find the
last index of a character from the specified string, we have applied lastindexOf(int ch, int
fromIndex) method and then we have passed the character with the index number to that to find
its index as shown in the output. We have also taken the ASCII value of the character in the
example below which also gives the same output.
NOTE: This method returns the index of the last occurrence of the given character,
searching backward starting at the specified index within the string .
Here is the code of the program:
public class lastIndexofChar{
public static void main(String args[]){
String s = "Java is a wonderful language";
System.out.println(s);
System.out.println("lastIndexOf(a, 19) = " + s.lastIndexOf('a', 19));
System.out.println("lastIndexOf(a, 19) = " + s.lastIndexOf(97, 19));
}
}

Output of the program:

C:\unique>javac
lastIndexofChar.java
C:\unique>java lastIndexofChar
Java is a wonderful language
lastIndexOf(a, 19) = 8
lastIndexOf(a, 19) = 8
C:\unique>

String regionMatches()
In this section, you will get the detailed explanation about the regionMatches() method of String
class. We are going to use regionMatches() method of String class in Java. The description of the
code is given below for the usage of the method.
Description of the code:
As shown in the example a substring of the specified string object is compared to a substring of
the other. If these substrings contain same characters sequence then we get true as output i.e. if
the specified subregion of the string matches the subregion of the string argument; otherwise we
get false. The substring to be compared begins at index toffset and has length len and that of
other substring to be compared begins at index ooffset and has length len.
Therefore, in the program code given below the characters from 20 through 28 in str1 match
characters 25 through 33 in str2 and give true as output.
However if one of the following is true then only we get false as an output:

if toffset is negative.
If ooffset is negative.

If toffset + len is greater than the length of the String object.

If ooffset + len is greater than the length of the other argument.


Parameters:
toffset - the starting offset of the subregion in this string.
ooffset - the starting offset of the subregion in the string argument.
len - the number of characters to compare.
NOTE: This method tests if two string regions are equal or not.

Here is the code of the program:


public class matchstr{
public static void main(String args[]){
String str1 = new String("Java is a wonderful language");
String str2 = new String("It is an object-oriented language");
boolean result = str1.regionMatches(20, str2, 25, 6);
System.out.println(result);
}
}

Output of the program:


C:\unique>javac matchstr.java
C:\unique>java matchstr
true
C:\unique>

String substring(int beginIndex)


In this section, you will get the detailed explanation about the substring(int beginIndex) method
of String class. We are going to use substring(int beginIndex) method of String class in Java.
The description of the code is given below for the usage of the method.
Description of the code:
Here, you will get to know about the substring(int beginIndex) method through the following
java program. In the program code given below, we have taken a String. To find a substring from
the specified string, we have applied substring(int beginIndex) method and then we have
passed the index number to that to find the specified substring from the beginning of that index
number as shown in the output.
NOTE: This method returns a new string from the specified string that is a substring of it.
Here is the code of the program:
public class StrSearch{
public static void main(String args[]){
String s = "Bonjour";
//String begin = 1;
String t = s.substring(1);
System.out.println(t);

}
}

Output of the program:


C:\unique>javac
StrSearch.java
C:\unique>java StrSearch
onjour
C:\unique>

String substring(int beginIndex, int


endIndex)
In this section, you will get the detailed explanation about the substring(int beginIndex, int
endIndex) method of String class. We are going to use substring(int beginIndex, int endIndex)
method of String class in Java. The description of the code is given below for the usage of the
method.
Description of the code:
Here, you will get to know about the substring(int beginIndex, int endIndex) method through
the following java program. In the program code given below, we have taken a String. To find a
substring from the specified string, we have applied substring(int beginIndex, int endIndex)
method and then we have passed the index numbers to that to find the specified substring from
the beginning and the end of the index numbers as shown in the output.
NOTE: This method returns a new string from the specified string that is a substring of it.
Here is the code of the program:
public class StringSearch{
public static void main(String args[]){
String s = "Bonjour";
//String begin = 3;
//String end = 7;
String t = s.substring(3, 7);
System.out.println(t);
}
}

Output of the program:


C:\unique>javac
StringSearch.java
C:\unique>java StringSearch
jour
C:\unique>

String equalsIgnoreCase(String Str)


In this section, you will get the detailed explanation about the equalsIgnoreCase(String Str)
method of String class. We are going to use equalsIgnoreCase(String Str) method of String
class in Java. The description of the code is given below for the usage of the method.
Description of the code:
As shown in the example below we have taken three strings i.e. str1, str2 and str3. Then we
have applied the equalsIgnoreCase(String Str) method to compare these three strings. This
method shows whether two String objects contain the same data, ignoring the case of the letters
in the String. Hence we get the following output.
If atleast one of the following is true then only two characters c1 and c2 are considered the
same, ignoring case.

Applying the method Character.toUpperCase(char) to each character produces the


same result.
Applying the method Character.toLowerCase(char) to each character produces the
same result.
The two characters are the same (as compared by the == operator).
Parameters:
anotherString - the String to compare other String.
Returns true if the argument is not null and the Strings are equal, ignoring case.
Otherwise returns true.

Here is the code of the program:


public class equalsIgnore{
public static void main(String[] args){
String str1 = "bon voyage";

String str2 = "Bon Appetit";


String str3 = "Bon Voyage";
boolean equals1 = str1.equalsIgnoreCase(str2);
boolean equals2 = str1.equalsIgnoreCase(str3);
System.out.println("\"" + str1 + "\" equals \"" + str2
+ "\"? " + equals1);
System.out.println("\"" + str1 + "\" equals \"" + str3
+ "\"? " + equals2);
}
}

Here is the code of the program:


C:\unique>javac equalsIgnore.java
C:\unique>java equalsIgnore
"bon voyage" equals "Bon Appetit"? false
"bon voyage" equals "Bon Voyage"? true
C:\unique>

String Concat()
In this section, you will get the detailed explanation about the Concat() method of String class.
We are going to use Concat() method of String class in Java. The description of the code is given
below for the usage of the method.
Description of the code:
As shown in the example we have taken two strings i.e. str1 and str2. Then we have
concatenated both the strings with the help of "+" operator. Concatenation means to add the two
or more strings. After concatenating strings we got the following output.
There is another way to concat the strings as well. That is:
"helples".concat("s") returns "helpless"
"con".concat("caten").concat("ation") returns "concatenation"
Parameters:
str - the String that is concatenated to the end of the String.
Returns a string that represents the concatenation of the object's characters followed by
the string argument's characters.

Here is the code of the program:


class concat{
public static void main(String[] args){
String str1 = "Table";
String str2 = "Tennis";
String Game = str1 + " " + str2;
System.out.println(Game);
}
}

Here is the code of the program:


C:\unique>javac concat.java
C:\unique>java concat
Table Tennis
C:\unique>

String copyValueOf(char[] data, int offset,


int count)
In this section, you will get the detailed explanation about the copyValueOf(char[] data,
int offset, int count) method of String class. We are going to use copyValueOf(char[] data,
int offset, int count) method of String class in Java. The description of the code is given below
for the usage of the method.
Description of the code:
As shown in the example we have taken a byte array to copy the contents to the other string. That
is this method creates a new String object with the contents of a character array. Thus in the
following program code we have passed the initial offset of the array and length of the array to
the copyValueOf() method. Hence we get the following output.
This method returns a String that represents the character sequence in the array specified.
Parameters:
data - the character array.
offset - initial offset of the subarray.
count - length of the subarray.

Here is the code of the program:


public class StrCopyValueOf{
public static void main(String[] args){
char[] arr = new char[] { '6', '8', '5', '3' };
String str = String.copyValueOf(arr, 0, 1);
System.out.println("The new String contains \"" + str + "\"");
}
}

Here is the code of the program:


C:\unique>javac StrCopyValueOf.java
C:\unique>java StrCopyValueOf
The new String contains "6"
C:\unique>

String getChars(int srcBegin, int srcEnd,


char[] dst, int dstBegin)
In this section, you will get the detailed explanation about the getChars() method of String class.
We are going to use getChars() method of String class in Java. The description of the code is
given below for the usage of the method.
Description of the code:
As shown in the example we have taken a String. Then we have taken a byte array to copy the
contents of the String. The contents will be copied from 2 through 9 from the string and the
source array will be filled from the starting position 0. That is copies characters from the string
into the destination character array.
The first character to be copied is at index srcBegin; the last character to be copied is at index
srcEnd-1. The characters are copied into the subarray of dst starting at index dstBegin and
ending at index:
Parameters:
srcBegin - index of the first character in the string to copy.
srcEnd - index after the last character in the string to copy.

dst - the destination array.


dstBegin - the start offset in the destination array.
Here is the code of the program:
public class getChar{
public static void main(String[] args){
String str = "How are you.";
char[] arr = new char[7];
str.getChars(2, 9, arr, 0);
System.out.print("The Character array equals: ");
System.out.println(arr);
}
}

Here is the code of the program:


C:\unique>javac getChar.java
C:\unique>java getChar
The Character array equals: w are y
C:\unique>

String intern()
In this section, you will get the detailed explanation about the intern() method of String class.
We are going to use intern() method of String class in Java. The description of the code is given
below for the usage of the method.
Description of the code:
As shown in the example we have created three Strings in three different ways. Then we have
used the "==" operator to determine which Strings are equal. Basically an intern string is the
one that has an entry in the global string pool. And if the string is not in global string pool then it
will be added. If the pool already contains a string equal to this String object as determined by
the equals(Object) method then on invoking the intern method the string from the pool is
returned. Otherwise, this String object is added to the pool and a reference to this String object
is returned.
It returns a canonical representation for the string object.
The String class maintains a pool of strings privately, which is empty initially.

For any two strings s1 and s2, s1.intern() == s2.intern() is true if and only if s1.equals(s2) is
true.
Returns a string that has the same contents as this string, but is definetly to be from a pool
of unique strings.
Here is the code of the program:
public class internExample{
public static void main(String[] args){
String str1 = "Hello Java";
String str2 = new StringBuffer("Hello").append(" Java").toString();
String str3 = str2.intern();
System.out.println("str1 == str2 " + (str1 == str2));
System.out.println("str1 == str3 " + (str1 == str3));
}
}
Output of the program:
C:\unique>javac internExample.java
C:\unique>java internExample
str1 == str2 false
str1 == str3 true
C:\unique>

String Determining a Character's Unicode


Block
In this section, you will get the detailed explanation about the UnicodeBlock() method of String
class. We are going to use UnicodeBlock() method of String class in Java. The description of the
code is given below for the usage of the method.
Description of the code:
As shown in the example we have taken a Unicode of a character. Then we have applied a
method UnicodeBlock() to get the character out of the code. Therefore, we get the following
output. Similarly, we can take other Unicode as well for different characters and on applying this
method we can get that particular character as shown below.

Here is the code of the program:


public class charUni{
public static void main(String args[]){
char ch = '\u1234';
Character.UnicodeBlock block = Character.UnicodeBlock.of(ch);
System.out.println(ch);
}
}

Output of the program:


C:\unique>javac charUni.java
C:\unique>java charUni
?
C:\unique>

You might also like