What is Java?
Java is a programming language and a platform.
Java is a high level, robust, secured and object-oriented
programming language.
Platform: Any hardware or software environment in which a
program runs, is known as a platform. Since Java has its own
runtime environment (JRE) and API, it is called platform.
6.
Where it isused?
According to Sun, 3 billion devices run java. There are many devices where java is
currently used. Some of them are as follows:
Desktop Applications such as acrobat reader, media player, antivirus etc.
Web Applications such as irctc.co.in, javatpoint.com etc.
Enterprise Applications such as banking applications.
Mobile
Embedded System
Smart Card
Robotics
Games etc
7.
Types of Javaapplication
There are mainly 4 type of applications that can be created using java:
1) Standalone Application
It is also known as desktop application or window-based application. An application that
we need to install on every machine such as media player, antivirus etc. AWT and Swing
are used in java for creating standalone applications.
2) Web Application
An application that runs on the server side and creates dynamic page, is called web
application. Currently, servlet, jsp, struts, jsf etc. technologies are used for creating web
applications in java.
3) Enterprise Application
An application that is distributed in nature, such as banking applications etc. It has the
advantage of high level security, load balancing and clustering. In java, EJB is used for
creating enterprise applications.
4) Mobile Application
An application that is created for mobile devices. Currently Android and Java ME are
used for creating mobile applications.
8.
Java Basics:-
History ofjava:-
Java was developed by
James Gosling,
Patrik Naughton,
Chris Warth,
Ed Frank, and
Mike Sheridan
at Sun Microsystems, Inc in 1991.
9.
History of Java
Java started out as a research project.
Research began in 1991 as the Green Project at Sun
Microsystems, Inc.
Research efforts birthed a new language, OAK. ( A tree outside
of the window of James Gosling’s office at Sun).
Java is available as jdk and it is an open source s/w.
10.
Contd..
.
It wasstarted in 1991 as a project named “Green”, to
develop a platform-independent language that can be
used to create software to be embedded in various
consumer electronic devices, such as microwave ovens
and remote controls etc.
• Many different types of CPU’s are used as controllers.
• C & C++ ( and most other languages ) are designed to be
compiled for a specific target.
• It is possible to compile a C++ program for any type of CPU, but
requires a full C++ compiler for that CPU.
• Compilers are expensive and time-consuming to create.
11.
History of Java(contd…)
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.
Oak was renamed Java in 1995.
Now Sun Microsystems is a subsidiary of Oracle Corporation.
Versions of Java
VersionCodename Year Features Added
JDK 1.0 Oak Jan23,1996 -
JDK 1.1
Rebirth of
Java
Feb19,1997
Inner classes JavaBeans, JDBC, RMI, Reflection, AWT.
J2SE 1.2 Playground Dec8, 1998
JIT compiler, Collections, IDL & CORBA, strictfp, Java
Plug-in.
J2SE 1.3 Kestrel May8, 2000
HotSpot JVM, JavaSound, Java Naming and Directory
Interface, Java Platform Debugger Architecture.
J2SE 1.4 Merlin Feb6, 2002
Preferences API, Logging API, assert, image I/O API,
security and cryptography extensions.
J2SE 5.0 Tiger Sep30, 2004
Generics, annotations, Autoboxing, Enumerations, Varargs,
Enhanced for each.
JAVA SE 6 Mustang Dec11, 2006
JDBC 4.0, JVM improvements, Improved JAXB, Improved
web services, Support for older Win9x versions dropped.
JAVA SE 7
Dolphin July28, 2011
Major updates to Java
JAVA SE 8 Spider 2014,March -
16.
Java Platforms
There arethree 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.
17.
Java Development Kit:
Itcontains one (or more) JRE's along with the various
development tools like the Java source compilers, bundling and
deployment tools, debuggers, development libraries, etc.
Java Virtual Machine:
An abstract machine architecture specified by the Java Virtual
Machine Specification.
It interprets the byte code into the machine code depending
upon the underlying OS and hardware combination. JVM is
platform dependent. (It uses the class libraries, and other
supporting files provided in JRE)
Java Terminology
18.
Java Runtime Environment:
Aruntime 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 (contd…)
Java Virtual Machine
Class loader subsystem: A mechanism for loading
types (classes and interfaces) given fully qualified
names.
The Java virtual machine organizes the memory it
needs to execute a program into several runtime data
areas.
Each Java virtual machine also has an execution
engine: a mechanism responsible for executing the
instructions contained in the methods of loaded
classes.
24.
Class loader subsystem
The Java virtual machine contains two kinds of class loaders: a
bootstrap class loader and user-defined class loaders.
The bootstrap class loader is a part of the virtual machine
implementation, and user-defined class loaders are part of the running
Java application.
Loading: finding and importing the binary data for a type
Linking: performing verification, preparation, and (optionally) resolution
Verification: ensuring the correctness of the imported type
Preparation: allocating memory for class variables and initializing the
memory to default values
Resolution: transforming symbolic references from the type into direct
references.
Initialization: invoking Java code that initializes class variables to their proper
starting values.
25.
When the virtualmachine loads a class file, it parses information about
a type from the binary data contained in the class file.
It places this type information into the method area.
As the program runs, the virtual machine places all objects the
program instantiates onto the heap.
As each new thread comes into existence, it gets its own pc register
(program counter) and Java stack.
What isthe Difference b/w OO and OB Languages?
In Object based languages inheritance is not supported so
that dynamic polymorphism also not supported.
E.g. VB,VC++.
Is C++ partial OOP?
Yes, C++ is a partial OOP because without using class also
we can able to write the program.
Is Java total OOP or partial OOP?
Java is a total oop language because with out object
orientation we can’t able to write any program.
28.
Java isa pure oop or not ?
By default java is not pure object oriented language.
Java is called as Hybrid language.
Pure oop languages are “small talk”, ”ruby”, “Eiffel”.
29.
Differences b/w C++and Java
C++ Java
1. Global variable are 1. No Global variables.
supported. Everything must be inside
the class only.
2.Multiple inheritance 2. No direct multiple
is supported. Inheritance.
30.
C++ Java
3.Constructors and3.Java supporting constructors
Destructors supported. only & instead of destructors
garbage collection is
supported.
4.In c++ pointers are 4.No pointer arithmetic in Java.
supported.
5.C++ supporting ASCII 5. Java supports Uni code
character set. Character set.
31.
Buzzwords of Java
Simple
Object-Oriented
Platform independent
Secured
Robust
Architecture neutral
Portable
Interpreted and High Performance
Multithreaded
Dynamic
Distributed
32.
Java Features (1)
Simple
fixes some clumsy features of C++ (ex: explicit pointers,
operator overloading etc. )
automatic garbage collection
rich pre-defined class library
Object oriented
focus on the data (objects) and methods manipulating the data
all functions are associated with objects
almost all datatypes are objects (files, strings, etc.)
potentially better code organization and reuse
33.
Java codecan be run on multiple
platforms
e.g.Windows,Linux,Sun
Solaris,Mac/OS etc.
Java code is compiled by the
compiler and converted into
bytecode.
This bytecode is a platform
independent code because it can
be run on multiple platforms i.e.
Write Once and Run
Anywhere(WORA).
Platform Independent
34.
Java Features (3)
Secure
it is secured because:
No explicit pointer
Programs run inside virtual machine sandbox.
usage in networked environments requires more security
35.
Robust
extensivecompile-time and runtime error checking
Java uses strong memory management .
automatic garbage collection tracks objects usage over time.
Architecture-Neutral
the sizes of the primitive data types are always the same
the libraries define portable interfaces .
Goal of java designers is “write once; run anywhere, any
time, forever.”
36.
Portable
sameapplication runs on all platforms
Interpreted and High Performance
java compiler generate byte-codes, not native machine
code
the compiled byte-codes are platform-independent
java bytecodes are translated on the fly to machine
readable instructions in runtime (Java Virtual Machine)
easy to translate directly into native machine code by
using a just-in-time compiler.
Java Features (2)
37.
Java Features (4)
Multithreaded
multiple concurrent threads of executions can run
simultaneously
The main advantage of multi-threading is that it shares
the same memory.
Threads are important for multi-media, Web
applications etc.
38.
Java Features (5)
Dynamic
java is designed to adapt to evolving environment
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
can check the class type in runtime
39.
Java Features (6)
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).
40.
Byte Code
Bytecodeis a highly optimized set of instructions
designed to be executed by the Java run-time system,
which is called the Java Virtual Machine (JVM).
The JVM is an interpreter for bytecode.
41.
Keywords
abstract continue gotopackage 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
Data Types
Simple TypeDerived Type User Defined Type
Numeric Type Non-Numeric class Interface
Integer Float Char Boolean
float double
byte short int long
E.g: Array, String…
44.
integer types
Javadoes not support unsigned, positive-only integers.
All are signed, positive and negative values.
Name Width 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
45.
byte
Thesmallest 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;
46.
import java.io.*;
public classIntDemo{
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 an 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);
}
}
47.
Floating-Point Types
Thereare two kinds of floating-point types.
All math functions, such as sin( ), cos( ), and sqrt( ), return double values.
Name Width in Bits Approximate Range
double 64 4.9e–324 to 1.8e+308
float 32 1.4e−045 to 3.4e+038
48.
import java.io.*;
public classFloatDemo{
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);
}
}
49.
Characters
char inJava is not the same as char in C or C++.
In C/C++, char is an integer type that is 8 bits wide.
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.
50.
import java.io.*;
public classCharDemo{
public static void main(String args[]){
System.out.println(Character.SIZE);
int c1 = Character.MAX_VALUE;
int c2 = Character.MIN_VALUE;
System.out.println(" c1 = " + c1);
System.out.println(" c2 = " + c2);
}
}
51.
Booleans
It canhave only one of two possible values, true or false.
This is the type returned by all relational operators, such
as a < b.
52.
Variables
The variableis 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] ...] ;
53.
The Scope andLifetime of Variables
Scope
The scope of a declared element is the portion of the program where the element is
visible.
Lifetime
The lifetime of a declared element is the period of time during which it is alive.
Java allows variables to be declared within any block.
A block begins with an opening curly brace and ends by a closing curly brace.
A block defines a scope. Thus, each time you start a new block, you are creating a new scope.
54.
Contd..
In Java,there are major scopes which are defined by a class and a method.
Scopes defined by a method
The scope defined by a method begins with its opening curly brace and ends with closing curly brace.
Scopes can be nested.
Objects declared in the outer scope will be visible to code within the
inner scope. The reverse is not true.
Objects declared within the inner scope will not be visible outside it.
55.
public class Scope
{
publicstatic void main(String args[])
{
int x; //know to all code within main
x=10;
if(x==10)
{ // starts new scope
int y=20; //Known only to this block
//x and y both known here
System.out.println("x and y: "+x+" "+y);
x=y+2;
}
// y=100; // error ! y not known here
//x is still known here
System.out.println("x is "+x);
}
}
The operandsof the arithmetic operators must be of a numeric
type.
You cannot use them on boolean types, but you can use them on
char types.
No fractional component attached to the result, when the division
operator is applied to an integer type.
The modulus operator, %, returns the remainder of a division
operation. It can be applied to floating-point types as well as
integer types.
Ex:- int x = 42;
double y = 42.25;
x mod 10 = 2
y mod 10 = 2.25
58.
// Demonstrate thebasic arithmetic operators.
class BasicMath {
public static void main(String args[]) {
// arithmetic using integers
System.out.println("Integer Arithmetic");
int a = 1 + 1;
int b = a * 3;
int c = b / 4;
int d = c - a;
int e = -d;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
System.out.println("e = " + e);
// arithmetic using doubles
System.out.println("nFloating Point Arithmetic");
double da = 1 + 1;
double db = da * 3;
double dc = db / 4;
double dd = dc - a;
double de = -dd;
System.out.println("da = " + da);
System.out.println("db = " + db);
System.out.println("dc = " + dc);
System.out.println("dd = " + dd);
System.out.println("de = " + de);
}
}
59.
/ Demonstrate ++and --.
class IncDec {
public static void main(String args[]) {
int a = 1;
int b = 2;
int c;
int 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);
}
}
60.
Relational Operators
Therelational 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
61.
Note :-
int done;
// ...
if(!done) ... // Valid in C/C++
if(done) ... // but not in Java.
In Java, these statements must be written like this:
if(done == 0)) ... // This is Java-style.
if(done != 0) ...
In C/C++, true is any nonzero value and false is zero.
In Java, true and false are nonnumeric values which do not relate to zero or
nonzero.
62.
Boolean Logical Operators
The Boolean logical operators operate only on boolean operands.
All of the binary logical operators combine two boolean values to form a resultant
boolean value.
Operator Result
& Logical AND
| Logical OR
^ Logical XOR (exclusive OR)
|| Short-circuit OR
&& Short-circuit AND
! Logical unary NOT
&= AND assignment
|= OR assignment
^= XOR assignment
== Equal to
!= Not equal to
?: Ternary if-then-else
63.
The Assignment Operator
The assignment operator is the single equal sign, =.
var = expression;
Here, the type of var must be compatible with the type of expression.
It allows you to create a chain of assignments.
int x, y, z;
x = y = z = 100; // set x, y, and z to 100
64.
The Bitwise Operators
Java defines several bitwise operators which can be applied to the integer
types, long,int, short, char, and byte.
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
&= Bitwise AND assignment
|= Bitwise OR assignment
65.
Cotnd..
^= Bitwiseexclusive OR assignment
>>= Shift right assignment
>>>= Shift right zero fill assignment
<<= Shift left assignment
66.
The ? Operator
General form:
expression1 ? expression2 : expression3 ;
Here, expression1 can be any expression that evaluates to a
boolean value. If expression1 is true, then expression2 is
evaluated; otherwise, expression3 is evaluated.
67.
// Demonstrate ?.
classTernary {
public static void main(String args[]) {
int i, k;
i = 10;
k = i < 0 ? -i : i; // get absolute value of i
System.out.print("Absolute value of ");
System.out.println(i + " is " + k);
i = -10;
k = i < 0 ? -i : i; // get absolute value of i
System.out.print("Absolute value of ");
System.out.println(i + " is " + k);
}
}
Control Statements
Java’scontrol statements can be put into the following
categories:
selection
iteration
jump
70.
Java’s Selection Statements
Java supports two selection statements:
if ( condition )
Same as in c/c++.
The condition is any expression that returns a boolean value.
Switch( expression )
Same as in c/c++.
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.
71.
// Demonstrate if-else-ifstatements.
class IfElse {
public static void main(String args[]) {
int month = 4; // April
String season;
if(month == 12 || month == 1 || month == 2)
season = "Winter";
else if(month == 3 || month == 4 || month == 5)
season = "Spring";
else if(month == 6 || month == 7 || month == 8)
season = "Summer";
else if(month == 9 || month == 10 || month == 11)
season = "Autumn";
else
season = "Bogus Month";
System.out.println("April is in the " + season + ".");
}
}
72.
class Switch {
publicstatic void main(String args[]) {
int month = 4;
String season;
switch (month) {
case 12:
case 1:
case 2:
season = "Winter";
break;
case 3:
case 4:
case 5:
season = "Spring";
break;
case 6:
case 7:
case 8:
season = "Summer";
break;
case 9:
case 10:
case 11:
season = "Autumn";
break;
default:
season = "Bogus Month";
}
System.out.println("April is in the " + season + ".");
}
}
73.
Iteration Statements
Java’siteration statements are
for
while
do-while.
Syntax is similar to c/c++.
The condition is any expression that returns a boolean value.
74.
Jump Statements
Javasupports three jump statements:
1. break
Using break to Exit a Loop
break;
Using break as a Form of Goto
label :
- - - -
- - - -
break label;
75.
2. continue
Similar to c/c++
3. return
The return statement is used to explicitly return from a method.
It transfers control back to the caller of the method.
76.
Type Conversion andCasting
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
77.
When onetype 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.
For widening conversions, the numeric types, including integer,
floating-point, and double types, are compatible with each other.
Ex:
int a=10;
double b=a;
However, there are no automatic conversion from the numeric types to
char or boolean
Also, char and boolean are not compatible with each other.
78.
The wideningconversion 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
79.
import java.io.*;
public classWidening{
public static void main(String args[]){
short s;
int i1,i2;
byte b1=10,b2=20;
System.out.println(“byte to short conversion");
s=b1;
System.out.println(s);
System.out.println(“byte to int conversion");
i1=b2;
System.out.println(i1);
//char to int
char c='a';
System.out.println(“char to int conversion");
i2=c;
System.out.println(i2);
}
}
80.
The narrowingconversion occurs from a type to a different
type that has a smaller size, such as from a long (64 bits) to
an int (32 bits).
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
The narrowing primitive conversion must be explicit.
You need to specify the target type in parentheses.
81.
it isstill possible to obtain a conversion between incompatible types.
Cast keyword / operator will be used to perform conversion between
incompatible types.
General form:
( target-type ) value;
82.
public classNarrowing
{
public static void main(String args[])
{
byte b;
int i=257;
double d=323.142;
System.out.println("int to byte conversion");
b= (byte)i;
System.out.println("i and b values: "+i+" "+b);
System.out.println("double to int conversion");
i=(int)d;
System.out.println("d and i values: "+d+" "+i);
System.out.println("double to byte conversion");
b=(byte)d;
System.out.println("d and b values: "+d+" "+b);
}
}
83.
Arrays in Java
An array is a data structure that defines an ordered collection of a
fixed number of homogeneous data elements
The size of an array is fixed and cannot increase to accommodate
more elements
84.
Reference variables inJava (1/4)
Reference variables are used in Java to store the references of the objects created by the
operator new
Any one of the following syntax can be used to create a reference to an int array
int x[];
int [] x;
• The reference x can be used for referring to any int array
//Declare a reference to an int array
int [] x;
//Create a new int array and make x refer to it
x = new int[5];
Reference Types inJava (4/4)
A reference type cannot be cast to primitive type
A reference type can be assigned ‘null’ to show that it is not referring to any object
‘null’ is a keyword in Java
int [] x = null;
87.
Initializing an arrayin Java
An array can be initialized while it is created as follows
int [] x = {1, 2, 3, 4};
char [] c = {‘a’, ‘b’, ‘c’};
88.
The length ofan array
Unlike C, Java checks the boundary of an array while accessing an element in it
Java will not allow the programmer to exceed its boundary
If x is a reference to an array, x.length will give you the length of the array
So setting up a for loop as follows is very common in Java
for(int i = 0; i < x.length; ++i){
x[i] = 5;
}
89.
import java.io.*;
public classSortNum{
public static void main(String args[])
{
int number[]={50,67,80,95,34};
int n=number.length;
System.out.println("length of array is"+n);
System.out.print("given list");
for(int i=0;i<n;i++)
{
System.out.print(" "+number[i]);
}
System.out.print("n");
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
if(number[i]<number[j])
{
int temp=number[i];
number[i]=number[j];
number[j]=temp;
}
}
}
System.out.print("sorted list");
for(int i=0;i<n;i++)
{
System.out.print(" "+number[i]);
}
}
}
90.
Multidimensional Arrays
Multidimensionalarrays are arrays of arrays.
To declare a multidimensional array variable, specify each
additional index using another set of square brackets.
int [][] x;
//x is a reference to an array of int arrays
x = new int[3][4];
//Create 3 new int arrays, each having 4 elements
//x[0] refers to the first int array, x[1] to the second and so on
//x[0][0] is the first element of the first array
//x.length will be 3
//x[0].length, x[1].length and x[2].length will be 4
91.
// Demonstrate atwo-dimensional array.
import java.io.*;
public class TwoDArray {
public static void main(String args[]) {
int twoD[][]= new int[4][5];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<5; j++) {
twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<5; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}
92.
Jagged Array
Thelength of each array in a multidimensional array can be different
Such an array is called a Jagged Array
int [][] x;
//x is a reference to an array of int arrays
x = new int[3][];
//Create 3 new int array references, x[0], x[1] and x[2]
//x.length is 3
x[0] = new int[4]; //x[0].length is 4
x[1] = new int[6]; //x[1].length is 6
x[2] = new int[3]; //x[2].length is 3
for(int i = 0; i < x.length; ++i)
for(int j = 0; j < x[i].length; ++j)
System.out.println(x[i][j]);
93.
class TwoDAgain {
publicstatic void main(String args[]) {
int twoD[][] = new int[4][];
twoD[0] = new int[1];
twoD[1] = new int[2];
twoD[2] = new int[3];
twoD[3] = new int[4];
int i, j, k = 0;
for(i=0; i<4; i++)
for(j=0; j<i+1; j++) {
twoD[i][j] = k;
k++;
}
for(i=0; i<4; i++) {
for(j=0; j<i+1; j++)
System.out.print(twoD[i][j] + " ");
System.out.println();
}
}
}
94.
java program structure
•In Java :
In Java :
A program is made up of one or more
A program is made up of one or more classes.
classes.
One class is marked as the special “starting” class.
Name of the file should coincide with the name of starting
class.
When a Java program is launched by the interpreter ( JVM ), it
invokes a static method named “main” in the start class.
95.
Sample Program
public classHelloWorld {
public static void main (String args []) {
System.out.println (“Welcome to Java Programming…..”);
}
}
public allows the program to control the visibility of class
members. When a class member is preceded by public, then that
member may be accessed by code outside the class in which it is
declared. In this case, main ( ) must be declared as public, since it
must be called by code outside of its class when the program is
started.
96.
static allows main() to be called without having to instantiate a
particular instance of the class. This is necessary since main ( ) is
called by the Java interpreter before any objects are made.
void states that the main method will not return any value.
main() is called when a Java application begins. In order to run
a class, the class must have a main method.
string args[] declares a parameter named args, which is an array of
String. In this case, args receives any command-line arguments
present when the program is executed.
97.
System is aclass 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.
The General Formof a Class
• A class is collection of objects of similar type or it is a template
• class classname {
• type instance-variable1;
• type instance-variable2;
• …
• type instance-variableN;
• type methodname1(parameter-list) {
• body of method
• }
• type methodname2(parameter-list) {
• body of method
• }
• …
• type methodnameN(parameter-list) {
• body of method
• }
• }
100.
The data,or variables, defined within a class are called instance
variables.
Functions defined within a class are called methods.
The methods and variables defined within a class are called
members of the class.
• Note:-
• The class declaration and the implementation of the
methods are stored in the same place and not defined separately.
Constructors and Methods
A constructor is a special member function whose task is to initialize the objects of its
class.
A constructor has the same name as the class in which it resides and is syntactically
similar to a method.
A constructor initializes an object immediately upon creation.
The constructor is automatically called immediately after the object is created.
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.
103.
Default Constructor:
Aconstructor 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();
104.
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() {
return w*h*d;
}
105.
class Box {
doublewidth;
double height;
double depth;
// This is the constructor for Box.
Box() {
System.out.println("Constructing Box");
width=2 ;
height =3;
depth =4;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
public class BoxDemo {
public static void main(String args[]) {
// declare, allocate, and initialize Box objects
Box mybox1 = new Box();
double vol;
// get volume of box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
}
}
106.
Parameterized constructor
Theconstructor that can take the arguments are called parameterized constructors
class Box {
double width;
double height;
double depth;
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
}
// declare, allocate, and initialize Box objects
Box mybox1 = new Box(10, 20, 15);
107.
class Box {
doublewidth;
double height;
double depth;
// This is the constructor for Box.
Box(double w, double h, double d) {
System.out.println("Constructing Box");
width = w;
height = h;
depth = d;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
class BoxDemo2 {
public static void main(String args[]) {
// declare, allocate, and initialize Box
objects
Box mybox1 = new Box(1, 2, 5);
Box mybox2 = new Box(3, 6, 9);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
108.
private:
A privatemember is accessible only to the class in which it is defined.
Use private keyword to create private members.
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.
Access Control
109.
public:
Any class,in any package ,has access to a class's public members.
To declare a public member, use the keyword public.
default :
When no access specifier is used, then by default the member of a class is public
within its own package, but cannot be accessed outside of its package.
110.
class Test {
inta; // default access
public int b; // public access
private int c; // private access
/*protected applies only when
inheritance is involved*/
// methods to access c
void setc(int i) { // set c's value
c = i;
}
int getc() { // get c's value
return c;
}
}
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());
}
}
111.
The this Keyword
this keyword is used inside any method to refer to the current
object.
Usage of java this keyword
Here is given the 6 usage of java this keyword.
this keyword can be used to refer current class instance
variable.
this() can be used to invoke current class constructor.
this keyword can be used to invoke current class method
(implicitly)
this can be passed as an argument in the method call.
this can be passed as argument in the constructor call.
this keyword can also be used to return the current class
instance.
112.
Instance Variable Hiding
In java, it is illegal to declare two local variables with the same name inside
the same or enclosing scopes.
But , you can have local variables, including formal parameters to methods,
which overlap with the names of the class’ instance variables.
When a local variable has the same name as an instance variable, the local
variable hides the instance variable.
113.
Contd..
Therefore ,thiscan be used to resolve any name collisions that might occur
between instance variables and local variables.
ex:
double width,height,depth;
Box(double width, double height, double depth) {
this.width = width;
this.height = height;
this.depth = depth;
}
114.
//instance variables andlocal variables are different
class Box
{
int w=5,h=5,d=5;
Box(int w1,int h1, int d1)
{
w=w1;
h=h1;
d=d1;
}
int volume()
{
return w*h*d;
}
}
class Ex5
{
public static void main(String args[])
{
Box b=new Box(1,2,3);
System.out.println("result is"+b.volume());
}
}
115.
// instance variablesand local variables are same
class Box
{
int w=5,h=5,d=5;
Box(int w,int h, int d)
{
w=w;
h=h;
d=d;
}
int volume()
{
return w*h*d;
}
}
class Ex5
{
public static void main(String args[])
{
Box b=new Box(1,2,3);
System.out.println("result is"+b.volume());
}
}
116.
// for hidinginstance variables by using ‘this’ keyword
class Box
{
int w=5,h=5,d=5;
Box(int w,int h, int d)
{
this.w=w;
this.h=h;
this.d=d;
}
int volume()
{
return w*h*d;
}
}
class Ex5
{
public static void main(String args[])
{
Box b=new Box(1,2,3);
System.out.println("result is"+b.volume());
}
117.
2) this()can be used to invoked current class constructor.
The this() constructor call can be used to invoke the current class constructor (constructor chaining).
This approach is better if you have many constructors in the class and want to reuse that constructor.
class Student13{
int id;
String name;
Student13(){
System.out.println("default constructor is invoked");
}
Student13(int id,String name){
this ();//it is used to invoked current class constructor.
this.id = id;
this.name = name;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student13 e1 = new Student13(111,"karan");
Student13 e2 = new Student13(222,"Aryan");
e1.display();
e2.display();
}
}
118.
class Student14{
int id;
Stringname;
String city;
Student14(int id,String name){
this.id = id;
this.name = name;
}
Student14(int id,String name,String city){
this(id,name);//now no need to initialize id and name
this.city=city;
}
void display(){System.out.println(id+" "+name+" "+city);}
public static void main(String args[]){
Student14 e1 = new Student14(111,"karan");
Student14 e2 = new Student14(222,"Aryan","delhi");
e1.display();
e2.display();
}
}
119.
3)The this keywordcan be used to invoke current class method
(implicitly).
You may invoke the method of the current class by using the
this keyword. If you don't use the this keyword, compiler
automatically adds this keyword while invoking the method.
EX:
120.
class S{
void m(){
System.out.println("methodis invoked");
}
void n(){
this.m();//no need because compiler does it for you.
}
void p(){
n();//complier will add this to invoke n() method as this.n()
}
public static void main(String args[]){
S s1 = new S();
s1.p();
}
}
121.
4) this keywordcan be passed as an argument in the method.
The this keyword can also be passed as an argument in the method. It is mainly
used in the event handling.
Ex:
class S2{
void m(S2 obj){
System.out.println("method is invoked");
}
void p(){
m(this);
}
public static void main(String args[]){
S2 s1 = new S2();
s1.p();
}
}
122.
5) Thethis keyword can be passed as argument in the constructor call.
We can pass the this keyword in the constructor also. It is useful if we have to use one object in multiple
classes.
class B{
A4 obj;
B(A4 obj){
this.obj=obj;
}
void display(){
System.out.println(obj.data);//using data member of A4 class
}
}
class A4{
int data=10;
A4(){
B b=new B(this);
b.display();
}
public static void main(String args[]){
A4 a=new A4();
}
}
123.
6) Thethis keyword can be used to return current
class instance.
We can return the this keyword as an statement from the
method. In such case, return type of the method must be the
class type (non-primitive).
Syntax of this that can be returned as a statement
return_type method_name(){
return this;
}
124.
class A{
A getA(){
returnthis;
}
void msg(){System.out.println("Hello java");}
}
class Test1{
public static void main(String args[]){
new A().getA().msg();
}
}
125.
Garbage Collection
objectsare dynamically allocated by using the new operator,
In C++, dynamically allocated objects must be manually released by use of a delete
operator.
Java handles deallocation automatically. This technique is called garbage collection.
Technique
when no. references to an object exist, that object is assumed to be no longer
needed, and the memory occupied by the object can be reclaimed.
Garbage collection only occurs at regular intervals during the execution of your
program.
126.
public class GarbageCollector{
publicstatic void main(String[] args) {
int SIZE = 200;
StringBuffer s;
for (int i = 0; i < SIZE; i++) {
}
System.out.println("Garbage Collection started explicitly.");
long time = System.currentTimeMillis();
System.gc();
System.out.println("It took " + (System.currentTimeMillis()-time) + " ms");
}
}
127.
The 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 handle or
window character font, 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
}
Here, the keyword protected is a specifier that prevents access to finalize( ) by code
defined outside its class.
128.
Overloading Methods
Definingtwo or more methods within the same class that share the same name, as long as their
parameter declarations are different is called method overloading.
When an overloaded method is invoked, Java uses the type and/or number of arguments to determine
which version of the overloaded method to call.
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;
}
}
129.
class Overload {
publicstatic void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
double result;
// call all versions of test()
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): " + result);
}
}
130.
// Automatic typeconversions apply to overloading.
class OverloadDemo {
void test() {
System.out.println("No parameters");
}
// Overload test for two integer parameters.
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
// overload test for a double parameter
void test(double a) {
System.out.println("Inside test(double) a: " + a);
}
}
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
int i = 88;
ob.test();
ob.test(10, 20);
ob.test(i); // this will invoke test(double)
ob.test(123.2); // this will invoke test(double)
}
}
131.
Overloading Constructors
Constructorscan be overloaded.
class Box {
double width, height,depth;
Box(){
width=12.0;
height=5.0;
depth=4.8;
}
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
double volume() {
return width * height * depth;
}
}
All declarations of Box objects must pass three arguments to the Box( ) constructor.
132.
Contd..
the followingstatements are valid
Box ob = new Box();
Box ob=new Box(10.0,20.0,30.0);
133.
Parameter Passing
Call-by-value
The call-by-valuecopies 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
Simple types, int, float, char, double, are passed by value
134.
// Simple typesare 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);
}
}
135.
Call-by-reference
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 formal parameter of the method will effect on the
actual parameter
Objects are passed by reference
136.
// Objects arepassed by reference.
class Test {
int a, b;
Test(int i, int j) {
a = i;
b = j;
}
void meth(Test o) { // pass an object
o.a *= 2;
o.b /= 2;
}
}
class CallByRef {
public static void main(String args[]) {
Test ob = new Test(15, 20);
System.out.println("ob.a and ob.b before call: " +ob.a + " " + ob.b);
ob.meth(ob);
System.out.println("ob.a and ob.b after call: " +ob.a + " " + ob.b);
}
}
137.
Recursion
Recursion isthe process of defining something in terms of itself.
A method that calls itself is said to be recursive.
Ex:class Factorial{
int fact(int n){
int result;
if(n==1)
return 1;
else
result = fact(n-1) * n;
return result;
} }
class Recursion{
public static void main(String args[]) {
Factorial f = new Factorial();
System.out.println("Factorial of 3 is " + f.fact(3));
System.out.println("Factorial of 4 is " + f.fact(4));
System.out.println("Factorial of 5 is " + f.fact(5));
} }
138.
Understanding static
Thestatic keyword is used in java mainly for memory management.
The static keyword belongs to the class than instance of the class.
The static can be:
variable (also known as class variable)
method (also known as class method)
block
nested class
139.
1) static variable
If you declare any variable as static, it is known static variable.
The static variable can be used to refer the common property of all objects
(that is not unique for each object)
e.g. company name of employees, college name of students etc.
The static variable gets memory only once in class area at the time of class
loading.
Advantage of static variable
It makes your program memory efficient (i.e it saves memory).
Understanding problem without static variable
class Student{
int rollno;
String name;
String college="ITS";
}
140.
Example of staticvariable
//Program of static variable
class Student{
int rollno;
String name;
static String college ="ITS";
Student(int r,String n){
rollno = r;
name = n;
}
void display (){
System.out.println(rollno+" "+name+" "+college);}
public static void main(String args[]){
Student s1 = new Student (111,"Karan");
Student s2 = new Student (222,"Aryan");
s1.display();
s2.display();
}
}
141.
2) static method
If you apply static keyword with any method, it is known as static method
A static method belongs to the class rather than object of a class.
A static method can be invoked without the need for creating an instance of a class.
static method can access static data member and can change the value of it.
Example of static method
//Program of changing the common property of all objects(static field).
class Student{
int rollno;
String name;
static String college = "ITS";
static void change(){
college = "BBDIT";
}
Student(int r, String n){
rollno = r;
name = n;
}
void display (){System.out.println(rollno+" "+name+" "+college);}
public static void main(String args[]){
Student.change();
Student s1 = new Student (111,"Karan");
Student s2 = new Student (222,"Aryan");
Student s3 = new Student (333,"Sonoo")
s1.display();
s2.display();
s3.display();
}
}
142.
Methods declared asstatic have several restrictions:
They can only call other static methods.
They must only access static data.
They cannot refer to this or super in any way.
Ex:
class A{
int a=40;//non static
public static void main(String args[]){
System.out.println(a);
}
}
143.
3)static block
Isused to initialize the static data member.
It is executed before main method at the time of class loading.
static block Syntax :
static {
statement1;
statement2;
…….
…….
}
Example of static block
class A{
static{
System.out.println("static block is invoked");
}
public static void main(String args[]){
System.out.println("Hello main");
}
}
144.
4)static nested class
Astatic class that is created inside a class is known as static nested class. It cannot
access the non-static members.
It can access static data members of outer class including private.
static nested class cannot access non-static (instance) data member or
method.
Program of static nested class that have instance method
class Outer{
static int data=30;
static class Inner{
void msg(){System.out.println("data is "+data);}
}
public static void main(String args[]){
Outer.Inner obj=new Outer.Inner();
obj.msg();
}
}
145.
// Demonstration ofstatic variables, methods, and blocks.
public class UseStatic {
static int a = 3; //static variables
static int b;
static void meth(int x) { //static method
System.out.println("x = " + x);
System.out.println("a = " + a);
System.out.println("b = " + b);
}
static { //static block
System.out.println("Static block initialized.");
b = a * 4;
}
public static void main(String args[]) {
meth(42); //static method calling inside the class
}
}
146.
String Handling
inJava a string is a sequence of characters.
But, unlike many other languages that implement strings as character arrays, Java implements
strings as objects of type String.
when you create a String object, you are creating a string that cannot be changed.
• That is, once a String object has been created, you cannot change the characters that
comprise that string.
• You can still perform all types of string operations.
• The difference is that each time you need an altered version of an existing string, a new String
object is created that contains the modifications.
• The original string is left unchanged.
• There are 3 types of String handling classes
• String
• StringBuffer
• StringTokenizer
•
•
147.
String Class
TheString class supports several constructors.
String is an object not an array of characters in java.
once a String object is created, you cannot change the characters that
are in string.
Strings created by a StringBuffer class can be modified after they are
created.
Both the String and StringBuffer classes are defined in java.lang.
148.
Contd..
Constructors
• String s= new String(); - Creates an empty string.
• String s=String(char chars[ ])
Ex:-
char chars[ ] = { 'a', 'b', 'c' };
String s = new String(chars);
• String(char chars[ ], int startIndex, int numChars)
• Ex:-
char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
String s = new String(chars, 2, 3);
We can also create string by using string literal.
String s2 = "abc";
• String(byte asciiChars[])
•String(byte asciiChars[], int startIndex, Int numChars)
Ex:
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);
}
}
151.
• string length
•the length of a string is the number of character that it contains
int length()
ex;
char chars[]={‘a’,’b’,’c’};
String s=new String(chars);
System.out.println(s.length());
152.
Special StringOperations
String Literals
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
153.
Special String Operations
String literals
char c[]={‘a’,’b’,’c’};
String s1=new String(c);
String s2=“abc”; // use string literal
System.out.println("abc".length());
String Concatenation:
String age=“9”;
String s=“he is”+age+”years old.”;
System.out.println(s);
String Concatenation with other data types
ex: String s=“four:”+2+2;
o/p: four:22
String s=“four:”+(2+2);
o/p: four: 4
154.
String Conversion andtoString()
syntax: String toString()
Ex:
class Box {
double width , height , depth;
Box(double w, double h, double d){
width=w;
height=h;
depth=d;
}
public String toString()
{
return "dimensions are "+width+" by" +height+" by"+depth +".";
}
}
class toStringDemo{
public static void main(String args[]){
Box b= new Box(10,12,14);
String s=" Box b:"+b; //concatenate Box objectcls
System.out.println(b); //convert Box to string
System.out.println(s);
}
}
155.
Character Extraction
charAt():
toextract a single character from a string
char charAt(int where)
Ex:
char ch;
ch=“abc”.charAt(1);
getChars():
to extract more than one character at a time,
void getChars(int sourceStart,int SourceEnd,char target[],int targetStart)
156.
class GetCharsDemo
{
public staticvoid main(String args[])
{
char ch[] = new char[10];
String str = "New Version in Java";
str.getChars(5,9,ch,0);
System.out.println(ch);
}
}
Ex:
public classCharArray
{
public static void main(String args[])
{
String text = "Coffee Cup";
char ch[] = text.toCharArray();
for(int i=0;i<ch.length;i++)
{
System.out.print(ch[i]);
}
}
}
160.
String Comparison
Tocompare the strings or substrings within strings.
equals() and equalsIgnoreCase()
Syntax:
boolean equals(Object str)
-str is the String object being compared with the invoking String object
boolean equalsIgnoreCase(String str)
161.
class EqualIgnoreDemo {
publicstatic void main(String args[]) {
String str1 = “hai";
String str2 = "hai";
String str3 = “HAI“;
System.out.println("First String : "+str1);
System.out.println("Second String : "+str2);
System.out.println("Third String : "+str3);
if(str1.equals(str2))
{
System.out.println("Str1 and Str2 are Equal");
}
else
{
System.out.println("Str1 and Str2 are Not Equal");
}
if(str2.equalsIgnoreCase(str3))
{
System.out.println("Str2 and Str3 are Equal");
}
else
{
System.out.println("Str2 and Str3 are Not Equal");
} } }
162.
boolean regionMatches(int startIndex,String str2,int str2StartIndex, int numChars)
boolean regionMatches(boolean ignoreCase,int startIndex, String str2, int
str2StartIndex, int numChars)
163.
class RegionTest
{
public staticvoid main(String args[])
{
String str1 = "This is Test";
String str2 = "THIS IS TEST";
if(str1.regionMatches(true,5,str2,5,3)) // Case, pos1,secString,pos1,len
{
System.out.println("Strings are Equal");
}
else
{
System.out.println("Strings are NOT Equal");
}
}
}
164.
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
int compareTo(String str)
ValueMeaning
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
167.
class SortString {
staticString 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
168.
Searching Strings
indexOf( )Searches for the first occurrence of a
character or substring.
lastIndexOf( ) Searches for the last occurrence of a
character or substring.
169.
int indexOf(intch)
int indexOf(String str)
int indexOf(int ch, int startIndex)
int indexOf(String str, int startIndex)
int lastIndexOf(int ch)
int lastIndexOf(String str)
int lastIndexOf(int ch, int startIndex)
int lastIndexOf(String str, int startIndex)
170.
class indexOfDemo {
publicstatic 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));
}
}
String objects areimmutable,
whenever you want to modify a String, you must either copy it into a StringBuffer or use one of the
following String methods,
String substring(int startIndex)
Here, startIndex specifies the index at which the substring will begin.
it returns a copy of the substring that begins at startIndex and runs to the end of the
invoking string.
String substring(int startIndex, int endIndex)
Here, startIndex specifies the beginning index, and endIndex specifies the stopping
point
The string returned contains all the characters from the beginning index, up to, but
not including, the ending index.
String concat(String str)
This method creates a new object that contains the invoking string with the contents of
str appended to the end
EX:
String s1 = "one";
String s2 = s1.concat("two");
//Using ‘+’
String s1 = "one";
String s2 = s1 + "two";
175.
Extracting Substrings
String s1= “String’s are objects”;
s1.substring(13);
s1.substring(9, 12);
s1.substring(0, 6);
In all examples, s1 is not
not modified
modified
// “objects” “are” “String”
S t r i n
0 1 2 3 4
g ’ s a
5 6 7 8 9
r e o b
10 11 12 13 14
j e c t s
15 16 17 18 19
176.
String replace(char original,char replacement)
The replace( ) method replaces all occurrences of one character in the invoking string
with another character.
Ex:
String s = "Hello".replace('l', 'w');
String replaceAll(String original, String replacement)
String trim( )
Thetrim( ) method returns a copy of the invoking string from which any leading and
trailing whitespace has been removed
Ex:
String s = “ Hello World ".trim();
Changing the Case of Characters Within a String
String toLowerCase( )
String toUpperCase( )
179.
class LowerUpper {
publicstatic void main(String args[]) {
String str1 = "java";
String str2 = "JAVA";
System.out.println("Upper Case Of : "+str1+" is : "+str1.toUpperCase());
System.out.println("Lower Case Of : "+str2+" is : "+str2.toLowerCase());
}
}
180.
String Buffer
StringBufferrepresents growable and writeable character
sequences.
StringBuffer may have characters and substrings inserted in
the middle or appended to the end.
StringBuffer Constructors
StringBuffer defines these three constructors:
StringBuffer( ) //reservse up to 16 char
StringBuffer(int size) //explicitly sets the size of the
StringBuffer(String str)
181.
class BufDec
{
public staticvoid main(String args[])
{
StringBuffer sb1 = new StringBuffer("Coffee Cup" );
StringBuffer sb2 = new StringBuffer(20);
StringBuffer sb3 = new StringBuffer();
System.out.println(sb1);
System.out.println("Buffer 1 Size : "+sb1.capacity());
System.out.println("Buffer 2 Size : "+sb2.capacity());
System.out.println("Buffer 3 Size : "+sb3.capacity());
}
182.
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.
void setLength(int len)
//To set the length of the buffer within a StringBuffer object.
char charAt(intwhere)
//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
EX:// 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 getChars(int sourceStart,int sourceEnd,char target[],int targetStart)
// To copy a substring of a StringBuffer into an array
185.
append():
//concatenates the string representation of any other type of data to the end of the invoking
StringBuffer object
StringBuffer append(String str)
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.
186.
class appendDemo{
public staticvoid main(String args[]){
String s;
int a=30;
StringBuffer sb= new StringBuffer(40);
s=sb.append(“a=“).append(a).append(“!”).toString();
}
}
class InsertDemo {
publicstatic void main(String args[]) {
char ch[] = {'J','A','V','A'};
StringBuffer sb1 = new StringBuffer("ring");
System.out.println("String is : "+sb1);
StringBuffer sb2 = sb1.insert(0,'B');
System.out.println("String after inserting 'B' : "+sb2);
StringBuffer sb3 = sb1.insert(sb1.length(),ch);
System.out.println("String after inserting chars (java) : "+sb3);
}
}
189.
StringBuffer reverse()
//reverse the characters within a StringBuffer object using reverse( )
// Using reverse() to reverse a StringBuffer.
Ex: class ReverseDemo{
public static void main(String args[]){
StringBuffer s= new StringBuffer(“abcdef”);
System.out.println(s);
s.reverse();
System.out.println(s);
}
}
190.
delete() anddeleteCharAt()
deletes a sequence of characters from the invoking object.
StringBuffer delete(int startIndex, int endIndex)
StringBuffer deleteCharAt(int loc)
class deleteDemo{
public static void main(String args[]){
StringBuffer sb = new StringBuffer(“this is test.”);
sb.delete(4,7);
System.out.println(“After delete: “+sb);
sb.deleteCharAt(0);
System.out.println(“After deleteCharAt: “+sb);
}
}
191.
StringBuffer replace(intstartIndex, int endIndex, String str)
Ex:
StringBuffer sb= new StringBuffer(“this is a test”);
Sb.replace(5,7,”was”);
String substring(int startIndex)
//to return sub strings.
String substring(int startIndex, int endIndex)
192.
StringTokenizer
The StringTokenizerclass provides the first step in this 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
you specify an input string and a string that contains delimiters
Delimiters are characters that separate tokens
Each character in the delimiters string is considered a valid delimiter
ex: “ ,;:”
The default set of delimiters consists of the whitespace characters:,space, tab,
newline,carriage return
token <= identifier | keyword | separator | operator
| literal | comment
193.
The StringTokenizer constructors
StringTokenizer(String str)
StringTokenizer(String str, String delimiters)
StringTokenizer(String str, String delimiters, boolean delimAsToken)
in all versions, str is the string that will be tokenized.
Write ajava program that reads a line of integers and then displays
each integer and find the sum of the integers (using StringTokenizer)
198.
import java.util.*;
class SumOfInt{
publicstatic void main(String args[]){
//String s=“1+2+3+4+5+6+7”;
Scanner s= new Scanner(System.in);
String t=s.next();
int sum=0;
StringTokenizer st=new StringTokenizer(t,"+");
while(st.hasMoreTokens())
{
String a=st.nextToken();
System.out.println(a);
sum=sum+Integer.parseInt(a);
}
System.out.println("sum of all integers is: "+sum);
}
}
199.
token <=identifier | keyword | separator | operator | literal | comment
Identifiers: names the programmer chooses
Keywords: names already in the programming language
Separators (also known as punctuators): punctuation characters and
paired-delimiters
Operators: symbols that operate on arguments and produce results
Literals (specified by their type)
Numeric: int and double
Logical: boolean
Textual: char and String
Reference: null
Comments
Line
Block
Editor's Notes
#20 The JVM Runtime Environment
The byte codes are stored in class files. At runtime, the bytecodes that make up a java software program are loaded, checked, and run in an interpreter. The interpreter has two functions: it executes bytecodes, and makes the appropriate calls to the underlying hardware.
The Java runtime environment runs code compiled for a JVM and performs four main tasks:
Loads Code - Performed by the class loader
Verifies Code - Performed by the bytecode verifier
Executes Code - Performed by the runtime interpreter
Garbage Collection - De allocates memory not being used
Class Loader
The class loader loads all classes needed for the execution of a program. The class loader adds security by separating the namespaces for the classes of the local file system from those imported from network sources.
Once all the classes have been loaded, the memory layout of the executable file is determined. At this point specific memory addresses are assigned to symbolic references and the lookup table is created. Because memory layout occurs at runtime, the java technology interpreter adds protection against unauthorized access into the restricted areas of code.
Java software code passes several tests before actually running on your machine. The JVM puts the code through a bytecode verifier that tests the format of code fragments and checks code fragments for illegal code – code that forges pointers, violates access rights on objects, or attempts to change object type.