Unit 1 Notes

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 51

UNIT -1

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

 BASIC OF JAVA PROGRAMMING

 HISTORY OF JAVA

Java was created by a team of programmers at sun micro System


in 1991.it took 18 months to develop the first working
version.This Language was initially called “oak” but it was
renamed “java” in 1995.
Actualy the originally goal was to create computer language that
could be used to build program that would run in any different
execution environment.They wanted to devlope a language that
could be used to write a software for different consumer
electronic devices.

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.

Java is influenced by C, C++, Smalltalk and borrowed some advanced


features from some other languages. The company promoted this
software product with a slogan named “Write Once Run Anywhere”
that means it can develop and run on any device equipped with Java
Virtual Machine (JVM). This language is applicable in all kinds of
operating systems including Linux, Windows, Solaris, and HP-UX etc.

What is Java?

Java is a programming language used to develop software applications


as well as applets that run on webpages.

 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 file extensions

Java source code files have a .java extension.

Java programs have a .class extension.

Java file extensions

Java source code files have a .java extension. Java programs have a
.class extension.

Java and Javascript

Java and Javascript, what's the difference? A major difference!!

Some people think that Java and Javascript are the same language.
They are not.

Java is a language used to create software applications and applets,


3
while Javascript is a scripting language used to create dynamic and
interactive content on webpages.

What can be done with Java?

 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

Program Execution Steps:

5
Java Virtual Machine

 Java is compiled into bytecodes


 Bytecodes are high-level, machine-independent instructions for a
hypothetical machine, the Java Virtual Machine (JVM)
 The Java run-time system provides the JVM
 The JVM interprets the bytecodes during program execution
 Since the bytecodes are interpreted, the performance of
Java programs slower than comparable C/C++ programs
 But the JVM is continually being improved and new techniques
are achieving speeds comparable to native C++ code

LIFE CYCLE OF JAVA PROGRAM

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

 Fundamental structure of a Java program consists of these


elements:
1. A class declaration - A class is a grouping of related variables
and functions (methods) that is used to achieve something.
 All the source code for a Java program will be placed
within the class definition.
 The class is given a name and the code within it is
surrounded by curly brackets.

Example:
class PrintText{ }

2. A main() method - A method is a grouping of code that


executes when it is called.
 One method used in every Java program is the main()
method, it's what makes a Java program work.
 The main() method has to be set with a few special
keywords and a certain parameter like in the example
below.
Example:

 The above example is a 'bare bones' Java program. It


doesn't do anything, only contains the fundamental
Java program structure.

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

NOTE: Every line of code in a Java program must end with a


semicolon or an error will be generated!
 Including comments in Java code
 Comments are declared so that code would be easier to
understand and to navigate. Comments can be placed
anywhere within code. You can have single line comments or
multi-line comments.
 Single line comments - declared with two / symbols (span a
single line)
 multi-line comments - declared with a starting /* and an
ending */ (span as many lines as you want)

Example:

9
/* This is a multi-line comment

This program will print


two lines of text */

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?

A variable is a container that stores a meaningful value that can be used


throughout a program.

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;

 You can assign a value to a variable at the same time that it is


declared. This process is known as initialization:

Example:
char aCharacter = 'a';
int aNumber = 10;

 Declaring a variable and then giving it a value:

11
char aCharacter;
aCharacter = 'a';
int aNumber;
aNumber = 10;

NOTE: A variable must be declared with a data type or an error will be


generated! The data type of a variable should be used only once with
the variable name - during declaration. After that, you can refer to the
variable by its name without the data type.

Naming variables

Rules that must be followed when naming variables or errors will be


generated and your program will not work:

 No spaces in variable names


 No special symbols in variable names such as !@#%^&*
 Variable names can only contain letters, numbers, and the
underscore ( _ ) symbol
 Variable names cannot start with numbers, only letters or the
underscore ( _ ) symbol (but variable names can contain numbers)

Recommended practices (make working with variables easier and help


clear up ambiguity in code):

 Make sure that the variable name is descriptive of what it stores -


For example, if you have a variable which stores a value specifying
the amount of chairs in a room, name it "numChairs".
 Make sure the variable name is of appropriate length - Should
be long enough to be descriptive, but not too long.

Also keep in mind:

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

Variables are printed by including the variable name in a


“System.out.print() ”or System.out.println() method.

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;

//print variables alone

System.out.println(aByte);
System.out.println(aNumber);

//print variables with text

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?

Java conditional logic

The if statement

