Unit-1 JAVA Notes
Unit-1 JAVA Notes
Introduction
Classes and Objects
String Handling
UNDERSTANDING JAVA’S OBJECT-ORIENTED DEVELOPMENT
Object Oriented Programming is a programming concept that works on the principle that
objects are the most important part of your program.
It allows users create the objects that they want and then create methods to handle those
objects. Manipulating these objects to get results is the goal of Object Oriented
Programming.
Object Oriented Programming popularly known as OOP, is used in a modern
programming language like Java. Java is object-oriented.
Object-oriented languages are better than “Do this/Do that” languages because they
organize data in a way that lets people do all kinds of things with it.
To modify the data, you can build on what you already have, rather than scrap
everything you’ve done and start over each time you need to do something new.
Although computer programmers are generally smart people, they took a while to figure
this out.
Advantages of OOPS:
1. OOP offers easy to understand and a clear modular structure for programs.
2. Objects created for Object-Oriented Programs can be reused in other programs. Thus it
saves significant development cost.
3. Large programs are difficult to write, but if the development and designing team follow
OOPS concept then they can better design with minimum flaws.
4. It also enhances program modularity because every object exists independently.
JAVA Buzzwords:
Java buzzwords are the key considerations for adopting the JAVA language.
1. Simple
2. Secure
3. Portable
4. Object-oriented
5. Robust
6. Multithreaded
7. Architecture-neutral
8. Interpreted
9. High performance
10. Distributed
11. Dynamic`
1. Simple:
Java was designed to be easy for the professional programmer to learn and use
effectively.
As many of the JAVA concepts are inherited from C & C++. Having the prior
knowledge of these two languages will make our learning job easier.
One will not find Java hard to learn. Moving to Java will require very little effort.
2. Secure:
When we download a “normal” program, we are taking a risk, because the code we are
downloading might contain a virus, Trojan horse, or other harmful code.
Malicious code can cause damage, because it can gain unauthorized access to system
resources. For example, a virus program might gather private information, such as credit
card numbers, bank account balances, and passwords, by searching the contents of any
computer local file system.
Java achieved this protection by limiting an applet to the Java execution environment
and not allowing it access to other parts of the computer.
3. Portable
Portability is a major aspect of the Internet because there are many different types of
computers and operating systems connected to it.
A Java program can run on any computer connected to the Internet, there needed to be
some way to enable that program to execute on different systems. The Java Virtual
Machine is the solution for providing the portability.
4. Object Oriented
Java manages to maintain a balance between the “everything is an object” paradigm and
the non-object model.
The object model in Java is simple and easy to extend, while primitive types, such as
integers, are kept as high-performance non-objects.
5. Robust
The multi-platform environment of the Web increases the demands on a robust program,
because the program must execute reliably in a variety of systems.
Thus, the ability to create robust programs was given a high priority.
Java checks the code at compile time and also checks it at run time.
Many hard-to-track-down bugs are simply impossible to create in Java.
Knowing that what you have written will behave in a predictable way under diverse
conditions is a key feature of Java.
6. Multi-Threaded
Java was designed to meet the real-world requirement of creating interactive, networked
programs.
To accomplish this, Java supports multithreaded programming, which allows us to write
programs that do many things simultaneously.
7. Architecture-Neutral
Programmers face a problem that if they write a program today, there is no guarantee
that it will run tomorrow—even on the same machine.
Operating system upgrades, processor upgrades, and changes in core system resources
can make a program malfunction.
To solve this issue, the Java designers made several hard decisions in the Java language
and the Java Virtual Machine.
Their goal was “write once; run anywhere, anytime, forever.” To a great extent, this
goal was accomplished.
8 & 9. Interpreted and High Performance
Java enables the creation of cross-platform programs by compiling into an intermediate
representation called Java bytecode.
This code can be executed on any system that implements the Java Virtual Machine.
Many previous attempts were made to get cross-platform solutions, but resulted degrade
in performance.
Java bytecode was designed very carefully so that it can easily translate directly into
native machine code with very high performance by using a just-in-time compiler.
10. Distributed
Java is designed for the distributed environment of the Internet.
It supports TCP/IP protocols for accessing a resource using a URL and Remote Method
Invocation (RMI) to invoke methods across a network.
11. Dynamic
Java programs carry substantial amounts of run-time information with them, which is
used to verify and resolve accesses to objects at run time.
This enables a possibility to dynamically link code in a safe manner.
DATA TYPES:
Java defines eight primitive types of data: byte, short, int, long, char, float, double, and Boolean.
These can be put in four groups:
Integers: This group includes byte, short, int, and long, which are for whole-valued
signed numbers.
Floating-point numbers: This group includes float and double, which represent
numbers with fractional precision.
Characters: This group includes char, which represents symbols in a character set, like
letters and numbers.
Boolean: This group includes Boolean, which is a special type for representing
true/false values.
Integers:
Java defines four integer types: byte, short, int, and long.
All of these are signed, positive and negative values.
Java does not support unsigned, positive-only integers.
Floating-point numbers:
Floating-point numbers, also known as real numbers, are used when evaluating
expressions that require fractional precision. For example, calculations such as square
root.
There are two kinds of floating-point types, float and double, which represent single-
and double-precision numbers, respectively.
Name Width in Bits Approximate Range
double 64 4.9e–324 to 1.8e+308
float 32 1.4e–045 to 3.4e+038
Characters
In Java, the data type used to store characters is char.
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.
For this purpose, it requires 16 bits. Thus, in Java char is a 16-bit type.
The range of a char is 0 to 65,536. There are no negative chars.
The standard set of characters known as ASCII still ranges from 0 to 127 as always, and
the extended 8-bit character set, ISO-Latin-1, ranges from 0 to 255.
Boolean:
Java has a primitive type, called Boolean, for logical values.
It can have only one of two possible values, true or false.
This is the type returned by all relational operators and conditional expressions.
LITERALS
Integer literals
Integers are probably the most commonly used type in the typical program. Any whole
number value is an integer literal.
Examples are 1, 2, 3, and 42.
These are all decimal values, meaning they are describing a base 10 number.
Floating-Point Literals
Floating-point numbers represent decimal values with a fractional component.
Examples include 6.022E23, 314159E–05 and 2e+100.
Boolean Literals
Boolean literals are simple. There are only two logical values that a Boolean value can
have, true and false.
The values of true and false do not convert into any numerical representation.
The true literal in Java does not equal 1, nor does the false literal equal 0.
Character Literals
Characters in Java are indices into the Unicode character set.
They are 16-bit values that can be converted into integers and manipulated with the
integer operators, such as the addition and subtraction operators.
Aliteral character is represented inside a pair of single quotes. All of the visible ASCII
characters can be directly entered inside the quotes, such as ‘a’, ‘z’, and ‘@’.
String Literals
String literals in Java are specified like they are in most other languages—by enclosing a
sequence of characters between a pair of double quotes. Examples of string literals are
“Hello World”
“two\nlines”
“\”This is in quotes\”“
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.
In addition, all variables have a scope, which defines their visibility, and a lifetime.
Declaring a Variable
In Java, all variables must be declared before they can be used.
The basic form of a variable declaration is shown here:
type identifier [ = value][, identifier [= value] ...] ;
Dynamic Initialization
Java allows variables to be initialized dynamically, using any expression valid at the
time the variable is declared.
Example:
class DynInit {
public static void main(String args[])
{
int a = 3, b = 4;
// c is dynamically initialized
int c = a * b);
System.out.println("Hypotenuse is " + c);
}
}
OPERATORS
Java provides a rich operator environment. Most of its operators can be divided into
the following four groups: arithmetic, bitwise, relational, and logical.
Java also defines some additional operators that handle certain special situations.
Arithmetic Operators
Arithmetic operators are used in mathematical expressions in the same way that they
are used in algebra.
The following table lists the arithmetic operators:
Operator Results
+ Addition
- Subtraction (also unary minus)
* Multiplication
/ Division
% Modulus
++ Increment
+= Addition assignment
-= Subtraction assignment
*= Multiplication assignment
/= Division assignment
%= Modulus assignment
-- Decrement
00001010 10
00100101 37
Using the Bitwise Logical Operators
Example: // Demonstrate the bitwise logical operators.
class BitLogic {
public static void main(String args[]) {
String binary[] = {
"0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111",
"1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111"
};
int a = 3; // 0 + 2 + 1 or 0011 in binary
int b = 6; // 4 + 2 + 0 or 0110 in binary
int c = a | b;
int d = a & b;
int e = a ^ b;
int f = (~a & b) | (a & ~b);
System.out.println(" a = " + binary[a]);
System.out.println(" b = " + binary[b]);
System.out.println(" a|b = " + binary[c]);
System.out.println(" a&b = " + binary[d]);
System.out.println(" a^b = " + binary[e]);
System.out.println("~a&b|a&~b = " + binary[f]);
}
}
Output:
a = 0011
b = 0110
a|b = 0111
a&b = 0010
a^b = 0101
~a&b|a&~b = 0101
Example:
class OpBitEquals {
public static void main(String args[]) {
int a = 1;
int b = 2;
int c = 3;
a |= 4;
b >>= 1;
c <<= 1;
a ^= c;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
}
}
Output:
a=3
b=1
c=6
Relational Operators
The relational operators determine the relationship that one operand has to the other.
Specifically, 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
The outcome of these operations is a boolean value. The relational operators are most
frequently used in the expressions that control the if-statement and the various loop
statements.
Any type in Java, including integers, floating-point numbers, characters, and Booleans
can be compared using the equality test, ==, and the inequality test, !=.
Example:
int a = 4;
int b = 1;
boolean c = a < b;
The result of a<b (which is false) is stored in c.
The logical Boolean operators, &, |, and ^, operate on boolean values in the same way
that they operate on the bits of an integer.
The logical ! operator inverts the Boolean state: !true == false and !false == true.
A B A|B A&B A^B !A
False False False False False True
True False True False True False
False True True False True True
True True True True False False
Operator Precedence
The following table shows the order of precedence for Java operators, from highest to
lowest.
Highest
() [] .
++ -- ~ !
* / %
+ -
>> >>> <<
> >= < <=
== !=
&
^
|
&&
||
?:
= OP=
Lowest
Example:
int a=10, b=10, c=30;
int res=a+b*c; <same> int res=a+(b*c);
To override the precedence int res=(a+b)*c;
CONTROL STATEMENTS
Programming language uses control statements to control the flow of execution of
program.
Java’s program control statements can be put into the following categories: selection,
iteration, and jump.
Selection statements allow your program to choose different paths of execution based
upon the outcome of an expression or the state of a variable.
Iteration statements enable program execution to repeat one or more statements.
Jump statements allow your program to execute in a nonlinear fashion.
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.
The value of the expression is compared with each of the literal values in the case
statements. If a match is found, the code sequence following that case statement is
executed.
If none of the constants matches the value of the expression, then the default statement is
executed.
The break statement is used inside the switch to terminate a statement sequence.
Example: // A simple example of the switch.
class SampleSwitch {
public static void main(String args[]) {
for(int i=0; i<6; i++)
switch(i) {
case 0:
System.out.println("i is zero.");
break;
case 1:
System.out.println("i is one.");
break;
case 2:
System.out.println("i is two.");
break;
case 3:
System.out.println("i is three.");
break;
default:
System.out.println("i is greater than 3.");
}
}
}
Output:
i is zero.
i is one.
i is two.
i is three.
i is greater than 3.
i is greater than 3.
ITERATION STATEMENTS
In Java iteration statements are for, while, and do-while.
We commonly call them loops.
A loop repeatedly executes the same set of instructions until a termination condition is
met.
while Statement
The while loop repeats a statement or block until its controlling expression is true.
General form:
while(condition) {
// body of loop
}
do-while Statement
When it is desirable to execute the body of a loop at least once, even if the conditional
expression is false, in such situations we use do-while loop.
In do-while loop the termination expression is tested at the end of the loop rather than at
the beginning.
General form:
do {
// body of loop
} while (condition);
Each iteration of the do-while loop first executes the body of the loop and then evaluates
the conditional expression.
If this expression is true, the loop will repeat. Otherwise, the loop terminates.
Example: // Demonstrate the do-while loop.
class DoWhile {
public static void main(String args[]) {
int n = 10;
do {
System.out.println("tick " + n);
n--;
} while(n > 0);
}
}
do {
System.out.println("tick " + n);
} while(--n > 0);
Output:
In this example, the expression (– –n > 0) combines the decrement of n and the test for
zero into one expression.
The do-while loop is especially useful when you process a menu selection, because you
will usually want the body of a menu loop to execute at least once.
Example: // Using a do-while to process a menu selection
class Menu {
public static void main(String args[]) throws java.io.IOException {
char choice;
do {
System.out.println("Help on:");
System.out.println(" 1. if");
System.out.println(" 2. switch");
System.out.println(" 3. while");
System.out.println(" 4. do-while");
System.out.println(" 5. for\n");
System.out.println("Choose one:");
choice = (char) System.in.read();
} while( choice < '1' || choice > '5');
System.out.println("\n");
switch(choice) {
case '1':
System.out.println("The if:\n");
System.out.println("if(condition) statement;");
System.out.println("else statement;");
break;
case '2':
System.out.println("The switch:\n");
System.out.println("switch(expression) {");
System.out.println(" case constant:");
System.out.println(" statement sequence");
System.out.println(" break;");
System.out.println(" // ...");
System.out.println("}");
break;
case '3':
System.out.println("The while:\n");
System.out.println("while(condition) statement;");
break;
case '4':
System.out.println("The do-while:\n");
System.out.println("do {");
System.out.println(" statement;");
System.out.println("} while (condition);");
break;
case '5':
System.out.println("The for:\n");
System.out.print("for(init; condition; iteration)");
System.out.println(" statement;");
break;
}
}
}
Output:
Here is a sample run produced by this program:
Help on:
1. if
2. switch
3. while
4. do-while
5. for
Choose one:
4
The do-while:
do {
statement;
} while (condition);
Here is one more for loop variation. You can intentionally create an infinite loop (a loop
that never terminates) if you leave all three parts of the for empty.
For example:
for( ; ; ) {
// ...
}
This loop will run forever because there is no condition under which it will terminate.
The For-Each Version of the for Loop
Beginning with JDK 5, a second form of for was defined that implements a “for-each”
style loop.
A for-each style loop is designed to cycle through a collection of objects, such as an
array, in strictly sequential fashion, from start to finish.
Java adds the for-each capability by enhancing the for statement.
The advantage of this approach is that no new keyword is required, and no preexisting
code is broken.
The for-each style of for is also referred to as the enhanced for loop.
General form:
for(type itr-var : collection) statement-block;
Here, type specifies the type and itr-var specifies the name of an iteration variable that
will receive the elements from a collection, one at a time, from beginning to end.
The collection being cycled through is specified by collection.
There are various types of collections that can be used with the for, but the only type
used in this chapter is the array.
With each iteration of the loop, the next element in the collection is retrieved and stored
in itr-var.
The loop repeats until all elements in the collection have been obtained.
Because the iteration variable receives values from the collection, type must be the same
as (or compatible with) the elements stored in the collection.
Examples:
Regular for loop
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;
for(int i=0; i < 10; i++) sum += nums[i];
The for-each form
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;
for(int x: nums) sum += x;
The iteration variable in for-each style loop is “read-only” as it relates to the underlying
array.
An assignment to the iteration variable has no effect on the underlying array.
We can’t change the contents of the array by assigning the iteration variable a new
value.
Example: // The for-each loop is essentially read-only.
class NoChange {
public static void main(String args[]) {
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
for(int x : nums) {
System.out.print(x + " ");
x = x * 10; // no effect on nums
}
System.out.println();
for(int x : nums)
System.out.print(x + " ");
System.out.println();
}
}
Output:
Nested Loops
Java allows loops to be nested. That is, one loop may be inside another.
For example: // Loops may be nested.
class Nested {
public static void main(String args[]) {
int i, j;
for(i=0; i<10; i++) {
for(j=i; j<10; j++)
System.out.print(".");
System.out.println();
}
}
}
Output:
..........
.........
........
.......
......
.....
....
...
..
.
JUMP STATEMENTS
Java supports three jump statements: break, continue, and return.
These statements transfer control to another part of your program.
Using break
In Java, the break statement has three uses:
a. First, as you have seen, it terminates a statement sequence in a switch statement.
b. Second, it can be used to exit a loop.
c. Third, it can be used as a “civilized” form of goto.
The last two uses are explained here:
Using break to Exit a Loop
By using break, we can force termination of a loop, bypassing the conditional expression
and any remaining code in the body of the loop.
When a break statement is used inside a loop, the loop is terminated and program control
resumes at the next statement following the loop.
Example: // Using break to exit a loop.
class BreakLoop {
public static void main(String args[]) {
for(int i=0; i<100; i++) {
if(i == 10) break; // terminate loop if i is 10
System.out.println("i: " + i);
}
System.out.println("Loop complete.");
}
}
Output:
i: 0
i: 1
i: 2
i: 3
i: 4
i: 5
i: 6
i: 7
i: 8
i: 9
Loop complete.
One of the most common uses for a labeled break statement is to exit from nested loops.
Example: // Using break to exit from nested loops
class BreakLoop4 {
public static void main(String args[]) {
outer: for(int i=0; i<3; i++) {
System.out.print("Pass " + i + ": ");
for(int j=0; j<100; j++) {
if(j == 10) break outer; // exit both loops
System.out.print(j + " ");
}
System.out.println("This will not print");
}
System.out.println("Loops complete.");
}
}
Output:
Pass 0: 0 1 2 3 4 5 6 7 8 9 Loops complete.
Using continue
The continue statement is useful to continue running the loop but stop processing the
remainder of the code in its body for this particular iteration.
The continue statement performs such an action.
In while and do-while loops, a continue statement causes control to be transferred
directly to the conditional expression that controls the loop.
In a for loop, control goes first to the iteration portion of the for statement and then to
the conditional expression.
For all three loops, any intermediate code is bypassed.
Example: // Demonstrate continue.
class Continue {
public static void main(String args[]) {
for(int i=0; i<10; i++) {
System.out.print(i + " ");
if (i%2 == 0) continue;
System.out.println("");
}
}
}
Output:
01
23
45
67
89
As with the break statement, continue may specify a label to describe which enclosing
loop to continue.
Example: // Using continue with a label.
class ContinueLabel {
public static void main(String args[]) {
outer: for (int i=0; i<10; i++) {
for(int j=0; j<10; j++) {
if(j > i) {
System.out.println();
continue outer;
}
System.out.print(" " + (i * j));
}
}
System.out.println();
}
}
Output:
0
01
024
0369
0 4 8 12 16
0 5 10 15 20 25
0 6 12 18 24 30 36
0 7 14 21 28 35 42 49
0 8 16 24 32 40 48 56 64
0 9 18 27 36 45 54 63 72 81
return Statement:
The return statement is used to explicitly return from a method.
That is, it causes program control to transfer back to the caller of the method.
At any time in a method the return statement can be used to cause execution to branch
back to the caller of the method.
Thus, the return statement immediately terminates the method in which it is executed.
Example: // Demonstrate return.
class Return {
public static void main(String args[]) {
boolean t = true;
System.out.println("Before the return.");
if(t) return; // return to caller
System.out.println("This won't execute.");
}
}
Output:
Before the return.
Here, return causes execution to return to the Java run-time system, since it is the run-
time system that calls main( ).
COMMENTS:
Comments are used for documenting the code for understanding.
There are three types of comments defined by Java.
1. Single-line Comment
// Single Line Comment
2. Multiline Comment
/* Line – 1
Line – 2
Line – 3 Multiline Comments */
3. Documentation comment
/** Documentation Comment
Documentation Comment */
SEPARATORS:
In Java, there are a few characters that are used as separators.
The most commonly used separator in Java is the semicolon.
SYMBOL NAME PURPOSE
() Parentheses Used to contain lists of parameters in method definition and invocation.
Also used for defining precedence in expressions, containing
expressions in control statements, and surrounding cast types.
{} Braces Used to contain the values of automatically initialized arrays. Also used
to define a block of code, for classes, methods, and local scopes.
[] Brackets Used to declare array types. Also used when dereferencing array
values.
. Period Used to separate package names from subpackages and classes. Also
used to separate a variable or method from a reference variable.
INTRODUCING CLASSES
The class is at the core of Java.
It is the logical construct upon which the entire Java language is built because it defines
the shape and nature of an object.
The class forms the basis for object-oriented programming in Java.
Any concept you wish to implement in a Java program must be encapsulated within a
class.
Class Fundamentals
Classes have been used since the beginning of this book, simply to encapsulate the
main( ) method, which has been used to demonstrate the basics of the Java syntax.
Class is used to define a new data type. Once defined, this new type can be used to
create objects of that type.
Thus, a class is a template for an object, and an object is an instance of a class.
The two words object and instance used interchangeably.
The General Form of a Class
When you define a class, you declare its exact form and nature.
You do this by specifying the data that it contains and the code that operates on that
data.
While very simple classes may contain only code or only data, most real-world classes
contain both.
General form:
class classname {
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list) {
// body of method
}
// ...
type methodnameN(parameter-list) {
// body of method
}
}
The data, or variables, defined within a class are called instance variables.
The code is contained within methods.
Collectively, the methods and variables defined within a class are called members of the
class.
Variables defined within a class are called instance variables because each instance of
the class (that is, each object of the class) contains its own copy of these variables.
Thus, the data for one object is separate and unique from the data for another.
All methods have the same general form as main( ), they will not be specified as static or
public. Java classes do not need to have a main( ) method.
Only one of the program class is the starting point for your program and is going to have
a main() method. Further, applets don’t require a main( ) method at all.
A Simple Class
Here is a class called Box that defines three instance variables: width, height, and depth.
Currently, Box does not contain any methods.
class Box {
double width;
double height;
double depth;
}
After this statement executes, mybox will be an instance of Box. Thus, it will have
“physical” reality.
Every Box object will contain its own copies of the instance variables width, height, and
depth. To access these variables, you will use the dot (.) operator.
The dot operator links the name of the object with the name of an instance variable.
mybox.width = 100;
Example Program
class Box {
double width;
double height;
double depth;
}
// This class declares an object of type Box.
class BoxDemo {
public static void main(String args[]) {
Box mybox = new Box();
double vol;
// assign values to mybox's instance variables
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
// compute volume of box
vol = mybox.width * mybox.height * mybox.depth;
System.out.println("Volume is " + vol);
}
}
Output:
Volume is 3000.0
File that contains this program should br BoxDemo.java, because the main( ) method is
in the class called BoxDemo, not the class called Box.
When you compile this program, you will find that two .class files have been created,
one for Box and one for BoxDemo.
The Java compiler automatically puts each class into its own .class file.
To run this program, you must execute BoxDemo.class.
Each object has its own copies of the instance variables.
This means that if you have two Box objects, each has its own copy of depth,
width, and height.
It is important to understand that changes to the instance variables of one object
have no effect on the instance variables of another.
Example: Demonstrating the effect on the instance variables.
class Box {
double width;
double height;
double depth;
}
class BoxDemo2 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
/* assign different values to mybox2's
instance variables */
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
// compute volume of first box
vol = mybox1.width * mybox1.height * mybox1.depth;
System.out.println("Volume is " + vol);
// compute volume of second box
vol = mybox2.width * mybox2.height * mybox2.depth;
System.out.println("Volume is " + vol);
}
}
Output:
Volume is 3000.0
Volume is 162.0
Declaring Objects
When we create a class, we are creating a new data type.
We can use this type to declare objects of that type.
Obtaining objects of a class is a two-step process.
First, we must declare a variable of the class type. This variable does not define
an object. Instead, it is simply a variable that can refer to an object.
Second, we must acquire an actual, physical copy of the object and assign it to
that variable. We can do this using the new operator. The new operator
dynamically allocates (that is, allocates at run time) memory for an object and
returns a reference to it.
The following is used to declare an object of type Box:
Box mybox = new Box();
This statement combines the two steps just described:
Box mybox; // declare reference to object
mybox = new Box(); // allocate a Box object
Although b1 and b2 both refer to the same object, they are not linked in any other
way.
A subsequent assignment to b1 will simply unhook b1 from the original object
without affecting the object or affecting b2.
Example:
Box b1 = new Box();
Box b2 = b1;
// ...
b1 = null;
Introducing Methods
Classes usually consist of two things: instance variables and methods.
A method is a set of statements or logic encoded as a single unit.
General form:
type name(parameter-list) {
// body of method
}
The type specifies the type of data returned by the method. This can be any valid
type, including class types that you create. If the method does not return a value,
its return type must be void.
The name of the method name can be any legal identifier.
The parameter-list is a sequence of type and identifier pairs separated by
commas. Parameters are essentially variables that receive the value of the
arguments passed to the method when it is called. If the method has no
parameters, then the parameter list will be empty.
Adding a Method to the Box Class
Methods are used to access the instance variables defined by the class.
Methods define the interface to most classes.
Example:
class Box {
double width;
double height;
double depth;
// display volume of a box
void volume() {
System.out.print("Volume is ");
System.out.println(width * height * depth);
}
}
class BoxDemo3 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
/* assign different values to mybox2's instance variables */
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
// display volume of first box
mybox1.volume();
// display volume of second box
mybox2.volume();
}
}
Output:
Volume is 3000.0
Volume is 162.0
class BoxDemo6 {
public static void main(String args[]) {
// declare, allocate, and initialize Box objects
Box mybox1 = new Box();
Box mybox2 = new Box();
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);
}
}
Output:
Parameterized Constructors
To initialize object properties with various values, rather than having the values
for all objects, the parameterized constructor is used.
For example: // Parameterized Constructors
class Box {
double width;
double height;
double depth;
// This is the constructor for Box.
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// compute and return volume
double volume() {
return width * height * depth;
}
}
class BoxDemo7 {
public static void main(String args[]) {
// declare, allocate, and initialize Box objects
Box mybox1 = new Box(10, 20, 15);
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);
}
}
Output:
Volume is 3000.0
Volume is 162.0
THIS KEYWORD
The this keyword refers to the current object in a method or constructor.
The most common use of this keyword is to eliminate the confusion between class attributes
and parameters with the same name (because a class attribute is shadowed by a method or
constructor parameter). this keyword can be used to refer current class instance variable. If
there is ambiguity between the instance variables and parameters, this keyword resolves the
problem of ambiguity.
this can also be used to:
Invoke current class constructor
Invoke current class method
Return the current class object
Pass an argument in the method call
Pass an argument in the constructor call
Understanding the problem without this keyword
Let's understand the problem if we don't use this keyword by the example given below:
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
rollno=rollno;
name=name;
fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis1{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
Output:
0 null 0.0
0 null 0.0
In the above example, parameters (formal arguments) and instance variables are same. So, we
are using this keyword to distinguish local variable and instance variable.
Solution of the above problem by this keyword
class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display(){System.out.println(rollno+" "+name+" "+fee);}
}
class TestThis2{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}}
Output:
111 ankit 5000.0
112 sumit 6000.0
SUPER KEYWORD
The most common use of the super keyword is to eliminate the confusion between superclasses and
subclasses that have methods with the same name.
EXAMPLE:
class A
int p=10;
void show() {
System.out.println("class A:"+p);
class B extends A {
int q=20;
int p=45;
void show () {
super.show();
System.out.println("class B:"+super.p);
System.out.println("class B:"+p);
Obj.show();
class B:10
class B:45
GARBAGE COLLECTION
Objects are dynamically allocated by using the new operator.
Java takes a different approach to destroy the objects and release the memory; it handles
deallocation automatically. This technique is called garbage collection.
When no references to an object exist, that object is assumed to be no longer needed,
and the memory occupied by that object can be released.
There is no need to destroy the objects explicitly. Garbage collection only occurs during
the execution of your program.
OVERLOADING METHODS
If two or more methods within the same class that share the same name, with different
parameter declarations, the methods are said to be overloaded, and the process is
referred to as method overloading.
Method overloading is one of the ways that Java supports polymorphism.
When Java encounters a call to an overloaded method, it checks the type and/or number
of arguments as its guide to determine the version of the overloaded method to actually
call.
Example: // Overloading Methods
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);
}
}
Output:
OVERLOADING CONSTRUCTORS
Like methods the constructors can also be overloaded with different type and/or number
of arguments.
This process is called constructor overloading.
Example: // Constructor Overloading.
class Box {
double width;
double height;
double depth;
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
Box() {
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}
Box(double len) {
width = height = depth = len;
}
double volume() {
return width * height * depth;
}
}
class OverloadCons {
public static void main(String args[]) {
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
}
}
Output:
Call-by-reference mechanism:
When an object is passed the reference of a class is passed.
Creating a variable of a class type only creates a reference to an object. Passing this
reference to a method, the parameter that receives it will refer to the same object as that
referred to by the argument.
This effectively means that objects are passed to methods by use of call-by-reference.
Changes made to the object inside the method do affect the object used as an argument.
Example: // Call-by-reference mechanism.
class Test {
int a, b;
Test(int i, int j) {
a = i;
b = j;
}
void meth(Test o) {
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);
}
}
Output:
ARRAYS
An array is a group of like-typed variables that are referred to by a common name.
Arrays of any type can be created and may have one or more dimensions.
A specific element in an array is accessed by its index.
Arrays offer a convenient means of grouping related information.
One-Dimensional Arrays
To create an array, you first must create an array variable of the desired type.
The general form of a one-dimensional array declaration is
type var-name[ ];
Here, type declares the base type of the array.
For example: the following declares an array named month_days with the type “array
of int”:
int month_days[];
After this declaration month_days is an array variable with value set to null, which
represents an array with no value.
To link month_days with an actual, physical array of integers, we must allocate one
using new and assign it to month_days.
new is a special operator that allocates memory.
The general form of new to one-dimensional arrays:
array-var = new type[size];
type specifies the type of data being allocated, size specifies the number of elements in
the array, and array-var is the array variable that is linked to the array.
The elements in the array allocated by new will automatically be initialized to zero.
This following example allocates a 12-element array of integers and links them to
month_days.
month_days = new int[12];
After this statement executes, month_days will refer to an array of 12 integers. Further,
all elements in the array will be initialized to zero.
Obtaining an array is a two-step process.
First, you must declare a variable of the desired array type.
Second, you must allocate the memory that will hold the array, using new, and assign it
to the array variable.
Thus, in Java all arrays are dynamically allocated.
Accessing Array Elements
Once you have allocated an array, you can access a specific element in the array by
specifying its index within square brackets.
All array indexes start at zero.
For example: to assigns the value 28 to the second element of month_days.
month_days[1] = 28;
One can combine the declaration of the array variable with the allocation of the array itself,
int month_days[] = new int[12];
If we do the declaration, definition & Initialization all together there is no need to use the
new keyword to allocate the memory.
For example: to store the number of days in each month, the following code creates an
initialized array of integers:
class AutoArray {
public static void main(String args[])
int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31,30, 31 };
Multidimensional Arrays
In Java, multidimensional arrays are actually arrays of arrays.
To declare a multidimensional array variable, specify each additional index using another
set of square brackets.
For example: to declare a two-dimensional array variable called twoD.
int twoD[][] = new int[4][5];
This allocates a 4 by 5 array and assigns it to twoD.
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();
}
}
}
To allocate memory for a multidimensional array, we need to specify the memory only for
the first (leftmost) dimension. We can allocate the remaining dimensions separately.
For example, to allocate memory for the first dimension of twoD. It allocates the second
dimension manually.
int twoD[][] = new int[4][];
twoD[0] = new int[5];
twoD[1] = new int[5];
twoD[2] = new int[5];
twoD[3] = new int[5];
(Ragged Array)For example: to create a two-dimensional array in which the sizes of the
second dimension are unequal.
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];
Example:
class TwoDAgain {
public static 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();
}
}
}
Output:
0
12
345
6789
Three-dimensional array
Let’s look at one more example that uses a multidimensional array.
The following program creates a 3 by 4 by 5, three-dimensional array.
Example: // Demonstrate a three-dimensional array.
class ThreeDMatrix {
public static void main(String args[]) {
int threeD[][][] = new int[3][4][5];
int i, j, k;
for(i=0; i<3; i++)
for(j=0; j<4; j++)
for(k=0; k<5; k++)
threeD[i][j][k] = i * j * k;
for(i=0; i<3; i++) {
for(j=0; j<4; j++) {
for(k=0; k<5; k++)
System.out.print(threeD[i][j][k] + " ");
System.out.println();
}
System.out.println();
}
}
}
Output
00000
00000
00000
00000
00000
01234
02468
0 3 6 9 12
00000
02468
0 4 8 12 16
0 6 12 18 24
Alternative Array Declaration Syntax
There is a second form that may be used to declare an array: type[ ] var-name;
The square brackets follow the type specifier, and not the name of the array variable.
int[] a2 = new int[3]; (SAME) int al[] = new int[3];
char twod1[][] = new char[3][4]; (SAME) char[][] twod2 = new char[3][4];
This alternative declaration is a convenience, when declaring several arrays at the same
time.
int[] nums, nums2, nums3; (SAME) int nums[], nums2[], nums3[];
String Handling
String
In Java,
string is basically an object that represents sequence of char values. An array of characters works
same as Java string. For example:
char[] ch={'j','a',’v’,’A’};
String s=new String(ch);
1. By string literal
2. By new keyword
1) String Literal
2) By new keyword
4 String substring(int beginIndex, int endIndex) It returns substring for given begin
index and end index.
15 String[] split(String regex, int limit) It returns a split string matching regex
and limit.
17 int indexOf(int ch, int fromIndex) It returns the specified char value
index starting with given index.
19 int indexOf(String substring, int fromIndex) It returns the specified substring index
starting with given index.
Java StringBuffer class is used to create mutable (modifiable) String objects. The StringBuffer class in Java
is the same as String class except it is mutable i.e. it can be changed.
A String that can be modified or changed is known as mutable String. StringBuffer and StringBuilder
classes are used for creating mutable strings.
A String that can be modified or changed is known as mutable String. StringBuffer and StringBuilder
classes are used for creating mutable strings.
Method Description
insert(int offset, It is used to insert the specified string with this string at
String s) the specified position. The insert() method is overloaded
like insert(int, char), insert(int, boolean), insert(int, int),
insert(int, float), insert(int, double) etc.
The append() method concatenates the given argument with this String.
StringBufferExample
1. class StringBufferExample{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello ");
4. sb.append("Java");//now original string is changed
5. System.out.println(sb);//prints Hello Java
6. }
7. }
Output:
Hello Java
The insert() method inserts the given String with this string at the given position.
StringBufferExample2.java
1. class StringBufferExample2{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello ");
4. sb.insert(1,"Java");//now original string is changed
5. System.out.println(sb);//prints HJavaello
6. }
7. }
Output: HJavaello
The replace() method replaces the given String from the specified beginIndex and endIndex.
StringBufferExample3.java
1. class StringBufferExample3{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello");
4. sb.replace(1,3,"Java");
5. System.out.println(sb);//prints HJavalo
6. }
7. }
Output: Hjavalo
The delete() method of the StringBuffer class deletes the String from the specified beginIndex to endIndex.
StringBufferExample4.java
1. class StringBufferExample4{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello");
4. sb.delete(1,3);
5. System.out.println(sb);//prints Hlo
6. }
7. }
Output: Hlo
The reverse() method of the StringBuilder class reverses the current String.
StringBufferExample5.java
1. class StringBufferExample5{
2. public static void main(String args[]){
3. StringBuffer sb=new StringBuffer("Hello");
4. sb.reverse();
5. System.out.println(sb);//prints olleH
6. }
7. }
Output:olleH
STRING BUILDER
Java StringBuilder class is used to create mutable (modifiable) String. The Java StringBuilder class is same
as StringBuffer class except that it is non-synchronized. It is available since JDK 1.5.
Method Description
public StringBuilder It is used to append the specified string with this string. The
append(String s) append() method is overloaded like append(char),
append(boolean), append(int), append(float), append(double) etc.
public StringBuilder insert(int It is used to insert the specified string with this string at the
offset, String s) specified position. The insert() method is overloaded like insert(int,
char), insert(int, boolean), insert(int, int), insert(int, float),
insert(int, double) etc.
public StringBuilder replace(int It is used to replace the string from specified startIndex and
startIndex, int endIndex, String endIndex.
str)
public StringBuilder delete(int It is used to delete the string from specified startIndex and
startIndex, int endIndex) endIndex.
public StringBuilder reverse() It is used to reverse the string.
public void ensureCapacity(int It is used to ensure the capacity at least equal to the given
minimumCapacity) minimum.
public char charAt(int index) It is used to return the character at the specified position.
public int length() It is used to return the length of the string i.e. total number of
characters.
public String substring(int It is used to return the substring from the specified beginIndex.
beginIndex)
public String substring(int It is used to return the substring from the specified beginIndex and
beginIndex, int endIndex) endIndex.
The StringBuilder append() method concatenates the given argument with this String.
StringBuilderExample.java
1. class StringBuilderExample{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello ");
4. sb.append("Java");
5. System.out.println(sb);
6. }
7. }
The StringBuilder insert() method inserts the given string with this string at the given position.
StringBuilderExample2.java
1. class StringBuilderExample2{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello ");
4. sb.insert(1,"Java");
5. System.out.println(sb);
6. }
7. }
OUTPUT: HJavaello
The StringBuilder replace() method replaces the given string from the specified beginIndex and endIndex.
StringBuilderExample3.java
1. class StringBuilderExample3{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello");
4. sb.replace(1,3,"Java");
5. System.out.println(sb);
6. }
7. }
Output: HJavalo
The delete() method of StringBuilder class deletes the string from the specified beginIndex to endIndex.
StringBuilderExample4.java
1. class StringBuilderExample4{
2. public static void main(String args[]){
3. StringBuilder sb=new StringBuilder("Hello");
4. sb.delete(1,3);
5. System.out.println(sb);
6. }
7. }
Output: Hlo
StringBuilderExample5.java
class StringBuilderExample5{
public static void main(String args[]){
StringBuilder sb=new StringBuilder("Hello");
sb.reverse();
System.out.println(sb);
}
}
Output: olleH
Java provides three classes to represent a sequence of characters: String, StringBuffer, and StringBuilder.
The String class is an immutable class whereas StringBuffer and StringBuilder classes are mutable. There
are many differences between StringBuffer and StringBuilder. The StringBuilder class is introduced since
JDK 1.5.
3) StringBuffer was introduced in Java 1.0 StringBuilder was introduced in Java 1.5
StringBuffer Example
Output: hellojava
StringBuilder Example
BuilderTest.java
//Java Program to demonstrate the use of StringBuilder class.
public class BuilderTest{
public static void main(String[] args){
StringBuilder builder=new StringBuilder("hello");
builder.append("java");
System.out.println(builder);
}
}
Output:
hellojava