This document provides an overview of Java programming concepts including:
- Java is an object-oriented programming language that allows writing programs as console applications or applets.
- It discusses Java features like being simple, object-oriented, robust, secure, portable, and supports multithreading.
- Key Java concepts covered are data types, keywords, classes, objects, inheritance, polymorphism and exceptions.
- It also discusses the Java virtual machine architecture, class files, and the basic structure of a Java program.
2. Software
Software is a collection of programs as a solution to
the real time problems.
A Program is a set of instructions with syntax and
semantics.
We write programs by using a programming
language.
3. Programming Languages
Machine Language
It contains 0’s and 1’s.
Machine understandable form
Difficult to write programs for human
Assembly Language
Microprocessor Language
Contains pneumonics
High Level Language
Procedures and functions
Object oriented programs are also high level.
Ex: PASCAL, COBOL,FORTRAN, C, C++, JAVA
4. Programming Styles
Three different programming styles.
Top-down
Bottom – Up
Modules
Top-down
The main method appears at top of the program. The
compilation begins from top.
Bottom-up
The functions or classes will be defined first, followed by main
method.
The compilation starts from the main, that is available at
bottom and goes to top.
6. what is Java?
Java is an Object Oriented Programming Language.
In Java, we can write two types of programs.
Console Applications
These programs result will displays at command prompt.
Applets / Web Programs
The program result will displays in the web browser.
8. History of Java
Java started out as a research project to manipulate consumer
electronic devices.
Research began in 1991 as the Green Project at Sun
Microsystems, under the lead of James Gosling.
Research efforts birthed a new language, OAK. ( A tree outside
the window of James Gosling’s office at Sun)
It was developed as an embedded programming language,
which would enable embedded system application.
9. History of Java
With the invention of www in 1993, The team developed
web applets to run on network of computers.
The team developed a web browser called HotJava in
1994.
Java is available as jdk from 1995 and it is an open source
s/w.
10. From the History of Java
Language was created with 5 main goals:
It should be object oriented.
A single representation of a program could be executed on
multiple operating systems. (i.e. write once, run anywhere)
It should fully support network programming.
It should execute code from remote sources securely.
It should be easy to use.
14. Versions of Java
Version Year Features Added
JDK 1.1 Feb19,1997
Inner classes JavaBeans, JDBC, RMI, Reflection,
AWT.
J2SE 1.2 Dec8, 1998
JIT compiler, Collections, IDL & CORBA, strictfp,
Java Plug-in.
J2SE 1.3
May8,
2000
HotSpot JVM, JavaSound, Java Naming and
Directory Interface, Java Platform Debugger
Architecture.
J2SE 1.4 Feb6, 2002
Preferences API, Logging API, assert, image I/O
API, security and cryptography extensions.
J2SE 5.0
Sep30,
2004
Generics, annotations, Autoboxing, Enumerations,
Varargs, Enhanced for each.
JAVA SE 6
Dec11,
2006
JDBC 4.0, JVM improvements, Improved web
services, Support for older Win9x versions dropped.
15. Java Platforms
There are three main platforms for Java:
Java SE (Java Platform, Standard Edition) – runs on
desktops and laptops.
Java ME (Java Platform, Micro Edition) – runs on
mobile devices such as cell phones.
Java EE (Java Platform, Enterprise Edition) – runs on
servers.
16. Java Development Kit: (Jdk)
It contains JRE's along with the various development tools like
the Java source compilers, bundling and deployment tools,
debuggers, development libraries, etc.
Tools of jdk
• javac ( java compiler)
• java (java interpreter)
• appletviewer
• jdb (java debugger)
Java Terminology
17. javadoc creates html format documentation
for java source code.
javap java disassembler, that converts
bytecode into program description
Java Virtual Machine: (JVM)
It interprets the byte code into the machine code
depending upon the underlying OS and hardware
combination. It uses the class libraries, and other
supporting files provided in JRE
Java Terminology
18. Java Runtime Environment:
A runtime environment which implements Java Virtual
Machine, and provides all class libraries and other facilities
necessary to execute Java programs. This is the software on
your computer that actually runs Java programs.
JRE = JVM + Java Packages Classes (like util, math,
lang, awt, swing etc) +runtime libraries.
Java Terminology
20. A class is collection of objects of similar type or it is a template.
Ex: fruit mango;
Objects are instances of the type class.
The wrapping up of data and functions into a single unit ( called
class) is known as encapsulation. Data encapsulation is the
most striking features of a class.
Abstraction refers to the act of representing essential features without
including
the background details or explanations
Inheritance is the process by which objects of one class acquire the properties
of another class. The concept of inheritance provides the reusability.
class object
21. Polymorphism:
It allows the single method to perform different actions based on
the parameters.
Dynamic Binding: When a method is called within a program, it
associated with the program at run time rather than at compile
time is called dynamic binding.
22. Object-Oriented Languages Types
1.Object-based programming language: It supports
Data encapsulation
Data hiding and access mechanisms
Automatic initialization and clear-up of objects
Operator overloading
Disadvantage : They do not support inheritance and dynamic binding
Ex: Ada
2.Object-oriented programming languages:
OOP = Object-based + inheritance + dynamic binding
Ex: C++, Java, Smalltalk, Object Pascal
23. Benefits of OOP
Through inheritance, we can eliminate redundant code and
extend the use of existing classes.
The principle of data hiding helps the programmer to build
secure programs.
It is easy to partition the work in a project based on objects.
Object oriented system easily upgraded from small to large
systems.
Software complexity can be easily managed.
24. Applications of oop
Real-time systems
Object-oriented databases
Neural networks and parallel programming
Decision support and office automation systems
CAD/CAM systems
25. C++ Vs. Java
C++ Java
Supports operator
overloading
Doesn’t support operator
overloading
Template classes are available. No templates
27. Features of Java (Java Buzz Words)
Simple
Object Oriented
Distributed
Robust
Secure
System independence & Portable
Compile, Interpreted and High Performance
Multithreaded
Dynamic
Architecture-Neutral
28. Java Features
Simple
The design goal of java is simple.
Pointers are eliminated in java.
Improper handling of pointers leads to memory leaks and reliability
issues.
Pointers may crash a program easily. For ex: when we add two
pointers the program crashes immediately.
Pointers break security over internet.
Rich pre-defined class libraries through packages
Object Oriented
Every thing (primitive types, arrays, void including static variable
and static methods ) will be represented as objects of class.
Java follows all features of OOP language.
All methods are associated with objects
29. Distributed
Java is designed for the distributed environment of the
Internet, because it handles TCP/IP protocols.
Allows objects on two different computers to execute
procedures remotely by using package called Remote Method
Invocation (RMI)
Robust
Robust means strong.
Inbuilt exception handling features.
Memory management feature.
Automatic garbage collection tracks objects usage over time
and deletes if the variable or an object is not used.
Java Features
30. Java Features
Secure
Security problems and virus threats can be eliminated or
minimized with java programs (firewalls) over internet.
Access restrictions are forced (private, public)
System independence
Byte code is not machine dependent. It can run on any processor
and any operating system.
Portability
Same application runs on all platforms
The sizes of the primitive data types are always the same
31. Java Features
Compile, Interpreted and High Performance
Java compiler generate byte-code, not native machine code
The byte-codes are platform-independent
Java byte code is translated to machine readable
instructions in runtime (Java Virtual Machine)
Easy to translate directly into native machine code by using a
just-in-time compiler, which enhances the speed of execution.
Multithreaded
A thread is an individual process.
JVM supports multithreaded programming.
Need not wait for the application to finish one task before
beginning another one.
32. Java Features
Dynamic
Libraries can freely add new methods and instance
variables without any effect on their clients
Interfaces promote flexibility and reusability in code by
specifying a set of methods an object can perform, but
leaves open how these methods should be implemented .
Architecture-Neutral
Goal of java designers is “write once; run anywhere, any
time, forever.”
33. Java Program Structure
Documentation Section
Package Statement
Import Statement
Interface Statements
Class Definition
Main method class
{
main method definition
}
Suggested
Optional
Essential
Optional
compulsory
Optional
34. Starting a Java Program (Sample)
import java.lang.System;
import java.lang.String; or use import java. lang.*;
class First
{
public static void main (String args [])
{
System.out.println (“Welcome to Java”);
}
}
35. Starting a Java Program (Sample) Explanation
First , decide and import the classes, which are required for the
program. Group of classes and interfaces with its methods are
contained in a package.
Java has several such packages in its library.
java library
Packages
Classes and interfaces
Methods
In java.lang.* , * means all the classes and interfaces of that
package are make available into our program.
37.
System is a class which is present in java.lang package.
out is a static field present in system class which returns a
PrintStream object. As out is a static field it can call directly
with classname.
println() is a method which present in PrintStream class
which can call through the PrintStream object return by
static field out present in System class to print a line to
console.
38. Single Line comments: Starts with // double slash symbol.
Multi Line comments: Stars with /* and ends with */
Java documentation comments: Starts with /** and end with
*/. These comments are used to provide description for
every feature in a java program.
Comments
39. Formatting the Output
n Next line
t Horizontal tab space
r Enter key
b Back space
f Form feed
Displays
” Displays”
’ Displays’
40. The Architecture of the Java Virtual Machine
Operating System
Interpreter
& JIT
42. Binary form of a class file
public class Hello
{
public static
{
System.out.println("Hello,
World!");
}
}
43. Keywords
abstract continue goto package synchronized
assert default if private this
boolean do implements protected throw
break double import public throws
byte else instanceOf return transient
case extends int short try
catch final interface static void
char finally long strictfp volatile
class float native super while
const for new switch
44. Data Types
Simple Type Derived Type User Defined
Type
Numeric Type Non-Numeric class Interface
Integer Float Char Boolean
float double
byte short int long
E.g: Array, String…
Single precision
Double precision
45. Data Types
Java Is a Strongly Typed Language
Every variable has a type, every expression has a type,
and every type is strictly defined.
All assignments, whether explicit or via parameter
passing in method calls, are checked for type
compatibility.
There are no automatic conversions of conflicting types
as in some languages.
For example, in C/C++ you can assign a floating-point
value to an integer. In Java, you cannot.
46. Integer Data Types
Java does not support unsigned, positive-only integers.
All are signed, positive and negative values.
Byte Data Type
The smallest integer type is byte.
Variables of type byte are especially useful while working with a
stream of data from a network or file.
Byte variables are declared by use of the byte keyword.
Ex: byte b, c;
Floating Point Types
There are two kinds of floating-point types.
All math functions, such as sin( ), cos( ), and sqrt( ), return
double values.
Boolean Data Type
It can have only one of two possible values, true or false.
This is the type, returned by all relational operators, such as a <
b.
47. Character Data Type
char in Java is not the same as char in C or C++.
Java uses Unicode to represent characters.
Unicode defines a fully international character set that can represent
all of the characters found in all human languages.
It is a unification of dozens of character sets, such as Latin, Greek,
Arabic, Cyrillic, Hebrew, Katakana, Hangul, and many more.
Hence it requires 16 bits.
The range of a char in java is 0 to 65,536.
There are no negative chars.
48. Data Types
Name Width in bits Range
long 64 –9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
int 32 –2,147,483,648 to 2,147,483,647
short 16 –32,768 to 32,767
byte 8 –128 to 127
double 64 4.9e–324 to 1.8e+308
float 32 1.4e−045 to 3.4e+038
char 16 0 to 65,536.
49. public class IntDemo{
public static void main(String args[]){
System.out.println(" For an Integer ");
System.out.println("Size is : "+Integer.SIZE);
int i1 = Integer.MAX_VALUE;
int i2 = Integer.MIN_VALUE ;
System.out.println("Max value is : "+i1);
System.out.println("Min Value is : "+i2);
System.out.println(" For an Byte");
System.out.println("Size is : "+Byte.SIZE);
byte b1 = Byte.MAX_VALUE;
byte b2 = Byte.MIN_VALUE ;
System.out.println("Max value is : "+b1);
System.out.println("Min Value is : "+b2);
System.out.println(" For an Short");
System.out.println("Size is : "+Short.SIZE);
short s1 = Short.MAX_VALUE;
short s2 = Short.MIN_VALUE ;
System.out.println("Max value is : "+s1);
System.out.println("Min Value is : "+s2);
System.out.println(" For a Long");
System.out.println("Size is : "+Long.SIZE);
long l1 = Long.MAX_VALUE;
long l2 = Long.MIN_VALUE ;
System.out.println("Max value is : "+l1);
System.out.println("Min Value is : "+l2);
}
}
50. public class FloatDemo{
public static void main(String args[]){
System.out.println(" For an Float");
System.out.println("Size is : "+Float.SIZE);
float f1 = Float.MAX_VALUE;
float f2 = Float.MIN_VALUE ;
System.out.println("Max value is : "+f1);
System.out.println("Min Value is : "+f2);
System.out.println(" For an Double");
System.out.println("Size is : "+Double.SIZE);
double d1 = Double.MAX_VALUE;
double d2 = Double.MIN_VALUE ;
System.out.println("Max value is : "+d1);
System.out.println("Min Value is : "+d2);
}
}
51. public class CharDemo{
public static void main(String args[]){
System.out.println(" For a Char");
System.out.println("Size is : "+Character.SIZE);
int f1 = Character.MAX_VALUE;
long f2 = Character.MIN_VALUE ;
System.out.println("Max value is : "+f1);
System.out.println("Min Value is : "+f2);
}
}
52. Variables
The variable is the basic unit of storage in a Java program.
A variable is defined by the combination of an identifier, a type, and an
optional initializer.
Declaring a Variable
In Java, all variables must be declared before they can be used.
type identifier [ = value][, identifier [= value] ...] ;
Types
Instance Variable
Class Variable
Local Variable
Parameters
53. Local variables :
• Local variables are declared in methods, constructors, or blocks.
54. Instance variables :
• Instance variables are declared in a class, but outside a method,
constructor or any block.
• Instance variables are created when an object is created with the use of
the key word 'new' and destroyed when the object is destroyed.
• Access modifiers can be given for instance variables.
• The instance variables are visible for all methods, constructors and block
in the class.
• Instance variables have default values.
• Instance variables can be accessed directly by calling the variable name
inside the class.
• However within static methods and different class ( when instance
variables are given accessibility) that should be called using the fully
qualified name ObjectReference.VariableName
55. Class/Static variables :
• Class variables also known as static variables are declared with the static
keyword in a class, but outside a method, constructor or a block.
• There would only be one copy of each class variable per class,
regardless of how many objects are created from it.
• Static variables are stored in static memory.
• Static variables are created when the program starts and destroyed when
the program stops.
• Visibility is similar to instance variables.
• Default values are same as instance variables.
• Static variables can be accessed by calling with the class name
ClassName.VariableName
56. class Variables{
int i;
public int j
static long l=10;
public static float f;
char c;
boolean b;
void display(int a){
i=a;
System.out.println("i value in display: "+i);
}
public static void main(String args[]){
double d=0.0;
//public double d=0.0; invalid
Variables v1=new Variables();
Variables v2=new Variables();
Variables v3=new Variables();
v1.display(100);
v1.i=2;
v2.i=3;
v3.i=4;
System.out.println("i value is: "+v1.i);
System.out.println("i value is: "+v2.i);
System.out.println("i value is: "+v3.i);
System.out.println("i value is: "+v1.j);
v1.l=20;
v2.l=30;
v3.l=40;
System.out.println("l value is: "+v1.l);
System.out.println("l value is: "+v2.l);
System.out.println("l value is: "+v3.l);
System.out.println("f value is: "+f);
System.out.println("c value is: "+v1.c);
System.out.println("b value is: "+v1.b);
System.out.println("d value is: "+d);
}
}
57. class Variables{
int i;//instance variable
public int j ;//instance variable
static long l=10;//class variable
public static float f;//class variable
char c;//instance variable
boolean b;//instance variable
void display(int a){
i=a;
System.out.println("i value in display: "+i);
}
public static void main(String args[]){
double d=0.0;//local varible
//public double d=0.0; invalid
Variables v1=new Variables();
Variables v2=new Variables();
Variables v3=new Variables();
v1.display(100);
v1.i=2;
v2.i=3;
v3.i=4;
System.out.println("i value is: "+v1.i);
System.out.println("i value is: "+v2.i);
System.out.println("i value is: "+v3.i);
System.out.println("i value is: "+v1.j);
v1.l=20;
v2.l=30;
v3.l=40;
System.out.println("l value is: "+v1.l);
System.out.println("l value is: "+v2.l);
System.out.println("l value is: "+v3.l);
System.out.println("f value is: "+f);
System.out.println("c value is: "+v1.c);
System.out.println("b value is: "+v1.b);
System.out.println("d value is: "+d);
}
}
58. Variables declared inside a scope are not accessible to code
outside.
Scopes can be nested. The outer scope encloses the inner
scope.
Variables declared in the outer scope are visible to the inner
scope.
Variables declared in the inner scope are not visible to the
outside scope.
61. Relational Operators
The relational operators determine the relationship that
one operand has to the other.
They determine equality and ordering.
Operator Result
== Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
62. Logical Operators
Operator Result
&& Logical AND
| | Logical OR
^ Logical XOR (exclusive OR)
|| Short-circuit OR
&& Short-circuit AND
! Logical unary NOT
63. & //executes both left and right side operands
&& // Java will not bother to evaluate the right-hand
operand when the outcome of the expression can be
determined by the left operand alone.
class Test{
public static void main(String args[]){
int denom=0,num=20;
if (denom != 0 && num / denom > 10)
System.out.println("Hi");
}
}
64. Boolean Logical Operators(2)
Operator Result
&= AND assignment
|= OR assignment
^= XOR assignment
== Equal to
!= Not equal to
?: Ternary if-then-else
66. Increment / Decrement Operator
Operator Result
++ Pre / Post increment
-- Pre / Post Decrement
67. Example:
class IncDec{
public static void main(String args[]){
int a = 1;
int b = 2;
int c,d;
c = ++b;
d = a++;
c++;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
}
68. class OpEquals{
public static void main(String args[]){
int a = 1;
int b = 2;
int c = 3;
a += 5;
b *= 4;
c += a * b;
c %= 6;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
}
}
69. Bitwise Operators(1)
bitwise operators can be applied to the integer types,
long, int, short, byte and char.
These operators act upon the individual bits of their
operands.
Operator Result
~ Bitwise unary NOT
& Bitwise AND
| Bitwise OR
^ Bitwise exclusive OR
>> Shift right
>>> Shift right zero fill
<< Shift left
70. Bitwise Operators(2)
Operator Result
&= Bitwise AND assignment
|= Bitwise OR assignment
^= Bitwise exclusive OR assignment
>>= Shift right assignment
>>>= Shift right zero fill assignment
<<= Shift left assignment
71. 00101010 42
&00001111 15
--------------
00001010 10
00101010 42
^00001111 15
-------------
00100101 37
int a = 32;
a = a >> 2; 8
int a = 64;
a = a << 2; 256
11111000 –8
>>1
11111100 –4
11111111 11111111 11111111 11111111 –1
>>>24
00000000 00000000 00000000 11111111 255
72. Example:
public class RelationalOperatorsDemo
{
public static void main(String args[])
{
int x=10,y=5;
System.out.println(“x>y:”+(x>y));
System.out.println(“x<y:”+(x<y));
System.out.println(“x>=y:”+(x>=y));
System.out.println(“x<=y:”+(x<=y));
System.out.println(“x==y:”+(x==y));
System.out.println(“x!=y:”+(x!=y));
}
}
76. Expressions
An expression is a combination of constants (like 10),
operators ( like +), variables(section of memory) and
parentheses ( like “(” and “)” ) used to calculate a
value.
Ex1: x = 1;
Ex2: y = 100 + x;
Ex3: x = (32 - y) / (x + 5)
79. Expressions
An expression is a combination of constants (like 10),
operators ( like +), variables(section of memory) and
parentheses ( like “(” and “)” ) used to calculate a
value.
Ex1: x = 1;
Ex2: y = 100 + x;
Ex3: x = (32 - y) / (x + 5)
80. Control Statements
Selection Statements: if & switch
Iteration Statements: for, while and do-while
Jump Statements: break, continue and return
82. The condition is any expression that returns a boolean value.
The expression must be of type byte, short, int, or char;
Each of the values specified in the case statements must be of a type
compatible with the expression.
84. for – each loop
This loop is specifically designed to handle the elements
of a collection. Collection represents a group of elements.
85. Example for for-each
class demo
{
public static void main(String args[])
{
}
}
}
86. Jump Statements
break; //exit from the loop
continue; //bypass the followed instructions
return; //control returns to the caller
label:
- - - -
- - - -
break label; //it’s like goto
statement
87. break, continue and return statements
break:
Used inside of a loop to come out of it.
Used inside switch block to come out of it.
Used in nested blocks to go to the end of the block.
Continue:
Used inside the loop to repeat the next iteration of loop.
When continue is executed, subsequent statements in the
loop are not executed and control goes back to the next
repetition of the loop.
Return statement is used in a method to come out of it
to the calling method.
89. Type Conversion and Casting
Type conversion, typecasting, refers to different
ways of, implicitly or explicitly, changing an entity of one
data type into another.
Types of Conversions:
1.Widening conversion
2.Narrowing conversion
90. Widening Conversion
The widening conversion is permitted in the following
cases:
byte to short, int, long, float, or double
short to int, long, float, or double
char to int, long, float, or double
int to long, float, or double
long to float or double
float to double
91. When one type of data is assigned to another type of variable, an
automatic type conversion will take place if the following two
conditions are met:
The two types are compatible.
The destination type is larger than the source type.
When these two conditions are met, a widening conversion takes
place.
Ex: char and boolean are not compatible with each other.
93. In general, the narrowing primitive conversion can occur in
these cases:
short to byte or char
char to byte or short
int to byte, short, or char
long to byte, short, or char
float to byte, short, char, int, or long
double to byte, short, char, int, long, or float
Narrowing conversion is used to cast the above incompatible types.
(target-type) value
Narrowing Conversion
95. Arrays
An array is a group of homogeneous (same type of) elements
that are referred by a common name.
In java, Arrays are created on dynamic memory by JVM.
The operator new is used for dynamic memory allocation.
One-Dimensional Arrays:
Syntax: type variablename[] = {elements list};
ex: int marks[] = {60,70,80,50};
Syntax : type varname[]=new type[size];
int month[] = new int[12];
97. If month is a reference to an array, month.length will gives
the length of the array.
Initialization:
char []c = {‘a’, ‘b’, ‘c’};
double d[][]= {
{1.0,2.0,3.0},
{4.0,5.0,6.0},
{7.0,8.0,9.0}
};
102. Command Line Arguments
Values passed by the user at runtime from command
prompt are command line arguments.
Represent values passed to main method.
To store these values main has a parameter, String args[ ]
For ex: c:java prog 22 33 anil
These three values automatically stored in main() method’s
args[ ] in the form of strings.
105. Class
Group of similar objects.
It is a model to create objects.
The properties and actions of the objects are written in the class.
Properties are represented by variable and actions are
represented by methods.
The variables defined inside a class are called as instance
variables because each object of the class contains its own copy
of these variables.
An object is an instance of a class.
106. General form of a class
class classname
{
type instance –variable 1;
type instance- variable 2;
…
type instance –variable N;
type methodname1(parameter-list)
{
statements of method
}
type methodname1(parameter-list)
{
statements of method
}
….
type methodname n (parameter-list)
{
statements of method
}
110. package packagename;
import statement;
class classname{
//instance variables;
//class or static variables;
/*methods(parameters){
//local variables;
//object creation
//statements;
}*/
}
import java.util.Scanner;
class Demon{
int i;
static double d;
public static void main(String args[]){
char c=‘a’;
Demon obj=new Demon();
Scanner s=new Scanner(System.in);
d=s.nextDouble();
System.out.println(obj.i);
System.out.println(d);
System.out.println(c);
}
}
111. class classname{
//instance variables;
//class or static variables;
/*methods(parameters){
//local variables;
//statements;
}*/
}
class MainCLass{
public static void main(String args[])
{
//object creation
//invoking methods
//statements
}
}
class Test{
char c='a';
static float f;
void display(){
int i=10;
System.out.println("Test:display()");
System.out.println(“c value: “+c);
System.out.println(“i value: “+i);
System.out.println(“f value: “+f);
}
}
class Demo{
public static void main(String args[]){
Test t=new Test();
t.display();
System.out.println("Demo:main()");
}
}
112. default :
private:
A private member is accessible only to the class in which it is
defined.
Use private keyword to create private members.
Access Control
113. public:
Any class, in any package has access to a class's public
members.
To declare a public member, use the keyword public.
protected:
Allows the class itself, subclasses, and all classes in the same
package to access the members.
To declare a protected member, use the keyword protected.
114. class AccessTest {
public static void main(String args[]) {
Test ob = new Test();
// These are OK, a and b may be accessed directly
ob.a = 10;
ob.b = 20;
// This is not OK and will cause an error
//ob.c = 100; // Error!
// You must access c through its methods
ob.setc(100); // OK
System.out.println(ob.a + " " +ob.b + " " + ob.getc());
}
}
//Example for access control
116. A constructor is a special method that initialize the instance variables.
The constructor is automatically called immediately after the object is
created.
A constructor has the same name as the class name in which it resides and
is syntactically similar to a method.
If no constructor in program .System provides its own constructor called as
default constructor.
Constructors doesn’t have any return type.
A constructor which accepts parameters is called as parameterized
constructor.
Constructors can be overloaded.
117. Default Constructor:
A constructor that accepts no parameters is called Default constructor.
If not defined, provided by the compiler.
The default constructor is called whenever an object is created without
specifying initial values.
Ex: class Box {
double width;
double height;
double depth;
Box() {
width = 10;
height = 10;
depth = 10;
}
}
// declare, allocate, and initialize Box objects
Box mybox1 = new Box();
118. class Test{
char c='a';
static float f;
Test(){
int i=10;
System.out.println("Test:Test()");
System.out.println(“c value: “+c);
System.out.println(“i value: “+i);
System.out.println(“f value: “+f);
}
}
class ConDemo{
public static void main(String args[]){
Test t=new Test();
//t.Test();
System.out.println(“ConDemo:main()");
}
}
class Test{
int x,y;
Test(int a, int b){
x=a;
y=b;
System.out.println(“x value: “+x);
System.out.println(“y value: “+y);
}
}
class PConDemo{
public static void main(String args[]){
Test t=new Test(10,20);
System.out.println(“PConDemo:main()");
}
}
//Parameterized Constructor// Default Constructor
119. Methods
General Form:
type name(parameter-list) {
// body of method
}
The type of data returned by a method must be
compatible with the return type specified by the method.
The variable receiving the value returned by a method
must also be compatible with the return type specified
for the method.
return value; //Here, value is the value returned.
Ex:
double volume(double w, double h, double d) {
return w*h*d;
120. Constructors Vs. Methods
Constructors Methods
Used to initialize the instance
variables of a class
Used for general processing
purpose or calculations
121. Types of Methods
Instance Method
Static Method
Instance Method: that act on the instance variables of the class.
Use with object form : objectname.methodname( );
Static methods don’t act upon the instance variables of a class.
because the JVM first executes static methods and then only it
creates objects.
Declared with static.
Static methods are called using classname.methodname().
123. Static variables & Static block
Static variable is a variable whose single copy in memory
is sharable by all objects
These variables are stored in method area of JVM.
A static block is a block of statements declared as static.
static {
statements;
}
125. Program to test which block executes first
class test
{
static {
System.out.println(“From static block”);
}
public static void main(String args[ ])
{
System.out.println(“From static method”);
}
}
126. class Box{
double width;
double height;
double depth;
Box(){
width=10;
height=10;
depth=10;
}
double volume(){
return width*height*depth;
}
}
class BoxDemo6{
public static void main(String args[]){
Box mybox1=new Box();
Box mybox2=new Box();
double vol;
vol=mybox1.volume();
System.out.println("Volume is: "+vol);
vol=mybox2.volume();
System.out.println("Volume is: "+vol);
}
}
Non parameterized or default Constructor
127. class Box{
double width;
double height;
double depth;
Box(double w,double h,double d){
width=w;
height=h;
depth=d;
}
double volume(){
return width*height*depth;
}
}
class BoxDemo7{
public static void main(String args[]){
Box mybox1=new Box(10,20,15);
Box mybox2=new Box(3,6,9);
double vol;
vol=mybox1.volume();
System.out.println("Volume is: "+vol);
vol=mybox2.volume();
System.out.println("Volume is:
"+vol);
}
}
Parameterized Constructor
128. Method & Constructor Overloading
Defining two or more methods with the same name and within the
same class is called method overloading.
Java uses the type and/or number of arguments to determine
which version of the overloaded method to call.
Constructors can also be overloaded in the same way as method
overloading.
129. class OverloadDemo {
void test() {
System.out.println("No parameters");
}
void test(int a) {
System.out.println("a: " + a);
}
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
double test(double a) {
System.out.println("double a: " + a);
return a*a;
}
}
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
double result;
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): " + result);
} }
//method overloading
130. //Constructor Overloading
class CDemo{
int value1;
int value2;
CDemo(){
value1 = 10;
value2 = 20;
System.out.println("Inside 1st
Constructor");
}
CDemo(int a){
value1 = a;
System.out.println("Inside 2nd Constructor");
}
CDemo(int a,int b){
value1 = a;
value2 = b;
System.out.println("Inside 3rd Constructor");
}
public void display(){
System.out.println("Value1 === "+value1);
System.out.println("Value2 === "+value2);
}
public static void main(String args[]){
CDemo d1 = new CDemo();
CDemo d2 = new CDemo(30);
CDemo d3 = new CDemo(30,40);
d1.display();
d2.display();
d3.display();
}
}
131. this
In java, it is illegal to declare two local variables with the same name inside
the same or enclosing scopes.
But you can have formal parameters to methods, which overlap with the
names of the class’ instance variables.
this keyword is used to refer to the current object.
this can be used to resolve any name collisions that might occur between
instance variables and formal variables.
When a formal variable has the same name as an instance variable, the formal
variable hides the instance variable.
Also used in method chaining and constructor chaining.
132. // instance and formal variables are different
class Box{
double w=5,h=5,d=5;
Box(double w1,double h1,double d1){
w=w1;
h=h1;
d=d1;
}
double volume(){
return w*h*d;
}
}
class BoxTest1{
public static void main(String args[]){
Box b=new Box(1,2,3);
System.out.println("Volume is: "+b.volume());
}
}
Output:
Volume is:6.0
133. // instance and formal variables are same
class Box{
double w=5,h=5,d=5;
Box(double w,double h,double d){
w=w;
h=h;
d=d;
}
double volume(){
return w*h*d;
}
}
class BoxTest2{
public static void main(String args[]){
Box b=new Box(1,2,3);
System.out.println("Volume is: "+b.volume());
}
}
Output:
Volume is:125.0
134. //’this’ hides the instance variables
class Box{
double w=5,h=5,d=5;
Box(double w,double h,double d){
}
double volume(){
return w*h*d;
}
}
class BoxTest2{
public static void main(String args[]){
Box b=new Box(1,2,3);
System.out.println("Volume is:
"+b.volume());
}
}
135. Parameter Passing
The call-by-value copies the value of a actual parameter into the
formal parameter of the method.
In this method, changes made to the formal parameter of the
method have no effect on the actual parameter.
In call-by-reference, a reference to an actual parameter (not the
value of the argument) is passed to the formal parameter.
In this method, changes made to the actual parameter will affect
the actual parameter used to call the method.
136. // Simple types are passed by value.
class Test {
void meth(int i, int j) {
i *= 2;
j /= 2;
}
}
class CallByValue {
public static void main(String args[]) {
Test ob = new Test();
int a = 15, b = 20;
System.out.println("a and b before call: " +a + " " + b);
ob.meth(a, b);
System.out.println("a and b after call: " +a + " " + b);
}
}
138. Recursion
Recursion is the process of defining something in terms
of itself.
A method that calls itself is said to be recursive.
140. Garbage Collection
Garbage collection done automatically in java.
When an object doesn’t have reference, that object is assumed to
be not required, and the memory occupied by the object can be
reclaimed.
Garbage collection only occurs at regular intervals during the
execution of your program.
We can run garbage collection on demand by calling the gc()
method.
public static void gc(): Initiates the garbage collection.
System.gc();
142. finalize( ) method
Sometimes an object will need to perform some action when it is
destroyed.
Ex:
If an object is holding some non-java resource such as a file, then you
might want to make sure these resources are freed before an object is
destroyed.
To handle such situations, Java provides a mechanism called
finalization.
The finalize( ) method has this general form:
protected void finalize( ){
// finalization code here
}
143. String
In java a string is a sequence of characters. They are objects of type String.
Once a String object has been created, we can not change the characters that
comprise in the string.
Strings are unchangeable once they are created so they are called as
immutable.
You can still perform all types of string operations. But, a new String object
is created that contains the modifications. The original string is left
unchanged.
To get changeable strings use the class called StringBuffer.
String and StringBuffer classes are declared final, so there cannot be
subclasses of these classes.
String class is defined in java.lang package, so these are available to all
programmers automatically.
144. Creating Strings
3 ways to create strings:
String s;
s = “Hello”;
String s = “Hello”;
We can create an object to String class by allocating memory
using new operator.
String s = new String(“Hello”);
Creating string by converting character arrays into strings.
char arr[ ] = { ‘h’, ‘e’, ‘l’, ‘l’ , ‘o’};
Now create string object by passing the array name to it as,
String s = new String (arr);
145. Types of string handling classes:
String
Once an object is created, no modifications can be done on that.
StringBuffer
Modifications can be allowed on created object.
StringTokenizer
Used to divide the string into substrings based on tokens.
String and SringBuffer classes are available in java.lang package where as
StringTokenizer class is available in java.util package.
String Handling
146. String s= new String();
String(char chars[])
String(char chars[], int startIndex, int numChars)
String(String strobj)
String str=new String(“SNIST”);
String str[]=new String[size];
String Constructors
147. String Constructors
String s= new String(); //To create an empty String call the default constructor.
String(char chars[]) //To create a string initialized by an array of characters.
String str = "abcd"; is equivalent to
char chars[]={‘a’,’b’,’c’,’d’};
String s=new String(chars);
String( char chars[], int startIndex, int numChars) //To create a string by specifying
positions from an array of characters
char chars[]={‘a’,’b’,’c’,’d’,’e’,’f’};
String s=new String(chars,2,3); //This initializes s with characters “cde”.
String(String str); //Construct a string object by passing another string object.
String str = "abcd";
String str2 = new String(str);
String(byte asciiChars[ ]) // Construct a string from subset of byte array.
String(byte asciiChars[ ], int startIndex, int numChars)
148. // Construct one String from another.
class MakeString {
public static void main(String args[])
{
char c[] = {'J', 'a', 'v', 'a'};
String s1 = new String(c);
String s2 = new String(s1);
System.out.println(s1);
System.out.println(s2);
}
}
Output:
Java
Java
// Construct string from subset of char array.
class SubStringCons {
public static void main(String args[])
{
byte ascii[] = {65, 66, 67, 68, 69, 70 };
String s1 = new String(ascii);
System.out.println(s1);
String s2 = new String(ascii, 2, 3);
System.out.println(s2);
}
}
Output:
ABCDEF
CDE
149. String Length
char chars[] = { 'a', 'b', 'c' };
String s = new String(chars);
System.out.println(s.length()); //it returns 3.
150. Special String Operations
String Concatenation
String Concatenation with Other Data Types
String Conversion and toString( )
Character Extraction
charAt( )
getChars( )
getBytes( )
toCharArray( )
String Comparison
equals( ) and equalsIgnoreCase( )
regionMatches( ), startsWith( ) and endsWith( )
equals( ) Versus ==
compareTo( )
Searching Strings
Modifying a String
substring( )
concat( )
replace( )
trim( )
Changing the Case of Characters Within a String
151. Special String Operations
String Concatenation
String age = "9";
String s = "He is " + age + " years old.";
System.out.println(s); // He is 9 years old.
String Concatenation with Other Data Types
int age = 9;
String s = "He is " + age + " years old.";
System.out.println(s); // He is 9 years old.
String s = "four: " + 2 + 2;
System.out.println(s);
//This fragment displays four: 22 rather than the four: 4
String s = "four: " + (2 + 2);
//Now s contains the string “four: 4”.
152. Special String Operations
String Conversion using toString( )
// Override toString() for Box class.
class Box {
double width;
double height;
double depth;
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
public String toString() {
return "Dimensions are " + width + " by "
+depth + " by " + height + ".";
}
}
class toStringDemo {
public static void main(String args[]) {
Box b = new Box(10, 12, 14);
String s = "Box b: " + b;
// concatenate Box object
System.out.println(b);
// convert Box to string
System.out.println(s);
}
}
The output of this program is shown here:
Dimensions are 10.0 by 14.0 by 12.0
Box b: Dimensions are 10.0 by 14.0 by 12.0
Box’s toString() method is automatically invoked when a Box object is used in a
concatenation expression or in a call to println( ).
153. Character Extraction
char charAt(int where)
//To extract a single character from a String
char ch;
ch = "abc".charAt(1);
//assigns the value “b” to ch.
void getChars(int sourceStart, int sourceEnd, char
target[ ], int targetStart)
//to extract more than one character at a time.
byte[ ] getBytes( )
//to store the characters in an array of bytes and it
uses the default character-to-byte conversions
provided by the platform.
//String source=“hi”+”how”+”are”+”you.”
//byte buf[] = source.getBytes();
char[ ] toCharArray( )
//to convert all the characters in a String object into a
character array. It returns an array of characters for
the entire string.
class getCharsDemo {
public static void main(String args[]) {
String s = "This is a demo of the
getChars method.";
int start = 10;
int end = 14;
char buf[] = new char[end - start];
s.getChars(start, end, buf, 0);
System.out.println (buf);
}
}
Here is the output of this program: demo
154. class GetBytesDemo{
public static void main(String[] args){
String str = "abc” + “ABC”;
byte[] b = str.getBytes();
//char[] c=str.toCharArray();
System.out.println(str);
for(int i=0;i<b.length;i++){
System.out.print(b[i]+" ");
//System.out.print(c[i]+" ");
}
}
}
Output:
97 98 99 65 66 67
//a b c A B C
155. String Comparison
boolean equals(Object str)
//To compare two strings for equality. It returns true if the strings contain the same
characters in the same order, and false otherwise.
boolean equalsIgnoreCase(String str)
//To perform a comparison that ignores case differences.
// Demonstrate equals() and
equalsIgnoreCase().
class equalsDemo {
public static void main(String args[])
{
String s1 = "Hello";
String s2 = "Hello";
String s3 = "Good-bye";
String s4 = "HELLO";
System.out.println(s1.equals(s2));
System.out.println(s1.equals(s3));
System.out.println(s1.equals(s4));
System.out.println(s1.equalsIgnoreCase(s4));
}
}
The output from the program is shown here:
true
false
false
true
156. String Comparison
boolean regionMatches(int startIndex, String str2, int str2StartIndex, int
numChars)
boolean regionMatches(boolean ignoreCase, int startIndex, String str2, int
str2StartIndex, int numChars)
//The regionMatches( ) method compares a specific region inside a string
with another specific region in another string.
//startIndex specifies the index at which the region begins within the
invoking String object.
//The String being compared is specified by str2. The index at which the
comparison will start within str2 is specified by str2StartIndex.
//The length of the substring being compared is passed in numChars.
157. class RegionTest{
public static void main(String args[]){
String str1 = "This is Test";
String str2 = “THIS IS TEST";
if(str1.regionMatches(5,str2,5,3)) {
// Case, pos1,secdString,pos1,len
System.out.println("Strings are Equal");
}
else{
System.out.println("Strings are NOT Equal");
}
}
}
Output:
Strings are NOT Equal
String Comparison
158. boolean startsWith(String str) //to determine whether a given String
begins with a specified string.
boolean endsWith(String str) // to determine whether the String in
question ends with a specified string.
Ex: "Football".endsWith("ball") and "Football".startsWith("Foot") are both true.
boolean startsWith(String str, int startIndex) //to specifies the index into
the invoking string at which point the search will begin.
Ex: "Football".startsWith("ball", 4) returns true.
equals( ) Versus ==
// It compares the characters inside a String object
//To compare two object references to see whether they refer to the same
instance.
String Comparison
159. // equals() vs ==
class EqualsNotEqualTo {
public static void main(String args[]) {
String s1 = "Hello";
String s2 = new String(s1);
//String s2 = s1;
System.out.println(s1.equals(s2));
System.out.println( s1 == s2);
}
}
Output:
true
false
String Comparison
160. int compareTo(String str)
Value Meaning
Less than zero The invoking string is less than str.
Greater than zero The invoking string is greater than str.
Zero The two strings are equal.
int compareToIgnoreCase(String str)
String Comparison
161. class SortString {
static String arr[] = {
"Now", "is", "the", "time", "for", "all", "good", "men",
"to", "come", "to", "the", "aid", "of", "their", "country“};
public static void main(String args[]) {
for(int j = 0; j < arr.length; j++) {
for(int i = j + 1; i < arr.length; i++) {
if(arr[i].compareTo(arr[j]) < 0) {
String t = arr[j];
arr[j] = arr[i];
arr[i] = t;
}
}
System.out.println(arr[j]);
}
}
}
The output of this program is the list of words:
Now aid all come country for good is men of
the the their time to to
String Comparison
162. indexOf( ) //Searches for the first occurrence of a character or substring.
lastIndexOf( ) //Searches for the last occurrence of a character or substring.
int indexOf(int ch) //To search for the first occurrence of a character.
int lastIndexOf(int ch) //To search for the last occurrence of a character.
int indexOf(String str) //To search for the first or last occurrence of a substring.
int lastIndexOf(String str)
int indexOf(int ch, int startIndex)
int lastIndexOf(int ch, int startIndex)
int indexOf(String str, int startIndex)
int lastIndexOf(String str, int startIndex)
In all cases, the methods return the index at which the character or substring
was found, or –1 on failure.
Searching Strings
163. // Demonstrate indexOf() and lastIndexOf().
class indexOfDemo {
public static void main(String args[]) {
String s = "Now is the time for all good men " +"to
come to the aid of their country.";
System.out.println(s);
System.out.println("indexOf(t) = " +s.indexOf('t'));
System.out.println("lastIndexOf(t) = " +s.lastIndexOf('t'));
System.out.println("indexOf(the) = " +s.indexOf("the"));
System.out.println("lastIndexOf(the) = " +s.lastIndexOf("the"));
System.out.println("indexOf(t, 10) = " +s.indexOf('t', 10));
System.out.println("lastIndexOf(t, 60) = " +s.lastIndexOf('t', 60));
System.out.println("indexOf(the, 10) = " +s.indexOf("the", 10));
System.out.println("lastIndexOf(the, 60) = " +s.lastIndexOf("the", 60));
}
}
Here is the output of this program:
Now is the time for all good men
to come to the aid of their country.
indexOf(t) = 7
lastIndexOf(t) = 65
indexOf(the) = 7
lastIndexOf(the) = 55
indexOf(t, 10) = 11
lastIndexOf(t, 60) = 55
indexOf(the, 10) = 44
lastIndexOf(the, 60) = 55
164. // Substring replacement.
class StringReplace {
public static void main(String args[]) {
String org = "This is a test. This is, too.";
String result = org.substring(0, 2);
System.out.println(result);
}
}
Output:
Th
Modifying a String
String substring(int startIndex)
//To extract a substring, startIndex specifies the beginning index
String substring(int startIndex, int endIndex)
// Here endIndex specifies the stopping point.
//endIndex-1
165. String concat(String str)
//To concatenate two strings, concat( ) performs the same function as +.
String s1 = "one";
String s2 = s1.concat("two");
String s1 = "one";
String s2 = s1 + "two";
String replace(char original, char replacement) //To replace all
occurrences of one character in the invoking string with another character
String s = "Hello".replace('l', 'w');
puts the string “Hewwo” into s.
String trim( ) //Removes leading and trailing whitespaces.
Here is an example:
String s = " Hello World ".trim();
//This puts the string “Hello World” into s.
166. Data Conversion Using valueOf( )
static String valueOf(double num)
// converts data from its internal format into a human-readable form.
static String valueOf(long num)
//each type can be converted properly into a string
static String valueOf(Object ob)
static String valueOf(char chars[ ])
167. Changing the Case of Characters Within a String
String toLowerCase( )
//converts all the characters in a string from uppercase to lowercase.
String toUpperCase( )
//converts all the characters in a string from lowercase to uppercase
// Demonstrate toUpperCase() and toLowerCase().
class ChangeCase {
public static void main(String args[]){
String s = "This is a test.";
System.out.println("Original: " + s);
String upper = s.toUpperCase();
String lower = s.toLowerCase();
System.out.println("Uppercase: " + upper);
System.out.println("Lowercase: " + lower);
}
}
Output:
Original: This is a test.
Uppercase: THIS IS A TEST.
Lowercase: this is a test.
169. StringBuffer( )
// The default constructor (the one with no parameters)
reserves room for 16 characters without reallocation.
StringBuffer(int size)
// accepts an integer argument that explicitly sets the size
of the buffer.
StringBuffer(String str)
// str + reserves room for 16 more characters without
reallocation.
StringBuffer Constructors
171. // StringBuffer length vs. capacity.
class StringBufferDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("Hello");
System.out.println("buffer = " + sb);
System.out.println("length = " + sb.length());
System.out.println("capacity = " + sb.capacity());
}
}
Output:
buffer = Hello
length = 5
capacity = 21
int length( ) //The current length of a StringBuffer can be found via the length( ) method
int capacity( ) //The total allocated capacity can be found through the capacity( ) method.
172. // Demonstrate charAt() and setCharAt().
class setCharAtDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("Hello");
System.out.println("buffer before = " + sb);
System.out.println("charAt(1) before = " + sb.charAt(1));
sb.setCharAt(1, 'i');
sb.setLength(2);
System.out.println("buffer after = " + sb);
System.out.println("charAt(1) after = " + sb.charAt(1));
}
}
void setLength(int len) //To set the length of the buffer within a StringBuffer object.
char charAt(int where)
//The value of a single character can be obtained from a StringBuffer via
the charAt( ) method.
void setCharAt(int where, char ch)
//To set the value of a character, ch specifies the new value of that character.
Output:
buffer before = Hello
charAt(1) before = e
buffer after = Hi
charAt(1) after = i
173. void getChars(int sourceStart, int sourceEnd, char target[ ], int
targetStart)
// To copy a substring of a StringBuffer into an array
StringBuffer append(String str)
// concatenates the string representation of any other type of data to the
end of the invoking StringBuffer object.
StringBuffer append(int num)
StringBuffer append(Object obj)
String.valueOf( ) is called for each parameter to obtain its string
representation. The result is appended to the current StringBuffer
object.
174. // Demonstrate append().
class appendDemo {
public static void main(String args[]) {
String s;
int a = 42;
StringBuffer sb = new StringBuffer(40);
s = sb.append("a = ").append(a).append("!").toString();
System.out.println(s);
}
}
Output:
a = 42!
175. //The insert( ) method inserts one string into another.
StringBuffer insert(int index, String str)
StringBuffer insert(int index, char ch)
StringBuffer insert(int index, Object obj)
// Demonstrate insert().
class insertDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("I Java!");
sb.insert(2, "like ");
System.out.println(sb);
}
}
Output:
I like Java!
176. StringBuffer reverse( )
// reverse the characters within a StringBuffer object using reverse( )
// Using reverse() to reverse a StringBuffer.
class ReverseDemo {
public static void main(String args[]) {
StringBuffer s = new StringBuffer("abcdef");
System.out.println(s);
s.reverse();
System.out.println(s);
}
}
Output:
abcdef
fedcba
177. StringBuffer delete(int startIndex, int endIndex) // to delete characters.
StringBuffer deleteCharAt(int loc)
// Demonstrate delete() and deleteCharAt()
class deleteDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("This is a test.");
sb.delete(4, 7);
System.out.println("After delete: " + sb);
sb.deleteCharAt(0);
System.out.println("After deleteCharAt: " + sb);
}
}
Output:
After delete: This a test.
After deleteCharAt: his a test.
178. StringBuffer replace(int startIndex, int endIndex, String str);
//It replaces one set of characters with another set inside a StringBuffer object.
// The replacement string is passed in str.
// Demonstrate replace()
class replaceDemo {
public static void main(String args[]) {
StringBuffer sb = new StringBuffer("This is a test.");
sb.replace(5, 7, "was");
System.out.println("After replace: " + sb);
}
}
Output: After replace: This was a test.
String substring(int startIndex) //to return sub strings.
String substring(int startIndex, int endIndex)
179. The StringTokenizer class provides the first step in parsing process,
often called the lexer (lexical analyzer) or scanner.
Parsing is the division of text into a set of discrete parts, or tokens.
To use StringTokenizer
Specify an input string and a delimiter string.
Delimiters are characters that separate tokens.
Each character in the delimiters string is considered a valid delimiter.
Ex: “ , ; : a”
The default set of delimiters consists of the whitespace characters:
Ex: space, tab, newline.
StringTokenizer
180. StringTokenizer Constructors
StringTokenizer(String str)
StringTokenizer(String str, String delimiters)
StringTokenizer(String str, String delimiters, boolean delimAsToken)
Methods
int countTokens( ) //returns number of tokens in the string.
boolean hasMoreTokens( ) //checks whether tokens are there or not
String nextToken( )//returns the token in the string
181. // Demonstrate StringTokenizer.
import java.util.StringTokenizer;
class STDemo{
//static String str = "Hello Welcome to Java Programming";
static String str = "Hello,Welcome,to,Java,Programming";
public static void main(String args[]) {
//StringTokenizer st = new StringTokenizer(str);
//StringTokenizer st = new StringTokenizer(str,",");
StringTokenizer st = new StringTokenizer(str,",",true);
while(st.hasMoreTokens()) {
String tokens = st.nextToken();
System.out.println(tokens + "n");
}
}
}
Output:
Hello
,
Welcome
,
to
,
Java
,
Programming
182. Exercise1:
Write a java program that reads a line of integers and
then displays each integer and find the sum of the
integers (using StringTokenizer)
183. import java.util.Scanner;
import java.util.*;
class Token{
static int sum=0;
public static void main(String sree[]){
Scanner s=new Scanner(System.in);
System.out.print("Enter sum of integers: ");
String str=s.next();
StringTokenizer st=new StringTokenizer(str,"+");
while(st.hasMoreTokens()){
sum=sum+Integer.parseInt(st.nextToken());
}
System.out.println("Sum of "+str+“is: "+sum);
}
}
Output:
Enter sum of integers: 10+20+30+40
Sum of 10+20+30+40 is: 100