The if statement will execute some code if a condition is true.

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.

The else statement

The if statement executes some code if a condition is true, but what if


the condition is false? The else statement will execute some code if the
condition in the if statement is false.

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

The switch statement is specifically designed for comparing one


variable to a number of possible values. It can be thought of as a
substitute for the if, else-if, else structure. There is an important
keyword used within the switch structure, and that keyword is the
break keyword. The break keyword is used to make sure that the
switch structure will not fall through to the next possible value.

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;

//test if aNumber equals an unspecified value and if it is print a message


default:
System.out.print("aNumber is not equal to any of the values specified");
}

===================================================================
Output:
aNumber is equal to 7

The ternary operator

The ternary operator is the question mark symbol (?), it works the same
way as the if-else structure, the coding is just different.

Syntax:

Variable = (condition)? Value the variable will take if condition is true:


value the variable will take if condition is false
19
Example:
int aNumber;
int anotherNumber = 7;
//check if anotherNumber equals 10 and if it is aNumber takes the value of 5
//otherwise aNumber takes the value of 15

aNumber = (anotherNumber==10) ? 5: 15;


System.out.print("aNumber = " + aNumber);

========================================================
Output:
aNumber = 15

Java loops

The for loop

The for loop is used to repeat a task a set number of times. It has three
parts.

 variable declaration - Initializes the variable at the beginning of


the loop to some value. This value is the starting point of the
loop.
 condition - Decides whether the loop will continue running or not.
While this condition is true, the loop will continue running. Once
the condition becomes false, the loop will stop running.
 Increment/decrement statement - The part of the loop that
changes the value of the variable created in the variable
20
declaration part of the loop. The increment/decrement statement
is the part of the loop which will eventually stop the loop from
running.

Syntax:

for(int a_variable = initial_value ; a_variable < end_value ;


a_variable_increment/decrement)
{
code to be executed;
}
Example:
for(int a = 1; a < 11; a++)
{
System.out.print(a + " ");
}
==========================================
Output:
1 2 3 4 5 6 7 8 9 10

Lets take apart the loop from the above example to see what each part
does.

 int a = 1 - A variable named a is declared with the value of 1.


 a < 11 - The condition of the loop, states that as long as the
variable a is less than 11, the loop should keep running.
 a++ - The increment statement part of the loop, states that for
every iteration of the loop, the value of the variable a should
increase by 1. Recall that initially a is 1.
 System.out.print(a + " ") - Print the value of a together with
a single space for each time the loop runs.

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

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

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.

Breaking out of a loop

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

(1) Arithmetic operator

The Java programming language provides operators that perform


addition, subtraction, multiplication, and division. There's a good
chance you'll recognize them by their counterparts in basic
mathematics. The only symbol that might look new to you is "%", which
divides one operand by another and returns the remainder as its result.

+ additive operator (also used for String concatenation)


- subtraction operator
* multiplication operator
/ division operator
% remainder operator
The following program, ArithmeticDemo, tests the arithmetic
operators.

class ArithmeticDemo {

public static void main (String[] args){

26
int result = 1 + 2; // result is now 3
System.out.println(result);

result = result - 1; // result is now 2


System.out.println(result);

result = result * 2; // result is now 4


System.out.println(result);

result = result / 2; // result is now 2


System.out.println(result);

result = result + 8; // result is now 10


result = result % 7; // result is now 3
System.out.println(result);

}
}

(2) Unary Operator

There are five types of Unary Operators.


(1)The Increment or Decrement operator:++ --
(2)the unary plus and unary minus:+ -
(3) the bitwise inversion operator:~
(4)the Boolean complement operatoe:!
(5)the cast operator: ()

(1) The Increment or Decrement operator:-

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;"

Although there is a major difference between a prefix and


a postfix expressions. In a prefixexpression, a value is incremented first
then this new value is restored back to the variable. On the other
hand, In postfix expression the current value is assigned to a variable
then it is incremented by1 and restored back to the original variable.

Lets make the things more clear with few examples


( i ) example using prefix unary operator:

public class Prefix{


public static void main(String[] args){
int x = 0; int y = 0; y = ++x;
System.out.println("The value of x :" + x);
System.out.println("The value of y:" + y);
}
}

Output of the Program:

C:\nisha>javac
Prefix.java

C:\nisha>java
Prefix

28
The value of x
:1
The value of
y:1

The output of this program shows that always 1 is stored in both


variables i.e. the value of "x" is incremented first then it is assigned to
the variable "y".

( ii ) example using postfix unary operator:

