Unit 1 Notes
Unit 1 Notes
Unit 1 Notes
INTRODUCTION TO JAVA
CONTENTS OF THIS UNIT
BASIC OF JAVA PROGRAMMING
DATA TYPES
VARIABLES
OPERATORS
CONTROL STRUCTURES INCLUDING SELECTION
LOOPING
JAVA METHOD
OVERLOADING
MATH CLASS
ARRAY IN JAVA
HISTORY OF JAVA
1
Earlier, C++ was widely used to write object oriented programming
languages, however, it was not a platform independent and needed to
be recompiled for each different CPUs. A team of Sun Microsystems
including Patrick Naughton, Mike Sheridan in the guidance of James
Goslings decided to develop an advanced programming language for
the betterment of consumer electronic devices. They wanted to make it
new software based on the power of networks that can run on different
application areas, such as computers and electronic devices. In the year
1991 they make platform independent software and named it Oak. But
later due to some patent conflicts, it was renamed as Java and in 1995
the Java 1.0 was officially released to the world.
What is Java?
Java is a high level language - Java's syntax allows for the use of
words and commands instead of just symbols and numbers, it is
closer to human languages and further from machine language.
The advantage to Java being a high level language is that it is
easier to read, write, and maintain.
Java is an object oriented language - Define your own reusable
data structures called objects as well as their attributes
2
(properties) and things they can do (methods). You can also
create relationships between various objects and data structures.
Java is a software development language AND a web language -
Create programs and applets (small programs that run on
webpages).
Java is platform independent - You can run the same Java
programs on various operating systems without having to rewrite
the code, unlike other programming languages such as C and C++.
Java source code is not converted into machine language, but into
a special form of instruction known as Java byte code which is
then interpreted by the Java run-time environment which
instructs the operating system on what to do. This allows Java
programs to run the same way on all operating systems.
Java source code files have a .java extension. Java programs have a
.class extension.
Some people think that Java and Javascript are the same language.
They are not.
Interact with the user - You can do things like ask the user
for their name and print a custom message with it such as
"Hello Roger!"
Create graphical programs - Graphical programs which can
include components like buttons, textboxes, menus, and
checkboxes. For example, you can create a simple text editing
program such as Window's Notepad.
Create applets - An applet is a program that runs within another
program. With Java, you can create applets that will run inside
webpages. For example, you can create an applet that will get
input from the user and store it in a database.
Respond to events - Make certain things happen when events like
a window being minimized or a button being clicked occur. You
can do things like issue a message to the user, display/hide certain
data, or even create animations.
Communicate with databases - Read data stored in a database or
write new data to a database. For example, you can store a users
name and e-mail address, and allow them to view this information
and change it if necessary and the changes will be reflected in the
database.
4
Sample JAVA Program and It’s Execution
5
Java Virtual Machine
The figure below explains the lifecycle of a Java Program. In words, the
figure can be explained as:
1. A Java program is written using either a Text Editor like Textpad or
an IDE like Eclipse and is saved as a .java file. (Program.java)
2. The .java file is then compiled using Java compiler and a .class file
is obtained from it. (Program.class)
3. The .class file is now portable and can be used to run this
Java programin any platform.
4. Class file (Program.class) is interpreted by the JVM installed on a
particular platform. JVM is part of the JRE software.
6
Characteristics of Java
1. Java is simple
2. Java is object-oriented
3. Java is distributed
4. Java is interpreted
5. Java is robust
6. Java is secure
7. Java is architecture-neutral
8. Java is portable
9. Java’s performance
10. Java is multithreaded
11. Java is dynamic
7
Java program core code
Example:
class PrintText{ }
class PrintText{
public static void main(String[] args)
{
}
} 8
3. Printing text
You can use two methods to print text in Java. Use double
quotes for the text within each method.
System.out.print() method - prints a line of text
System.out.println() method - prints a line of text followed by
a line break
Example:
class PrintText{
public static void main(String[] args){
System.out.println ("Here is some text");
System.out.print ("Here is some more text");
}
}
Output:
Here is some text
Here is some more text
Example:
9
/* This is a multi-line comment
class PrintText
{
public static void main(String[] args){
//print a single line of text followed by a line break
System.out.println("Here is some text");
//print another line of text
//with no line break afterwards
System.out.print("Here is some more text");
}
}
What is a variable?
For example, in a program that calculates tax on items you can have a
few variables - one variable that stores the regular price of an item and
another variable that stores the total price of an item after the tax is
calculated on it. Variables store this information in a computer's
memory and the value of a variable can change all throughout a
program.
Declaring variables
One variable in your program can store numeric data while another
variable can store text data. Java has special keywords to signify what
type of data each variable stores. Use these keywords when declaring
your variables to set the data type of the variable.
10
Java data types
Size in
Keyword Type of data the variable will store
memory
boolean true/false value 1 bit
byte byte size integer 8 bits
char a single character 16 bits
double precision floating point decimal
double 64 bits
number
single precision floating point decimal
float 32 bits
number
int a whole number 32 bits
long a whole number (used for long numbers) 64 bits
short a whole number (used for short numbers) 16 bits
Example:
char aCharacter;
int aNumber;
Example:
char aCharacter = 'a';
int aNumber = 10;
11
char aCharacter;
aCharacter = 'a';
int aNumber;
aNumber = 10;
Naming variables
12
Distinguish between uppercase and lowercase - Java is a case
sensitive language which means that the variables varOne,
VarOne, and VARONE are three separate variables!
When referring to existing variables, be careful about spelling - If
you try to reference an existing variable and make a spelling
mistake, an error will be generated.
Printing variables
When printing the value of a variable, the variable name should NOT
be included in double quotes. You can also print variables together
with regular text. To do this, use the + symbol to join the text and
variable values.
class PrintText
{
public static void main(String[] args)
{
//declare some variables
byte aByte = -10;
int aNumber = 10;
char aChar = 'b';
boolean isBoolean = true;
System.out.println(aByte);
System.out.println(aNumber);
13
System.out.println("aChar = " + aChar);
System.out.println("Is the isBoolean variable a boolean
variable? " + isBoolean); }
}
Output:
-10
10
aChar = b
Is the isBoolean variable a boolean variable?
The if statement
Syntax:
if(condition)
{
Perform this action;
}
Example:
int aNumber = 5; //check if aNumber equals 5 and if it is print a message
if (aNumber == 5)
{
System.out.print("aNumber is equal to 5");
}
=====================================================
Output:
aNumber is equal to 5
14
NOTE: Use two equal signs (==) in the condition when comparing
values. One equal sign (=) is used to assign values, while two equal signs
(==) are used to compare values.
Syntax:
if(condition)
{
perform this action;
}
else
{
perform this action if the above condition is false;
}
Example:
int aNumber = 10; //check if aNumber equals 5 and if it is print a message if
(aNumber == 5)
{
System.out.print("aNumber is equal to 5");
}
//otherwise print a different message
else{
System.out.println("aNumber equals a number other than 5");
}
=======================================================
Output:
aNumber equals a number other than 5
15
The else-if statement
Any condition can be only true or false, but what if you needed to test a
variable for more than one value? This is where the else-if statement
comes in. The else-if statement performs an action if the variable in the
if statement is another value specified in the else- if statement itself.
Syntax:
if(condition1)
{
perform this action;
}
else if(Condition2)
{
perform this action;
}
Example:
int aNumber = 7;
if (aNumber == 5)
{
System.out.print("aNumber is equal to 5");
}
else if (aNumber == 7)
{
System.out.print("aNumber is equal to 7");
}
===========================================================
Output:
aNumber is equal to 7
16
Using if, else, and else if together
You can use the if, else, and else if statements together when you want
to check a variable for a certain value many times. If it is not any of the
checked values then the code specified by the else statement will be
executed.
Syntax:
if(condition1)
{
perform this action;
}
else if(Condition2)
{
perform this action;
}
else
{
perform this action if the any of above condition is not true;
}
Example:
int aNumber = 7;
if (aNumber == 5)
{
System.out.print("aNumber is equal to 5");
}
else if (aNumber == 7)
{
System.out.print("aNumber is equal to 7");
}
else
{
System.out.print("number is not matched”);
}
===========================================================
Output:
aNumber is equal to 7 17
The switch statement
Syntax:
switch(variable)
{
case possible value:
perform this action;
break;
case possible value:
perform this action;
break;
case possible value:
perform this action;
break;
default:
perform this action if none of the values match;
}
Example:
Example:
18
int aNumber = 7;
switch(aNumber)
{
//test if aNumber equals one of a set of values and if it is print a message
case 1:
System.out.print("aNumber is equal to 1");
break;
case 2:
System.out.print("aNumber is equal to 2");
break;
case 3:
System.out.print("aNumber is equal to 3");
break;
case 7: System.out.print("aNumber is equal to 7");
break;
===================================================================
Output:
aNumber is equal to 7
The ternary operator is the question mark symbol (?), it works the same
way as the if-else structure, the coding is just different.
Syntax:
========================================================
Output:
aNumber = 15
Java loops
The for loop is used to repeat a task a set number of times. It has three
parts.
Syntax:
Lets take apart the loop from the above example to see what each part
does.
21
The above loop will execute the code between the braces 10 times
because a begins at 1 and ends at 10. This counter is what runs the
loop.
The while loop works differently than the for loop. The for loop repeats
a segment of code a specific number of times, while the while loop
repeats a segment of code an unknown number of times. The code
within a while loop will execute while the specified condition is true.
Syntax:
Initialization;
while(condition is true)
{
execute this code;
increment/decrement // not compulsory
}
Example:
int num = 0;
while(num < 25)
{
num = num + 5;
System.out.print(num + " ");
}
================================================
Output:
5 10 15 20 25
In the above code, a variable named num is initialized with the value of
0. The condition for the while loop is that while num is less than 25, 5
22
should be added to num and it should be printed (together with a
single space). Once the value of num is greater than 25, the loop will
stop executing.
The do-while loop is very similar to the while loop, but it does things in
reverse order. The while loop - while a condition is true, perform a
certain action, the do-while loop - perform a certain action while a
condition is true. Also, the code within a do-while loop will always
execute at least once, even if the specified condition is false. This is
because the code is executed before the condition is tested.
Syntax:
do
{
execute this code;
} while (condition);
Example:
int num = 5;
do{
num = num + 2;
System.out.print(num + " ");
} while (num < 25);
===================================================
Output:
7 9 11 13 15 17 19 21 23 25
In the above code, a variable named num is initialized with the value of
5. The condition for the do-while loop is that 2 should be added to num
and it should be printed (together with a single space) while num is less
23
than 25. Once the value of num is greater than 25, the loop will stop
executing.
You can completely break out of a loop when it is still running. This is
achieved with the break keyword. Once a loop is exited, the first
statement right after it will be executed. The break keyword provides
an easy way to exit a loop if an error occurs, or if you found what you
were looking for.
Example:
for(int a = 1; a < 10; a++)
{
System.out.print(a + " ");
if(a == 5)
{break;}
}
System.out.print("You have exited the loop");
In the above example, the for loop is set to iterate 9 times and print the
current value of the variable a during each iteration. The if statement
within the loop states that when the variable a is equal to 5, break out
of the loop.
Output:
1 2 3 4 5 You have exited the loop
Continuing a loop
While you can break out of a loop completely with the break keyword,
there is another keyword used when working with loops - the continue
keyword. Using the continue keyword in a loop will stop the loop at
some point and continue with the next iteration of the loop from the
beginning of it.
24
Example:
for(int a = 1; a < 10; a++)
{ if(a == 5){continue;} System.out.print(a + " ");
}
In the above example, the for loop is set to iterate 9 times and print the
current value of the variable a during each iteration. The if statement
within the loop states that when the variable a is equal to 5, stop the
loop and continue with the next iteration of the loop from the
beginning of it. For this reason, all the numbers except the number 5
are printed.
Output:
12346789
NOTE: For the continue keyword to work properly, the
conditional statement needs to come first just like in the above
example
25
OPERATORS IN JAVA
Arithmetic operator
Unary Operator
Comparison Operator
Bitwise Operator
Shift Operator
Ternary operator
Assignment operator
class ArithmeticDemo {
26
int result = 1 + 2; // result is now 3
System.out.println(result);
}
}
27
The increment/decrement operators can be a prefix or a postfix .In a
prefix expression (++ x or -- x), an operator is applied before an
operand while in a postfix expression (x ++ or x --) an operator is
applied after an operand. In both conditions 1 is added to the value of
the variable and the result isstored back to the variable. However both
operators have the same effect as "x = x + 1;"
C:\nisha>javac
Prefix.java
C:\nisha>java
Prefix
28
The value of x
:1
The value of
y:1
C:\nisha>java
Postfix
The value of x
:1
The value of
y:0
The output of the program indicates the value of variable "x" is stored
first to the variable "y" then it isincremented by 1.
29
Unary Plus (+) Operator
Unary plus operator (+) indicates positive value. This (+) operator is
used to perform a type conversion operation on an operand. The type
of the operand must be an arithmetic data type i.e. if a value of the
integer operand is negative then that value can be produced as a
positively applying unary plus (+) operator. For example, lets see the
expressions shown as:
int x = 0;
int y = (-
25);
x = (+y);
Unary minus operator (-) indicates negative value and differ from the
unary plus operator. This (-) operator is also used to perform a type
conversion operation on an operand. If a value of the integer operand
is positive then that value can be produced as a negatively applying
unary minus (-) operator. For example, lets see the expressions shown
as:
int x = 0;
int y = 25;
x = (-y);
30
In this expression, a positive value is assigned tothe variable "y". After
applying minus plus (-)operator on the operand "y", the value
becomes "-25" which indicates it as a negative value. This behavior
represents the number in two's complement format.
The bitwise NOT "~" operator inverts each bit in the operand i.e. this
operator changes all the ones to zeros and all the zeros to ones.
Remember that this operator takes only one operand or parameter.
Hence in the program code given below only one parameter has been
taken.
class BitwiseNOT{
public static void main(String args[])
{ System.out.println(" ~ NOT opeartor");
System.out.println("~ 1 = " + ~1);
System.out.println("~ 5 = " + ~5);
}
}
~1=-2
~5=-6
31
The logical compliment (!) operator is also known as Boolean Negation
Operator. It is used to invertthe value of a boolean type operand i.e.
the type of the operand must be boolean while using this operator,. If
the value of the boolean operand is false, the ! operator returns true.
But, if the value of the operand is true, the ! operator returns false.
Lets have one more example using unary operators in different flavors:
class UnaryOperator {
number = -number;
System.out.println("result is now:" + number);
++number;
System.out.println("result is now:" + number);
32
number1=number++;
System.out.println("result is now:" + number);
System.out.println("result of number1 is:" + number1);
C:\nisha>javac
UnaryOperator.java
C:\nisha>java
UnaryOperator
result is now:1
result is now:-1
result is now:0
result is now:1
result of number1
is:0
2 is geater than 1:
true
2 is geater than 1:
false
33
(3) Comparision Operator
All the standard comparison operators work for primitive values (int,
double, char, ...). The == and != operators can be used to compare
object references, but see Comparing Objects for how to compare
object values
The result of every comparison is boolean (true or false).
operator meaning
< less than
<= less than or equal to
== equal to
>= greater than or equal to
> greater than
!= not equal
(4) Short-circuit operator
Java provides two interesting Boolean operators not found in most
other computer languages. These are secondary versions of the
Boolean AND and OR operators, and are known as short-circuit
logical operators. As you can see from the preceding table, the OR
operator results in true when A is true, no matter what B is.
Similarly, the AND operator results in false when A is false, no
matter what B is. If operator results in false when A is false, no
matter what B is. If you use the | | and && forms, rather than the |
and & forms of these operators, java will not bother to evaluate
the right-hand operand alone. This is very useful when the right-
hand operand depends on the left one being true or false in order
to function properly. For example, the following code fragment
34
shows
35
how you can take advantage of short-circuit logical evaluation to be
sure that a division operation will be valid before evaluating it:
Here, using a single & ensures that the increment operation will
be applied to e whether c is equal to 1 or not.
36
in two's complement form. For example, -4 is 1111 1111 1111 1111
1111 1111 1111 1100.
Operator Name Example Result Description
37
0101(5)<< 1 1010(10)
>>> a>>>b Shift bits of a by
distance b
0101(5)>>> 1 0010(2)
minVal = (a < b) ? a : b;
In this code, if the variable a is less than b, minVal is assigned the value
of a; otherwise, minVal is assigned the value of b. Note that the
38
parentheses in this example are optional, so you can write that same
statement like this:
minVal = a < b ? a : b;
I think the parentheses make the code a little easier to read, but again,
they're completely optional.
You can take a similar approach to get the absolute value of a number,
using code like this:
<variable> = <expression>;
For example:
int counter = 1;
String name = "Nisha";
boolean rs = true;
39
Shape s1 = new Shape(); //
creates new object
Shape s2 = s1; //assigning
the reference of s1 to s2
counter = 5; // previous
value is overwritten
In all cases a value of right side is being assigned to its type of variable
lying to the left side. You can also assign a value to the more than one
variable simultaneously. For example, see these expressions shown as:
x = y = z = 2;
x =(y + z);
40
In this case, both variables must be of the same type
41
ARRAY IN JAVA
x0=0;
x1=1;
x2=2;
x3=3;
x4=4;
x5=5;
with this
… x[0]=0;
x[1]=1;
42
x[2]=2;
x[3]=3;
x[4]=4;
x[5]=5;
how this helps is that the index (the number in the bracket[]) can
be referenced by a variable for easy looping.
<elementType>[] <arrayName>;
or
<elementType> <arrayName>[];
Example:
43
Constructing an Array
Initializing an Array
intArray[0]=1; // Assigns an integer value 1 to the first element 0
of the array
intArray[1]=2; // Assigns an integer value 2 to the second
element 1 of the array
class ArrayDemo{
public static void main(String args[]){
44
int array[] = new int[7];
for (int count=0;count<7;count++){
array[count]=count+1;
}
for (int count=0;count<7;count++){
System.out.println("array["+count+"] = "+array[count]);
}
//System.out.println("Length of Array = "+array.length);
// array[8] =10;
}
}
Step 2) Save , Compile & Run the code. Observe the Output
multidimensional arrays
array of Objects
46
It is possible to declare array of reference variables.
Syntax:
Class <array_name> = new Class[array_length]
class ObjectArray{
public static void main(String args[]){
Account obj[] = new Account[2] ;
//obj[0] = new Account();
//obj[1] = new Account();
47
obj[0].setData(1,2);
obj[1].setData(3,4);
System.out.println("For Array Element 0");
obj[0].showData();
System.out.println("For Array Element 1");
obj[1].showData();
}
}
MATH IN JAVA
Java’s Math class contain a collection of methods and two constants
that support mathematical computation.As this class is final it cant be
extend.the constructor of this class is private,so you cant create an
istance .but these methods and constructor are static,so they can be
accessed through the class name without having to construct a Math
object.
Math.PI,Math.E
For example,
Double x,y;
X=9;
Y=Math.sqrt(x)//this computes the square root of x
48
All trigonometric method parameters are measured in radians, the
normal mathematical system of angles, and not in degrees, the normal
human angular measurement system. Use the toRadians or toDegrees
methods to convert between these systems, or use the fact that there
are 2*PI radians in 360 degrees. In addition to the methods below, the
arc methods are also available.
double Math.sin(ar) Returns the sine of ar.
double Math.cos(ar) Returns the cosine of ar.
double Math.tan(ar) Returns the tangent of
ar.
double Math.toRadians(d) Returns d (angle in degrees) converted
to radians.
double Math.toDegrees(ar) Returns ar (angle in radians) converted
to degrees.
Exponential Methods
The two basic functions for logarithms and power are available. These
both use the base e (Math.E) as is the usual case in mathematics.
double Math.exp(d) Returns e (2.71...) to the power d.
double Math.pow(d1, d2) Returns d1d2.
double Math.log(d) Returns the logarithm of d to base e.
double Math.log10(d) Returns the logarithm of d to base 10.
Misc Methods
double Math.sqrt(d) Returns the square root of d.
Math.abs(x) Returns absolute value of x with same
type as the parameter: int, long, float, or
double.
Math.max(x, y) Returns maximum of x and y with same
type as the parameter: int, long, float, or
double.
Math.min(x, y) Returns minimum of x and y with same
type as the parameter: int, long, float, or
49
double.
50
Integer Related Methods
51