You are on page 1of 27

Overview of the Java Language

Chapter 2
Basics in Java Programming
This chapter outlines the core syntax and constructs of the Java language. You will learn
how to declare Java variables
2.1. Structure of java Program
Java is a pure object oriented language, and hence everything is written within a class
block.

[Documentation]
[package statement]
[import statement(s)]
[interface statement]
[class definition]
main method class definition
In the Java
language, the simplest form of a class definition is
class name
{
...
}
The keyword class begins the class definition for a class named name. The variables and
methods of the class are embraced by the curly brackets that begin and end the class
definition block. The "Hello World" application has no variables and has a single method
named main.
2.2. Creating, Compiling and Running a Java Program
To create java program, you will:
 Create a source file. A source file contains text, written in the Java programming
language, that you and other programmers can understand. You can use any text
editor to create and edit source files.
 Compile the source file into a bytecode file. The compiler, javac, takes your
source file and translates its text into instructions that the Java Virtual Machine
(Java VM) can understand. The compiler converts these instructions into a
bytecode file.

-1-
Overview of the Java Language

 Run the program contained in the bytecode file. The Java interpreter installed
on your computer implements the Java VM. This interpreter takes your bytecode
file and carries out the instructions by translating them into instructions that your
computer can understand.
Note:
 Class name must be the same as the file name where the class lives. Eg. A class
named MyFirstClass has to be in the file called MyFirstClass.java.
 A program can contain one or more class definitions but only one public class
definition.
 The program can be created in any text editor.
 If a file contains multiple classes, the file name must be the class name of the
class that contains the main method.
Example:
class Test1{
public static void main(String args[]){
System.out.println(“My First Java Program”);
}
}
Note: we are using the System and String class directly, because they are found in the
package java.lang in which it is automatically included in any java program.
public (access modifier) makes the item visible from outside the class. static
indicates that the main() method is a class method not an instant method. It allows
main() to be called without having to instantiate a particular instance of the class.
 Compiling from the command prompt
C:\>path=”C:\tc\bin”
javac Test1.java
A file called Test1.class will created (Bytecode)
 Running the program
C:\>java Test1
Output: My First Java Program

-2-
Overview of the Java Language

2.3. Lexical Components of Java Tokens


Java program = Comments + Token(s) + white space
2.3.1. Comments
Java supports three types of comment delimiters.
The /* and */ delimiters are used to enclose text that is to be treated as a comment by the
compiler. These delimiters are useful when you want to designate a lengthy piece of code
as a comment, as shown in the following:
/* This is a comment that will span multiple source code lines. */
The // comment delimiter is borrowed from C++ and is used to indicate that the rest of
the line is to be treated as a comment by the Java compiler. This type of comment
delimiter is particularly useful for adding comments adjacent to lines of code, as shown
in the following:
Date today = new Date(); // create an object with today's date
System.out.println(today); // display the date
Finally, the /** and */ delimiters are new to Java and are used to indicate that the
enclosed text is to be treated as a comment by the compiler, but that the text is
also part of the automatic class documentation that can be generated using
JavaDoc.
The Java comment delimiters are summarized in Table 2.1.
Table 2.1. Java comment delimiters.

Start End Purpose


/* */ The enclosed text is treated as a comment.
// (none) The rest of the line is treated as a comment.
/** */ The enclosed text is treated as a comment by the
compiler but is used by JavaDoc to automatically
generate documentation.

2.3.2. Atomic elements of java (Tokens)

-3-
Overview of the Java Language

- Token is the smaller individual units inside a program the compiler recognizes when
building up the program. There are five types of Tokens in Java: Reserved keywords,
Identifiers, Literals, operators, separators.
1. Reserved keywords
- Are words with special meaning to the compiler (eg. Class, new, static, import, this
etc…). You have to be able to identify all Java programming language keywords and
correctly constructed identifiers. Some are not used but are reserved for further use.
(Ex.: const, goto)
Java Keywords
abstract float public
boolean for return
Break if short
Byte implements static
Case import super
Catch instanceof switch
Char int synchronized
Class interface this
continue long throw
default native throws
Do new transient
double null try
Else operator void
extends package volatile
Final private while
finally protected

2. Identifiers

-4-
Overview of the Java Language

