Introduction To Java Arrays
Introduction To Java Arrays
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
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
-g:{lines,vars,source}
-nowarn
Generate no warnings
-verbose
-deprecation
are
-classpath <path>
-cp <path>
-sourcepath <path>
-bootclasspath <path>
-extdirs <dirs>
-endorseddirs <dirs>
-proc:{none,only}
-processor <class1>[,<class2>,<class3>...]
Names of the annotation processors to run;
bypasses default discovery process
-processorpath <path>
-d <directory>
-s <directory>
-implicit:{none,class}
-encoding <encoding>
-source <release>
-target <release>
-version
Version information
-help
-Akey[=value]
-X
-J<flag>
C:\>
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,"
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>()
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>
*/
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.
*/
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.
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
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
4
8
32
6-7
308
15
64 +/- 1.8 * 10
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.
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];
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]);
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("");
}
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.
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
=
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
Precedence
expr++,, expr-++expr, --expr, +expr,
-expr ~ !
*/%
+<< >> >>>
< > , <= , >= instanceof
== , !=
&
^
|
&&
||
?:
= , +=, -=, *=, /=, %=,
&=, ^=, |=, <<=, >>=,
>>, >=
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;
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!");
}
}
}
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);
}
}
}
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.
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.
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");
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
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();
}
}
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);
}
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
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.
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.
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.");
}
}
}
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");
java.io.File;
java.io.InputStream;
java.io.FileInputStream;
java.io.IOException;
if (byteArray != null) {
System.out.println("Your File Content: ");
for (int i=0; i < byteArray.length; i++) {
System.out.print((char)byteArray[i]);
}
}
}
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{
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);
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);
}
C:\unique>
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));
}
}
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"));
}
}
System.out.println(s);
System.out.println("lastIndexOf(the) -> " + s.lastIndexOf("nest"));
}
}
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.
}
}
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.
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>