public class Postfix{


public static void main(String[] args){
int x = 0;
int y = 0;
y = x++;
System.out.println("The value of x :"+ x );
System.out.println("The value of y:" + y );
}
}

Output of the Program:

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.

(2) unary plus and minus operator

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);

In this expression, a negative value is assigned to the variable "y". After


applying unary plus (+)operator on the operand "y", the value
becomes 25 which indicates it as a positive value.
However a number is positive without using unary plus (+) operator, if
we have initially assigned it positively into the operand in the program.

II. Unary minus (-) Operator

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.

(3) The Bitwise Inversion operator

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.

Here is the code of program:

class BitwiseNOT{
public static void main(String args[])
{ System.out.println(" ~ NOT opeartor");
System.out.println("~ 1 = " + ~1);
System.out.println("~ 5 = " + ~5);
}
}

Output of the program:

~1=-2
~5=-6

(4) The Boolean Complement Operator

Logical Compliment (!) Operator

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.

For example, lets see the statements shown as:

boolean result = (2>1);


result = !result
System.out.println("2 is geater
than 1: " + result);

In these statements, the first expression returns true to the


variable "result" but at the end of the program, the output is shown
as false because the compliment (!) operator inverts the value of the
variable "result".

Lets have one more example using unary operators in different flavors:

class UnaryOperator {

public static void main(String[] args){


int number = 1;
int number1 = 0;
System.out.println("result is now:" + number);

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);

boolean result = (2>1);


System.out.println("2 is geater than 1: " + result);
System.out.println("2 is geater than 1: " + !result);
}
}

Output of the Program:

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:

if ( denom != 0 && num / denom >10)

Since the short-circuit form of AND (&&) is used, there is no risk


of causing a run-time exception when denom is zero. If this line of
code were written using the single & version of AND, both sides
would have to be evaluated, causing a run-time exception when
denom is zero.

It is standard practice to use the short-circuit forms of AND


and OR in cases involving Boolean logic, leaving the single-character
versions exclusively for bitwise operations. However, there are
exceptions to this rule. For example, consider the following
statement:

if ( c==1 & e++ < 100 ) d = 100;

Here, using a single & ensures that the increment operation will
be applied to e whether c is equal to 1 or not.

(5) Bitwise Operator


Java's bitwise operators operate on individual bits of integer (int and
long) values. If an operand is shorter than an int, it is promoted to
int before doing the operations.
It helps to know how integers are represented in binary. For example
the decimal number 3 is represented as 11 in binary and the decimal
number 5 is represented as 101 in binary. Negative integers are store

36
in two's complement form. For example, -4 is 1111 1111 1111 1111
1111 1111 1111 1100.
Operator Name Example Result Description

a&b and 3&5 1 1 if both bits are 1.

a|b or 3|5 7 1 if either bit is 1.

a^b xor 3^5 6 1 if both bits are different.

~a not ~3 -4 Inverts the bits.

(6) Shift Operator

<< Signed left shift


>> Signed right shift
>>> Unsigned right shift
Java provides two right side shifting operator (>> >>>) and one left shift
operator(<<).A Shift operator allow us to perform bit manipulating on
data.This table summarize the shift operator in java programming
language.

Operator Use operation


>> a>>b Shift bits a right by
distance b
0101(5) >> 1 0010(2)
<< a<<b Shift bits of a left by
distance b

37
0101(5)<< 1 1010(10)
>>> a>>>b Shift bits of a by
distance b
0101(5)>>> 1 0010(2)

(7) Ternary Operator


Interested in saying a lot while writing a little? In a single line of code,
the Java ternaryoperator let's you assign a value to a variable based on
a boolean value (either a boolean field, or a statement that evaluates to
a boolean result).
At its most basic, the ternary operator (also known as the conditional
operator) can be used as an alternative to the Java if/then/else syntax,
but it actually goes beyond that, and can even be used on the right
hand side of Java statements.
Simple ternary operator examples
Although it may be a little confusing when you first see it, the ternary
operator lets you make powerful decisions with a minimal amount of
coding.
One use of the Java ternary operator (also called the conditional
operator) is to assign the minimum (or maximum) value of two
variables to a third variable, essentially replacing
a Math.min(a,b) or Math.max(a,b) method call. Here's an example that
assigns the minimum of two variables, a and b, to a third variable
named minVal is:

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:

int absValue = (a < 0) ? -a : a;

(8) Assignment operator

Assignment operator is the most common operator almost used with