- Identifiers are programmer given names used to identify classes, methods, variables,
objects, packages. Java is case sensitive language. For example, Mathvar, mathVar,
MathVar, etc are different identifiers.
 Identifier Rules:
 Must begin with
 Letters
 Underscore characters (_) or Any currency symbol (e.g $)
 Remaining characters
 Letters
 Digits
 As long as you like!! (until you are tired of typing)
- Identifiers’ naming conventions
 Class names: starts with cap letter and should be inter-cap
 Variable names: start with lower case and should be inter-cap
 Method names: start with lower case and should be inter-cap
 Constants: often written in all capital and use underscore if you are using more
than one word.
3. Literals
- Literals are constant values
- Can be digits, letters or others that represent constant value to be stored in variables.
- Examples:
55, 2.2, 2.99f, “Hello”.
- Literals are used to create values that are:
 Assigned to variables
 Used in expressions
 Passed to methods
- Java creates anonymous reference for string literals
- Only one object is created for every literal containing the same data.

4. Operators

-5-
Overview of the Java Language

- Are symbols that take one or more arguments (operands) and operates on them to
produce a result.
5. Separators
- Are symbols used to indicate where groups of codes are divided and arranged.
- They basically define the shape and function of our code.
- Some of them are:
Name Symbol Description
Parenthesis ()
braces {}
brackets []
semicolon ;
comma , ,
period .

White space
- Java is free form language
- White space is space, tab, newline.
2.4. Java Program Expression and Statements
- Variables and operators, which discussed before, are basic building blocks of
programs. You combine literals, variables, and operators to form expressions.
- Expression is segments of code that perform computations and return values.
- Certain expressions can be made into statements-complete units of execution.
- By grouping statements together with curly braces { and }, you create blocks of code.
Expressions
- An expression is a series of variables, operators, and method calls (constructed
according to the syntax of the language) that evaluates to a single value.
- Expressions perform the work of a program.
- Among other things, expressions are used to compute and to assign values to
variables and to help control the execution flow of a program.
- The job of an expression is twofold: to perform the computation indicated by the
elements of the expression and to return a value that is the result of the computation.

-6-
Overview of the Java Language

Statements
- Statements are roughly equivalent to sentences in natural languages.
- A statement forms a complete unit of execution.
- There are three kinds of statements:
o expression statements
o declaration statements
o control flow statements
- The following types of expressions can be made into a statement by terminating the
expression with a semicolon (;):
o Null statments
o Assignment expressions
o Any use of ++ or --
o Method calls
o Object creation expressions
- These kinds of statements are called expression statements.
- Here are some examples of expression statements:
aValue = 8933.234; //assignment statement
aValue++; //increment statement
System.out.println(aValue); //method call statement
Integer integerObject = new Integer(4); //object creation
- In addition to these kinds of expression statements, there are two other kinds of
statements. A declaration statement declares a variable. You've seen many examples
of declaration statements.
double aValue = 8933.234; // declaration statement
- A control flow statement regulates the order in which statements get executed. The
for loop and the if statement are both examples of control flow statements.
Blocks
A block is a group of zero or more statements between balanced braces and can be used
anywhere a single statement is allowed.

if (Character.isUpperCase(aChar)) {
System.out.println("The character " + aChar + " is upper case.");

-7-
Overview of the Java Language

} else {
System.out.println("The character " + aChar + " is lower case.");
}

2.5. Variables and Data Types


An object stores its state in variables. A variable is an item of data named by an
identifier. You must explicitly provide a name and a type for each variable you want to
use in your program. The variable's name must be a legal identifier
You use the variable name to refer to the data that the variable contains. The variable's
type determines what values it can hold and what operations can be performed on it. To
give a variable a type and a name, you write a variable declaration, which generally looks
like this:
type name
In addition to the name and type that you explicitly give a variable, a variable has scope.
The section of code where the variable's simple name can be used is the variable's scope.
The variable's scope is determined implicitly by the location of the variable declaration,
that is, where the declaration appears in relation to other code elements.
- There are three kinds of variables in Java.
1. Instance variables: variables that hold data for an instance of a class.
2. Class variables: variables that hold data that will be shard among all instances of
a class.
3. Local variables: variables that pertain only to a block of code.
Note:
 We can not use variables with out initializing them in Java.
 Class numeric variables are initialized to zero and Boolean variables are
initialized to false if you do not initialize them, where as local variables will not
be initialized.
Data Types
Java has two basic data types
1. Primitive types
2. Reference types
Primitive Data Types

