Chapter 2 (Java Basics)
Chapter 2 (Java Basics)
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
-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.");
}
-8-
Overview of the Java Language
-9-
Overview of the Java Language
- 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
- 12 -
Overview of the Java Language
- 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
- 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
- 15 -
Overview of the Java Language
- 16 -
Overview of the Java Language
- 17 -
Overview of the Java Language
- 18 -
Overview of the Java Language
- 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
- 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)
- 24 -
Overview of the Java Language
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.
- 25 -
Overview of the Java Language
- 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
- 27 -