all programming languages. It is represented by "=" symbol in Java
which is used to assign a value to a variable lying to the left side of the
assignment operator. But, If the value already exists in that variable
then it will be overwritten by the assignment operator (=). This
operator can also be used to assign the references to the
objects. Syntax of using the assignment operator is:

<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);

Where the assignment operator is evaluated from right to left. In the


first expression, value 2 is assigned to the variables
"z", then "z" to "y", then "y" to "x" together. While in second
expression, the evaluated value of the addition operation is assigned to
the variable "x" initially then the value of variable "x" is returned.

Apart from "=" operator, different kind of assignment operators


available in Java that are know ascompound assignment operators and
can be used with all arithmetic or, bitwise and bit shiftoperators.
Syntax of using the compound assignment operator is:

operand operation= operand

In this type of expression, firstly an arithmetic operation is performed


then the evaluated value is assigned to a left most variable. For
example an expression as x += y; is equivalent to the expression as x =
x
+ y; which adds the value of operands "x" and "y" then stores back to
the variable "x".

40
In this case, both variables must be of the same type

41
 ARRAY IN JAVA

An array is a very common type of data structure where in all elements


must be of the same data type.

Once defined , the size of an array is fixed and cannot increase to


accommodate more elements.

The first element of an array starts with zero.

In simple words it’s a programming construct which helps


replacing this

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.

for(count=0; count<5; count++) {


System.out.println(x[count]);
}

Using and array in your program is a 3 step process -


1) Declaring your Array
2) Constructing your Array
3) Initializing your Array

Syntax for Declaring Array Variables

<elementType>[] <arrayName>;
or
<elementType> <arrayName>[];

Example:

int intArray[]; // Defines that intArray is an ARRAY variable of


which will store integer values
int []intArray;

43
Constructing an Array

<arrayName> = new <elementType>[<noOfElements>];


Example:
intArray = new int[10]; // Defines that intArray will store 10
integer values

Declaration and Construction combined

int intArray[] = new int[10];

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

Declaring and Initializing an Array


<elementType>[] <arayName> = {<arrayInitializerCode>};
Example:
int intArray[] = {1, 2, 3, 4}; // Initilializes an integer array of
length 4 where the first element is 1 , second element is 2 and so
on.

Assignment: First Array Program


Step 1) Copy the following code into a editor

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

Step 3)If x is a reference to an array, x.length will give you the


length of the array.
Uncomment line #10 . Save , Compile & Run the code.Observe the
Output

Step 4)Unlike C, Java checks the boundary of an array while


accessing an element in it. Java will not allow the programmer to
exceed its boundary.
Uncomment line #11 . Save , Compile & Run the code.Observe the
Output

Step 5) ArrayIndexOutOfBoundsException is thrown. In case of C ,


the same code would have shown some garbage value.
45
arrays are passed by reference

Arrays are passed to functions by reference, or as a pointer to the


original. This means anything you do to the Array inside the
function affects the original.

multidimensional arrays

Multidimensional arrays, are arrays of arrays.

To declare a multidimensional array variable, specify each


additional index using another set of square brackets.
Ex: int twoD[ ][ ] = new int[4][5] ;

When you allocate memory for a multidimensional array, you


need only specify the memory for the first (leftmost) dimension.
You can allocate the remaining dimensions separately.

In Java the length of each array in a multidimensional array is


under your control.
Ex:
int twoD[][] = new int[4][];
twoD[0] = new int[5];
twoD[1] = new int[6];
twoD[2] = new int[7];
twoD[3] = new int[8];

array of Objects

46
It is possible to declare array of reference variables.
Syntax:
Class <array_name> = new Class[array_length]

Assignment: To create Array Of Objects


Step 1) Copy the following code into a editor
class Account{
int a;
int b;
public void setData(int c,int d){
a=c;
b=d;
}
public void showData(){
System.out.println("Value of a ="+a);
System.out.println("Value of b ="+b);
}
}

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

The following methods translate floating point values to integer values,


altho these values may still be stored in a double.

double Math.floor(d) Returns the closest integer-valued


double which is equal to or less than d.
double Math.ceil(d) Returns the closest integer-valued
double which is equal to or greater
than d.
double Math.rint(d) Returns the closest integer-valued
double to d.
long Math.round(d) Returns the long which is closest in
value to the double d.
int Math.round(f) Returns the int which is closest in value
to the float f.
Random Numbers
double Math.random() Returns a number x in the range, 0.0 <=
x < 1.0

*********all the best*********

51

You might also like