-8-
Overview of the Java Language

-are eight in number


Note:
 Boolean type has a value true or false (there is no conversion b/n Boolean and
other types).
 All non-primitive types are reference types, so all class types are reference types.
Programs use variables of reference types (normally called references) to refer to
objects in the program.
 All integers in Java are signed, Java doesn‟t support unsigned integers.
Reference types

Keyword Description Size/Format


(integers)
byte Byte-length integer 8-bit two's complement
short Short integer 16-bit two's complement
int Integer 32-bit two's complement
long Long integer 64-bit two's complement
(real numbers)
float Single-precision floating point 32-bit IEEE 754
double Double-precision floating point 64-bit IEEE 754
(other types)
char A single character 16-bit Unicode character
boolean A boolean value (true or false) true or false
- Arrays, classes, and interfaces are reference types.
- The value of a reference type variable, in contrast to that of a primitive type, is a
reference to (an address of) the value or set of values represented by the variable.
- A reference is called a pointer or a memory address in other languages.
- The Java programming language does not support the explicit use of addresses like
other languages do. You use the variable's name instead.

-9-
Overview of the Java Language

2.6. Type casting


1. Automatic type casting
Java supports automatic widening. Widening conversion for primitive, which is a
kind of conversion from one type to another which doesn‟t lose information.
double
float
Long
Char int
Short
Byte

- Two conditions for automatic casting


o Types are compatible
o Destination is wider than the source
- Numeric types, i.e integers and floating point types are compatible to each other.
- Widening conversion usually occur automatically.
Example:
float f = 9.0; //error 9 is a double literal
float f = 9; //correct
2. Explicit type casting
- When ever you need to narrow or go in the other direction, Java won‟t do that
automatically.
- You have to do that programmatically.
Syntax:
(<dest-type>)<var_Idf or value>
Example:
float f =3.5f;
f = (float)2.9;
float x=98;
byte b=2;
float y=x+b;

- 10 -
Overview of the Java Language

b = (byte)y;
int x = (int)2.7;
2.7. Scope and Lifetime of variables
- A variable's scope is the region of a program within which the variable can be
referred to by its simple name.
- Secondarily, scope also determines when the system creates and destroys memory for
the variable.
- Scope is distinct from visibility, which applies only to member variables and
determines whether the variable can be used from outside of the class within which it
is declared.
- Visibility is set with an access modifier.
- A block defines a scope. Each time you create a block of code, you are creating a
new, nested scope.
- Objects declared in the outer block will be visible to code within the inner block
down from the declaration. (The reverse is not true)
- Variables are created when their scope is entered, and destroyed when their scope is
left. This means that a variable will not hold its value once it has gone out of scope.
- Variable declared within a block will lose its value when the block is left. Thus, the
lifetime of a variable is confined to its scope.
- You can‟t declare a variable in an inner block to have the same name as the one up in
an outer block.
- But it is possible to declare a variable down out down outside the inner block using
the same name.
2.8. Operators
- An operator performs a function on one, two, or three operands.
- An operator that requires one operand is called a unary operator.
- The unary operators support either prefix or postfix notation.
- Prefix notation means that the operator appears before its operand
operator op //prefix notation
- Postfix notation means that the operator appears after its operand
op operator //postfix notation

- 11 -
Overview of the Java Language

- An operator that requires two operands is a binary operator.


- All of the binary operators use infix notation, which means that the operator appears
between its operands:
op1 operator op2 //infix notation
- And finally, a ternary operator is one that requires three operands.
- The Java programming language has one ternary operator, ?:, which is a short-hand
if-else statement.
- The ternary operator is also infix; each component of the operator appears between
operands
op1 ? op2 : op3 //infix notation
- In addition to performing the operation, an operator returns a value.
- The return value and its type depend on the operator and the type of its operands.
- The data type returned by an arithmetic operator depends on the type of its operands:
If you add two integers, you get an integer back. An operation is said to evaluate to
its result.
- The following table lists the basic arithmetic operators provided by the Java
programming language. Except for +, which is also used to concatenate strings, these
operators can be used only on numeric values.
Operator Use Description
+ op1 + op2 Adds op1 and op2
- op1 - op2 Subtracts op2 from op1
* op1 * op2 Multiplies op1 by op2
/ op1 / op2 Divides op1 by op2
% op1 % op2 Computes the remainder of dividing op1 by op2

- These short cut operators increment or decrement a number by one.


