Java Notes Unit2
Java Notes Unit2
Java Notes Unit2
Learning Objectives:
(Java basics: History of Java, Java buzzwords, data types, variables, scope and life time of variables,
arrays, operators, expressions, control statements, type conversion and costing, simple java program,
classes and objects concepts of classes, objects, constructors, methods, access control, this keyword,
garbage collection, overloading methods and constructors, parameter passing, recursion, nested and
inner classes, exploring string class.)
1. The JVM uses a verifier on each class at runtime to verify that it has the correct structure
2. The JVM checks certain runtime operations, such as pointer and array access, to make sure they are
touching only the memory they should. Memory is managed
Automatically by the garbage collector (GC). This prevents the common buffer overflow security
problems suffered by C++ code. This also makes it easy to find many common bugs, since they are
caught by the runtime checker.
3. The Security Manager can check which operations a particular piece of code is allowed to do at
runtime.
Architecture Neutral / Portable
Java is designed to Write Once Run Anywhere, and for the most part this works. Not even a
recompile is required a Java executable can work, without change, on any Java enabled platform.
High-performance
Java performance has gotten a lot better with aggressive just-in-time-compiler (JIT) techniques (the
HotSpot project). Java performance is often similar to the speed of C , and is faster than C in some
cases. However memory use and startup time are both significantly worse than C.
Multi-Threaded
Java has a notion of concurrency (running multiple programs or threads of execution at the same time)
wired right in to the language itself. This works out more cleanly than languages where concurrency is
bolted on after the fact.
Dynamic
Class and type information is kept around at runtime. This enables runtime loading and inspection of
code in a very flexible way.
Data Types:
Java programming language is a language in which all the variables must be declared first and then to
be used. That means to specify the name and the type of the variable. This specifies that Java is a
strongly-typed programming language. Like
Integer
Java defines four integer types :byte, short, int and long. All of these are signed, positive and negative
values.
The width and ranges of these integer type vary widely, as shown in this table:
Name
Width
Range
long
64
-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
int
32
-2,147,483,648 to 2,147,483,647
short
16
-32,768 to 32,767
byte
8
-128 to 127
Declaration of Integer types
long price;
int num;
short qty;
byte bt;
Floating - Point Types
Floating-point numbers, also known as real numbers, are used when evaluating expressions that require
fractional precision. Their width and range shown here:
Name
Width
Range
double
64
1.7e-308 to 1.7e+308
float
32
3.4e-038 to 3.4+038
Declaration of floating-point types
double price;
float salary;
Character
In Java, the data type used to store character is char. In Java, char is a 16-bit type. The range of char is
0 to 65536.
Declaration of character types
char ch;
Boolean
Java has a simple type, called boolean, for logical value. It can have only two possible
values, true or false.
Declaration of boolean types
boolean b;
A sample code using different data types:
When we declare a field it is not always essential that we initialize it too. The compiler sets a default
value to the fields which are not initialized which might be zero or null. However this is not
recommended.
Variables:
A variable refers to the memory location that holds values like: numbers, texts etc. in the computer
memory. A variable is a name of location where the data is stored when a program executes.
The Java contains the following types of variables:
1. Instance Variables (Non-static fields): In object oriented programming, objects store their
individual states in the "non-static fields" that is declared without the static keyword. Each
object of the class has its own set of values for these non-static variables so we can say that
these are related to objects (instances of the class).Hence these variables are also known
as instance variables. These variables take default values if not initialized.
2. Class Variables (Static fields): These are collectively related to a class and none of the object
can claim them its sole-proprietor . The variables defined with static keyword are shared by all
objects. Here Objects do not store an individual value but they are forced to share it among
themselves. These variables are declared as "static fields" using the static keyword. Always
the same set of values is shared among different objects of the same class. So these variables are
like global variables which are same for all objects of the class. These variables take default
values if not initialized.
3. Local Variables: The variables defined in a method or block of code is called local variables.
These variables can be accessed within a method or block of code only. These variables don't
take default values if not initialized. These values are required to be initialized before using
them.
4. Parameters: Parameters or arguments are variables used in method declarations.
Declaring and defining variables
Before using variables you must declare the variables name and type. See the following example for
variables declaration:
int num; //represents that num is a variable that can store value of int type.
String name; //represents that name is a variable that can store string value.
boolean bol; //represents that bol is a variable that can take boolean value (true/false);
You can assign a value to a variable at the declaration time by using an assignment operator ( = ).
int num = 1000; // This line declares num as an int variable which holds value "1000".
boolean bol = true; // This line declares bol as boolean variable which is set to the value "true".
Literals
By literal we mean any number, text, or other information that represents a value. This means what you
type is what you get. We will use literals in addition to variables in Java statement. While writing a
source code as a character sequence, we can specify any value as a literal such as an integer. This
character sequence will specify the syntax based on the value's type. This will give a literal as a result.
For instance
int month = 10;
In the above statement the literal is an integer value i.e 10. The literal is 10 because it directly
represents the integer value.
In Java programming language there are some special type of literals that represent numbers,
characters, strings and boolean values. Lets have a closer look on each of the following.
Number Literals
Number literals is a sequence of digits and a suffix as L. To represent the type as long integer we use L
as a suffix. We can specify the integers either in decimal, hexadecimal or octal format. To indicate
a decimal format put the left most digit as nonzero. Similarly put the characters as ox to the left of at
least one hexadecimal digit to indicatehexadecimal format. Also we can indicate the octal format by
a zero digit followed by the digits 0 to 7. Lets tweak the table below.
Decimal integer literal of type long
659L
integer
Hexadecimal integer literal of type
0x4a
integer
Octal integer literal of type long
057L
integer
Character Literals
We can specify a character literal as a single printable character in a pair of single quote characters such
as 'a', '#', and '3'. You must be knowing about the ASCII character set. The ASCII character set includes
128 characters including letters, numerals, punctuations etc. There are few character literals which are
not readily printable through a keyboard. The table below shows the codes that can represent these
special characters. The letter d such as in the octal, hex etc represents a number.
Escap
Meaning
e
\n
New line
\t
Tab
\b
Backspace
\r
Carriage return
\f
Formfeed
\\
Backslash
\'
Single quotation mark
\"
Double quotation mark
\d
Octal
\xd
Hexadecimal
\ud
Unicode character
It is very interesting to know that if we want to specify a single quote, a backslash, or a nonprintable
character as a character literal use an escape sequence. An escape sequence uses a special syntax to
represents a character. The syntax begins with a single backslash character.
Lets see the table below in which the character literals use Unicode escape sequence to represent
printable and nonprintable characters both.
'u0041' Capital letter A
'\u0030' Digit 0
'\u0022' Double quote "
'\u003b' Punctuation ;
'\u0020' Space
'\u0009' Horizontal Tab
Boolean Literals
The values true and false are also treated as literals in Java programming. When we assign a value to a
boolean variable, we can only use these two values. Unlike C, we can't presume that the value of 1 is
equivalent to true and 0 is equivalent to false in Java. We have to use the values true and false to
represent a Boolean value. Like
boolean chosen = true;
Remember that the literal true is not represented by the quotation marks around it. The Java compiler
will take it as a string of characters, if its in quotation marks.
Floating-point literals
Floating-point numbers are like real numbers in mathematics, for example, 4.13179, -0.000001. Java
has two kinds of floating-point numbers: float and double. The default type when you write a floatingpoint literal is double.
Type
Size
Range
Precision
name bytes bits approximate in decimal digits
float 4
32 +/- 3.4 * 1038
6-7
doubl
8
64 +/- 1.8 * 10308
15
e
A floating-point literal can be denoted as a decimal point, a fraction part, an exponent (represented by E
or e) and as an integer. We also add a suffix to the floating point literal as D, d, F or f. The type of a
floating-point literal defaults to double-precision floating-point.
The following floating-point literals represent double-precision floating-point and floating-point values.
6.5E+32 (or
Double-precision floating6.5E32)
point literal
Double-precision floating7D
point literal
.01f
Floating-point literal
String Literals
The string of characters is represented as String literals in Java. In Java a string is not a basic data type,
rather it is an object. These strings are not stored in arrays as in C language. There are few methods
provided in Java to combine strings, modify strings and to know whether to strings have the same
value.
We represent string literals as
String myString = "How are you?";
The above example shows how to represent a string. It consists of a series of characters inside double
quotation marks.
Lets see some more examples of string literals:
""
Following statement declares an array variable, myList, creates an array of 10 elements of double type, and
assigns its reference to myList.:
double[] myList = new double[10];
Following picture represents array myList. Here myList holds ten double values and the indices are from 0 to 9.
Operator
Description
Example
A + B will give 30
B / A will give 2
B % A will give 0
++
B++ gives 21
--
B-- gives 19
Operator
Description
Example
==
(A == B) is not true.
!=
(A! = B) is true.
>
<
>=
<=
(A <= B) is true.
Operator
Description
Example
&
<<
>>
>>>
Operator
&&
Description
Called Logical AND operator. If both the
Example
(A && B) is false.
(A || B) is true.
Operator
Description
Example
+=
C += A is equivalent to C = C + A
-=
C -= A is equivalent to C = C - A
*=
C *= A is equivalent to C = C * A
/=
C /= A is equivalent to C = C / A
%=
C %= A is equivalent to C = C % A
<<=
>>=
&=
^=
C ^= 2 is same as C = C ^ 2
|=
C |= 2 is same as C = C | 2
Misc Operators
There are few other operators supported by Java Language.
Conditional Operator ( ? : ):
Conditional operator is also known as the ternary operator. This operator consists of three operands and is used
to evaluate boolean expressions. The goal of the operator is to decide which value should be assigned to the
variable. The operator is written as :
variable x = (expression) ? value if true : value if false
Following is the example:
public class Test {
public static void main(String args[]){
int a , b;
a = 10;
b = (a == 1) ? 20: 30;
System.out.println( "Value of b is : " + b );
b = (a == 10) ? 20: 30;
System.out.println( "Value of b is : " + b );
}
}
This would produce following result:
Value of b is : 30
Value of b is : 20
instanceOf Operator:
This operator is used only for object reference variables. The operator checks whether the object is of a
particular type(class type or interface type). instanceOf operator is wriiten as:
( Object reference variable ) instanceOf (class/interface type)
If the object referred by the variable on the left side of the operator passes the IS-A check for the class/interface
type on the right side then the result will be true. Following is the example:
String name = = 'James';
boolean result = s instanceOf String;
// This will return true since name is type of String
This operator will still return true if the object being compared is the assignment compatible with the type on the
right. Following is one more example:
class Vehicle {}
public class Car extends Vehicle {
public static void main(String args[]){
Vehicle a = new Car();
boolean result = a instanceof Car;
System.out.println( result);
}
}
This would produce following result:
true
evaluated. Certain operators have higher precedence than others; for example, the multiplication operator has
higher precedence than the addition operator:
For example x = 7 + 3 * 2; Here x is assigned 13, not 20 because operator * has higher precedence than + so it
first get multiplied with 3*2 and then adds into 7.
Here operators with the highest precedence appear at the top of the table, those with the lowest appear at the
bottom. Within an expression, higher precedenace operators will be evaluated first.
Category
Operator
Associativity
Postfix
() [] . (dot operator)
Left to right
Unary
++ - - ! ~
Right to left
Multiplicative
*/%
Left to right
Additive
+-
Left to right
Shift
Left to right
Relational
Left to right
Equality
== !=
Left to right
Bitwise AND
&
Left to right
Bitwise XOR
Left to right
Bitwise OR
Left to right
Logical AND
&&
Left to right
Logical OR
||
Left to right
Conditional
?:
Right to left
Assignment
Right to left
Comma
Left to right
Control Statements
The control statement are used to controll the flow of execution of the program . This execution order
depends on the supplied data values and the conditional logic. Java contains the following types of
control statements:
1- Selection Statements
2- Repetition Statements
3- Branching Statements
Selection statements:
1. If Statement:
This is a control statement to execute a single statement or a block of code, when the given
condition is true and if it is false then it skips if block and rest code of program is executed .
Syntax:
if(conditional_expression){
<statements>;
...;
...;
}
Example: If n%2 evaluates to 0 then the "if" block is executed. Here it evaluates to 0 so if
block is executed. Hence "This is even number" is printed on the screen.
int n = 10;
if(n%2 = = 0){
System.out.println("This is
even number");
}
2. If-else Statement:
The "if-else" statement is an extension of if statement that provides another option when 'if'
statement evaluates to "false" i.e. else block is executed if "if" statement is false.
Syntax:
if(conditional_expression){
<statements>;
...;
...;
}
else{
<statements>;
....;
....;
}
Example: If n%2 doesn't evaluate to 0 then else block is executed. Here n%2 evaluates to 1 that
is not equal to 0 so else block is executed. So "This is not even number" is printed on the
screen.
int n = 11;
if(n%2 = = 0){
System.out.println("This is even
number");
}
else{
System.out.println("This is not
even number");
}
3. Switch Statement:
This is an easier implementation to the if-else statements. The keyword "switch" is followed
by an expression that should evaluates to byte, short, char or int primitive data types ,only. In a
switch block there can be one or more labeled cases. The expression that creates labels for the
case must be unique. The switch expression is matched with each case label. Only the matched
case is executed ,if no case matches then the default statement (if present) is executed.
Syntax:
switch(control_expression){
case expression 1:
<statement>;
case expression 2:
<statement>;
...
...
case expression n:
<statement>;
default:
<statement>;
}//end switch
Example: Here expression "day" in switch statement evaluates to 5 which matches with a case
labeled "5" so code in case 5 is executed that results to output "Friday" on the screen.
int day = 5;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesda
y");
break;
case 4:
System.out.println("Thrusday")
;
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday")
;
break;
case 7:
System.out.println("Sunday");
break;
default:
System.out.println("Invalid
entry");
break;
}
Repetition Statements:
1.
int i = 1;
//print 1 to 10
while (i <= 10){
System.out.println("Num
" + i);
i++;
}
2.
3.
int i = 1;
do{
System.out.println("Num
: " + i);
i++;
}while(i <= 10);
4.
5.
current value of num is printed. Now num is incremented and checked again whether num<=10.If it is so then again it enters into
the loop. This process continues till num>10. It prints values 1 to10 on the screen.
1.
Break statements:
The break statement is a branching statement that contains two forms: labeled and unlabeled. The break statement is used for
breaking the execution of a loop (while, do-while and for) . It also terminates the switch statements.
Syntax:
break; // breaks the innermost loop or switch statement.
break label; // breaks the outermost loop in a series of nested loops.
Example: When if statement evaluates to true it prints "data is found" and comes out of the loop and executes the statements just
following the loop.
2.
Continue statements:
This is a branching statement that are used in the looping statements (while, do-while and for) to skip the current iteration of the
loop and resume the next iteration .
Syntax:
continue;
3.
Example:
4.
Return statements:
It is a special branching statement that transfers the control to the caller of the method. This statement is used to return a value to
the caller method and terminates execution of method. This has two forms: one that returns a value and the other that can not
return. the returned value type must match the return type of method.
Syntax:
return;
return values;
return; //This returns nothing. So this can be used when method is declared with void return type.
return expression; //It returns the value evaluated from the expression.
Example: Here Welcome() function is called within println() function which returns a String value "Welcome to roseIndia.net". This
is printed to the screen.
In this example we will see that how to convert the data type by using type casting. In the given line of the code c
1:0); illustrates that if t which is boolean type variable is true then value of c
= (char)(t?
which is
the char type variable will be 1 but 1 is a numeric value. So, 1 is changed into
character according to the Unicode value. But in this line c = (char)(t?'1':'0');
is already given as a character which will be stored as it is in the char type variable c.
Code of the program :
All source code is first written in plain text files ending with the .java extension. Source files are then
compiled to produce .class files. A .class file does not contain code that is native to your processor.
Rather, it contains bytecode, the machine language of the Java Virtual Machine (Java VM). The java
launcher tool then runs your application with an instance of the Java VM.
Figure 1: MyProgram.java is compiled to produce MyProgram.class, which is then interpreted by the Java
VM before My Program runs on a computer.
Object:
Object - Objects have states and behaviors. Example: A dog has states-color, name, breed as well as
behaviors -wagging, barking, eating. An object is an instance of a class.
Objects in Java:
Let us now look deep into what are objects. If we consider the real-world we can find many objects
around us, Cars, Dogs, Humans etc. All these objects have a state and behavior.
If we consider a dog then its state is . name, breed, color, and the behavior is . barking, wagging,
running
If you compare the software object with a real world object, they have very similar characteristics.
Software objects also have a state and behavior. A software object's state is stored in fields and
Note: In certain other languages, methods are referred to as procedures and functions. A method with a nonvoid
return value type is called a function; a method with a void return value type is called a procedure.
Example:
Here is the source code of the above defined method called max(). This method takes two parameters num1 and
num2 and returns the maximum between the two:
/** Return the max between two numbers */
public static int max(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
result = num2;
return result;
}
Calling a Method:
In creating a method, you give a definition of what the method is to do. To use a method, you have to call or
invoke it. There are two ways to call a method; the choice is based on whether the method returns a value or not.
When a program calls a method, program control is transferred to the called method. A called method returns
control to the caller when its return statement is executed or when its method-ending closing brace is reached.
If the method returns a value, a call to the method is usually treated as a value. For example:
int larger = max(30, 40);
If the method returns void, a call to the method must be a statement. For example, the method println returns
void. The following call is a statement:
System.out.println("Welcome to Java!");
Example:
Following is the example to demonstrate how to define a method and how to call it:
public class TestMax {
/** Main method */
public static void main(String[] args) {
int i = 5;
int j = 2;
int k = max(i, j);
System.out.println("The maximum between " + i +
" and " + j + " is " + k);
}
/** Return the max between two numbers */
public static int max(int num1, int num2) {
int result;
Overloading Methods:
The max method that was used earlier works only with the int data type. But what if you need to find which of
two floating-point numbers has the maximum value? The solution is to create another method with the same
name but different parameters, as shown in the following code:
public static double max(double num1, double num2) {
if (num1 > num2)
return num1;
else
return num2;
}
If you call max with int parameters, the max method that expects int parameters will be invoked; if you call max
with double parameters, the max method that expects double parameters will be invoked. This is referred to
as method overloading; that is, two methods have the same name but different parameter lists within one class.
The Java compiler determines which method is used based on the method signature. Overloading methods can
make programs clearer and more readable. Methods that perform closely related tasks should be given the same
name.
Overloaded methods must have different parameter lists. You cannot overload methods based on different
modifiers or return types. Sometimes there are two or more possible matches for an invocation of a method due
to similar method signature, so the compiler cannot determine the most specific match. This is referred to as
ambiguous invocation.
The Scope of Variables:
The scope of a variable is the part of the program where the variable can be referenced. A variable
defined inside a method is referred to as a local variable.
The scope of a local variable starts from its declaration and continues to the end of the block that
contains the variable. A local variable must be declared before it can be used.
A parameter is actually a local variable. The scope of a method parameter covers the entire method.
A variable declared in the initial action part of a for loop header has its scope in the entire loop. But a
variable declared inside a for loop body has its scope limited in the loop body from its declaration to the
end of the block that contains the variable as shown below:
You can declare a local variable with the same name multiple times in different non-nesting blocks in a method,
but you cannot declare a local variable twice in nested blocks.
Using Command-Line Arguments:
Sometimes you will want to pass information into a program when you run it. This is accomplished by
passing command-line arguments to main( ).
A command-line argument is the information that directly follows the program's name on the command
line when it is executed. To access the command-line arguments inside a Java program is quite easy.they
are stored as strings in the String array passed to main( ).
Example:
The following program displays all of the command-line arguments that it is called with:
class CommandLine {
public static void main(String args[]){
for(int i=0; i<args.length; i++){
System.out.println("args[" + i + "]: " +
args[i]);
}
}
}
Try executing this program, as shown here:
java CommandLine this is a command line 200 -100
This would produce following result:
args[0]: this
args[1]: is
args[2]: a
args[3]: command
args[4]: line
args[5]: 200
args[6]: -100
The Constructors:
A constructor initializes an object when it is created. It has the same name as its class and is syntactically similar
to a method. However, constructors have no explicit return type.
Typically, you will use a constructor to give initial values to the instance variables defined by the class, or to
perform any other startup procedures required to create a fully formed object.
All classes have constructors, whether you define one or not, because Java automatically provides a default
constructor that initializes all member variables to zero. However, once you define your own constructor, the
default constructor is no longer used.
Example:
Here is a simple example that uses a constructor:
// A simple constructor.
class MyClass {
int x;
// Following is the constructor
MyClass() {
x = 10;
}
}
You would call constructor to initialize objects as follows:
class ConsDemo {
public static void main(String args[]) {
MyClass t1 = new MyClass();
MyClass t2 = new MyClass();
Important Questions:
1. (a) What is an array? Why arrays are easier to use compared to a bunch of related variables?
(b) Write a program for transposition of a matrix using arraycopy command.
2. (a) What is a constructor? What are its special properties?
(b) How do we invoke a constructor?
(c) What are objects? How are they created from a class?
3. (a) What is class? How does it accomplish data hiding?
(b) How do classes help us to organize our programs?
(c) Compare and contrast overloading and overriding methods.
4.(a) How does String class differ from the StringBuffer class?
(b) Write program to do the following:
i. To output the question who is the inventor of java?
ii. To accept an answer
iii. To print out Good and then stop, if the answer is correct.
iv. To output the message try again, if the answer is wrong
v. To display the correct answer when the answer is wrong even at the third attempt.
5.Briefly explain following:
(a) final & this keywords
(b) garbage collection
(c) passing parameter-call by value
(d) Overloading methods & Constructors.
6.(a) What is the difference between equality of objects and equality of objects and equality of
references that refer to them?
(b) What is the difference between a public member and a private member of a class?
(c) write an application that computes the value of ex by using the formula:
ex = 1 + x/1! + x2/2! + x3/3! + ..........