Operator Use Description
++ op++ Increments op by 1; evaluates to the value of op before it was
incremented
++ ++op Increments op by 1; evaluates to the value of op after it was
incremented

- 12 -
Overview of the Java Language

-- op-- Decrements op by 1; evaluates to the value of op before it was


decremented
-- --op Decrements op by 1; evaluates to the value of op after it was
decremented

- Here is the Java programming language's other arithmetic operators.


Operator Use Description
+ +op Promotes op to int if it's a byte, short, or char
- -op Arithmetically negates op
Relational and Conditional Operators
- Use these relational operators to determine the relationship between two values.
Operator Use Returns true if
> op1 > op2 op1 is greater than op2
>= op1 >= op2 op1 is greater than or equal to op2
< op1 < op2 op1 is less than op2
<= op1 <= op2 op1 is less than or equal to op2
== op1 == op2 op1 and op2 are equal
!= op1 != op2 op1 and op2 are not equal

- You can use the following conditional operators to form multi-part decisions.
Operator Use Returns true if
&& op1 && op1 and op2 are both true, conditionally evaluates op2
op2
|| op1 || op2 either op1 or op2 is true, conditionally evaluates op2
! ! op op is false
& op1 & op1 and op2 are both true, always evaluates op1 and op2
op2
| op1 | op2 either op1 or op2 is true, always evaluates op1 and op2
^ op1 ^ op2 if op1 and op2 are different--that is if one or the other of the
operands is true but not both

- 13 -
Overview of the Java Language

Shift and Logical Operators


- Each shift operator shifts the bits of the left-hand operand over by the number of
positions indicated by the right-hand operand.
- The shift occurs in the direction indicated by the operator itself.
Operator Use Operation
>> op1 >> op2 shift bits of op1 right by distance op2
<< op1 << op2 shift bits of op1 left by distance op2
>>> op1 >>> op2 shift bits of op1 right by distance op2 (unsigned)
- These operators perform logical functions on their operands.
Operator Use Operation
& op1 & op2 bitwise and
| op1 | op2 bitwise or
^ op1 ^ op2 bitwise xor
~ ~op2 bitwise complement
Assignment Operators
- The basic assignment operator looks as follows and assigns the value of op2 to op1.
op1 = op2;
- In addition to the basic assignment operation, the Java programming language defines
these short cut assignment operators that perform an operation and an assignment
using one operator.
Operator Use Equivalent to
+= op1 += op2 op1 = op1 + op2
-= op1 -= op2 op1 = op1 - op2
*= op1 *= op2 op1 = op1 * op2
/= op1 /= op2 op1 = op1 / op2
%= op1 %= op2 op1 = op1 % op2
&= op1 &= op2 op1 = op1 & op2
|= op1 |= op2 op1 = op1 | op2
^= op1 ^= op2 op1 = op1 ^ op2
<<= op1 <<= op2 op1 = op1 << op2
>>= op1 >>= op2 op1 = op1 >> op2
>>>= op1 >>>= op2 op1 = op1 >>> op2

- 14 -
Overview of the Java Language

Other Operators
- The Java programming language also supports these operators.
Operator Use Description
?: op1 ? op2 : If op1 is true, returns op2. Otherwise, returns op3.
op3
[] type [] Declares an array of unknown length, which contains type
elements.
[] type[ op1 ] Creates and array with op1 elements. Must be used with the
new operator.
[] op1[ op2 ] Accesses the element at op2 index within the array op1. Indices
begin at 0 and extend through the length of the array minus
one.
. op1.op2 Is a reference to the op2 member of op1.
() op1(params) Declares or calls the method named op1 with the specified
parameters. The list of parameters can be an empty list. The
list is comma-separated.
(type) (type) op1 Casts (converts) op1 to type. An exception will be thrown if
the type of op1 is incompatible with type.
new new op1 Creates a new object or array. op1 is either a call to a
constructor, or an array specification.
instanceof op1 instanceof Returns true if op1 is an instance of op2
op2

2.9. Control Flow Statements


- The Java programming language provides several control flow statements, which are
listed in the following table.
Statement Type Keyword
looping while, do-while , for

decision making if-else, switch-case

exception handling try-catch-finally, throw


branching break, continue, label:, return

- 15 -
Overview of the Java Language

- The general form of a control flow statement is


control flow statement details
{
statement(s)
}
- Technically, the braces, { and }, are not required if the block contains only one
statement. However, I recommend that you always use { and }, because the code is
easier to read and it helps to prevent errors when modifying code.
2.10. Arrays
- An array is a structure that holds multiple values of the same type.
- The length of an array is established when the array is created (at runtime).
- After creation, an array is a fixed-length structure.
- An array element is one of the values within an array and is accessed by its position
within the array.
- If you want to store data of different types in a single structure, or if you need a
structure whose size can change dynamically, use a Collection implementation, such
as Vector, instead of an array.
- Unlike C++ in Java arrays are created dynamically.
- Array elements can be:
 Primitive types
 References to objects
- You need to understand that there are three steps for using arrays in Java.
 Declare arrays
 Create arrays
 Initialize the array
1. Declaring an Array
String studentName[];
or
String []studentName;
String studentName[][];

- 16 -
Overview of the Java Language

- In these cases no memory space is allocated.


2. Creating an array
StudentName = new String[10];
int x[] = new int[100];
- When creating an array, each element of the array receives a default value zero (for
numeric types) ,false for boolean and null for references (any non primitive types).
3. Array Initializing
int x[]={2,3,5,7};
- All array indices must be greater than or equal to zero and less than the length of the
array. If there is an invalid index, Java generates an exception (i.e
ArrayIndexOutOfBoundsException).
- The Java interpreter checks array indices to ensure that they are valid during
execution.
- Be careful when looping through an array.
- Limitations of Arrays in C++
1. No bound checking (overflow) or no array index checking.
2. Array coping is not possible using the assignment statement.
Example: Creating and coping arrays
Public class ArrayCopy{
public static void main(String args[])
{ int copyArray[];
int originalArray = {10, 20, 30, 40, 50};
copyArray = originalArray;
copyArray[0] = 0;
for(int i = 0; i<originalArray.length; i++)
System.out.print(originalArray[i]+” “);
}
}
The output is: 0 20 30 40 50

- 17 -
Overview of the Java Language

Two dimensional arrays


- A multidimensional array with the same number of columns in every row can be
created with an array creation expression.
int b[][];
b = new int[3][4];
- A multidimensional array in which each row has a different number of columns can
be created as follows.
int b[][];
b = new int[2][];
b[0] = new int[5];
b[1] = new int[3];
using array initializer
int arr1[][] = {{1,2,3}, {4,5,6}};
int srr2[][] = {{1}, {1,2}, {1,2,3}, {1,2}};

- 18 -
Overview of the Java Language

2.11. Characters and Strings


The Java platform contains three classes that you can use when working with character
data:
 Character: - A classes whose instances can hold a single character value.
This class also defines handy methods that can manipulate or inspect
single-character data.
 String:- A class for working with immutable (unchanging) data composed
of multiple characters.
 StringBuffer:- A class for storing and manipulating mutable data
composed of multiple characters.
Characters
- An object of Character type contains a single character value.
- You use a Character object instead of a primitive char variable when an object is
required-for example, when passing a character value into a method that changes the
value or when placing a character value into a data structure, such as a vector, that
requires objects.
- The following sample program, CharacterDemo, creates a few character objects and
displays some information about them.
public class CharacterDemo {
public static void main(String args[]) {
Character a = new Character('a');
Character a2 = new Character('a');
Character b = new Character('b');
int difference = a.compareTo(b);
if (difference == 0) {
System.out.println("a is equal to b.");
}
else if (difference <0) {="{"
System.out.println("a="System.out.println("a" is="is" less="less"
than="than" b.");="b.");" }="}" else="else" if="if"
(difference="(difference"> 0) {
System.out.println("a is greater than b.");

- 19 -
Overview of the Java Language

}
System.out.println("a is " + ((a.equals(a2)) ? "equal" : "not equal") + " to a2.");
System.out.println("The character " + a.toString() + " is "
+ (Character.isUpperCase(a.charValue()) ? "upper" : "lower") + "case.");
}
}
The following is the output from this program:
a is less than b.
a is equal to a2.
The character a is lowercase.
Character(char)
The Character class's only constructor, which creates a Character object containing
the value provided by the argument. Once a Character object has been created, the
value it contains cannot be changed.
compareTo(Character)
An instance method that compares the values held by two character objects: the
object on which the method is called (a in the example) and the argument to the
method (b in the example). This method returns an integer indicating whether the
value in the current object is greater than, equal to, or less than the value held by
the argument. A letter is greater than another letter if its numeric value is greater.
equals(Object)
An instance method that compares the value held by the current object with the
value held by another. This method returns true if the values held by both objects
are equal.
toString()
An instance method that converts the object to a string. The resulting string is one
character in length and contains the value held by the character object.
charValue()
An instance method that returns the value held by the character object as a
primitive char value.
isUpperCase(char)
A class method that determines whether a primitive char value is uppercase. This
is one of many Character class methods that inspect or manipulate character data.

- 20 -
Overview of the Java Language

- The Java platform provides two classes, String and StringBuffer, that store and
manipulate strings-character data consisting of more than one character.
- The String class provides for strings whose value will not change. For example, if you
write a method that requires string data and the method is not going to modify the
string in any way, pass a String object into the method.
- The StringBuffer class provides for strings that will be modified; you use string buffers
when you know that the value of the character data will change.
- You typically use string buffers for constructing character data dynamically: for
example, when reading text data from a file. Because strings are constants, they are
more efficient to use than are string buffers and can be shared. So it's important to use
strings when you can.
- Following is a sample program called StringsDemo, which reverses the characters of a
string. This program uses both a string and a string buffer.
public class StringsDemo {
public static void main(String[] args) {
String palindrome = "Dot saw I was Tod";
int len = palindrome.length();
StringBuffer dest = new StringBuffer(len);
for (int i = (len - 1); i >= 0; i--) {
dest.append(palindrome.charAt(i));
}
System.out.println(dest.toString());
}
}
- The output from this program is:
doT saw I was toD
Creating Strings and StringBuffers
- A string is often created from a string literal--a series of characters enclosed in double
quotes. For example, when it encounters the following string literal, the Java platform
creates a String object whose value is Gobbledygook. "Gobbledygook"
- The StringsDemo program uses this technique to create the string referred to by the
palindrome variable:
String palindrome = "Dot saw I was Tod";

- 21 -
Overview of the Java Language

- You can also create String objects as you would any other Java object: using the new
keyword and a constructor.
- The String class provides several constructors that allow you to provide the initial
value of the string, using different sources, such as an array of characters, an array of
bytes, or a string buffer.
- Here's an example of creating a string from a character array:
char[] helloArray = { 'h', 'e', 'l', 'l', 'o' };
String helloString = new String(helloArray);
System.out.println(helloString);
- The last line of this code snippet displays: hello.
- You must always use new to create a string buffer. The StringsDemo program creates
the string buffer referred to by dest, using the constructor that sets the buffer's
capacity:
String palindrome = "Dot saw I was Tod";
int len = palindrome.length();
StringBuffer dest = new StringBuffer(len);
- This code creates the string buffer with an initial capacity equal to the length of the
string referred to by the name palindrome. This ensures only one memory allocation
for dest because it's just big enough to contain the characters that will be copied to it.
- By initializing the string buffer's capacity to a reasonable first guess, you minimize
the number of times memory must be allocated for it. This makes your code more
efficient because memory allocation is a relatively expensive operation.
- String in Java is not primitive type but a class.
- A String class is included in java.lang package.
- Anything in java.lang package is automatically included in your Java program.
Method or Constructor Purpose
String()
String (byte[])
String (byte[], int, int) Creates a new string object. For all
String (byte[], int, int, String) constructors that take arguments, the first
String (byte[], String) argument provides the value for the string.
String (char[])
String (char[], int, int)

- 22 -
Overview of the Java Language

String (String)
String (StringBuffer)

Creating String
String name = “”;
String s = “hello”;
String myText = “This is a longer string.”;
String name = new String(“Kebede”);
- Strings are immutable. In fact all wrapper objects are immutable. What that means is
that once assigned their values can not be changed. It might appear that they can.
- Let us have a look to the following example.
class String Test{
public static void main(String args[]){
String name = “Kebede”;
System.out.println(name);
name = name + “Tollosa”;
System.out.println(name);
}
}
OutPut: Kebede
Kebede Tollosa

Memory

name Kebede

Kebede Tollosa

- Objects are automatically cleaned up when no longer referenced.

- 23 -
Overview of the Java Language

- String methods length, charAt, getChars determine the length of a string, obtain the
character a specific location in a string and retrieve the entire set of characters in a
string respectively.
Example: string s = “hello”;
int size = s.length(); //size = 5
char ch = charAt(0); //ch = „h‟
char charArray[] = new char[4];
s.getChars(0, 4, charArray, 0);
 first argu.: starting index string object to be copied.
 Second argu.: no of chars to be copied
 Third argu.: starting index in charArray.
Comparing Strings
- When references are compared using ==, the result is true if both references
refer to the same object in memory. When comparing objects to determine
whether thy have the same contents, use the method „equals‟ defined in the
String class.
- If you are comparing two String types for equality use the method
„equalsIgnoreCase‟., which ignores the case of letters when comparing. Thus
String “hello” and the String “Hello” compares as equal Strings.
- CompareTo returns 0 if the Strings are equal, a negative number if the String
object that invokes „compareTo‟ method is greater than the String that is
passed as an argument and positive otherwise.
String s1 = “Hello”;
String s2 = “Hello”;
- In order to save memory Java compiler creates only a new reference. So s1 =
s2 is true, not for the reason you think.

s1(reference) s2(reference)

String s1 = new String(“Hello”);


Hello

- 24 -
Overview of the Java Language

String s2 = new String(“Hello”);


- In this case we are explicitly controlling the creation of new object.

s1(reference) s1(reference)

Hello Hello

s1 = s2, the equal sign doesn‟t look at the values of the objects. In order to
compare the values of the objects, we use “equals()” method.
equals() method
- Compares content of wrapper objects.
- Object types must be the same.
== returns true for objects.
- when the reference point to the same object.
- The object values are NOT compared.
- Other methods in String Wrapper class
Example: Consider the following declaration
String str = “Hello”;
 Str.indexOf(„h‟); //returns the index of the character „c‟ if it finds, otherwise -1.

 Str.indexOf(„h‟,1); //the second argument is the starting index at which the search should begin.
 str.lastIndexOf(„l‟[,2]); //To locate the last occurrence of the character in the string str.
 s1.concat(s2); //returns the concatenated string.
Extracting a string
 String str = “Hello”;
 str.replace(„l‟,‟L‟); //returns a new string object
 str.substring(2); //returns the sub string starting from index 2.

 Str.substring(2,7); //the second argument is the last index-

 str.toUpperCase(); //returns a new string object


 str.toLowerCase(); //returns a new string object
 str.trim(); //returns a new string object containing the string without leading and/or trialing white spaces.

- 25 -
Overview of the Java Language

 Char charArray[] = str.toCharArray();//creates a new character array containing a copy of

characters in str and assigns a reference to variable charArray.

- Every object in Java has a toString method that enables a program to obtain the
objects string representation. This technique can not be used with primitive
types.
- valueOf(…) method takes an argument of any type and converts the argument
to a string object.
Eg. int x = 6;
String s = String.valueOf(x);
- String objects are constant strings, where as StringBuffer objects are
modifiable strings.
StringBuffer buffer = new StringBuffer(“Hello there”);
buffer.toString();
buffer.charAt(0);
buffer.getChars(0, buffer.length(), charArray, 0);
buffer.append(objref);
buffer.append(“String literal”);
buffer.append(bool value);
String s=buffer.toString();
Buffer.setCharAt(0, „h‟)
- Wrapper classes enable primitive type values to be treated as objects.
Character Class
 Character.isDigit(ch);
 Character.isLetter(ch);
 Character.isLetterOrDigit(ch);
 Character.isLowerCase(ch);
 Character.isUpperCase(ch);
 Character.toUpperCase(ch);
 Character.toLowerCase(ch);

- 26 -
Overview of the Java Language

 Character.isJavaIdentifierStart(ch);
Wrapper classes
- Wrapper class contained in java.lang package
- Used to convert primitive data types into object types
Simple Type Wrapper class
Boolean Boolean
Char Character
Double Double
Float Float
Int Integer
Long Long

- To convert primitive number to objectNumber class use constructor methods.


Integer intobj =new Integer(intval)
- To convert object number to primitive number use typeValue() method.
float f= FloatObj.floatValue();
int i= IntObj.intValue();
- To convert number to string use toString method()
Str =Integer.toString(i);
Str =Float.toString(f);
- String objects can be converted to numeric object using static method
valueOf().
intObj= Integer.value(Str);
- One can convert numeric string to primitive number usoing parsing methods
int i = Integer.parser.parseInt(str);
Through exception
long l=Long.parseLong(str) ;

- 27 -

You might also like