Oop Unit-1&2
Oop Unit-1&2
Oop Unit-1&2
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.
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.
(properties) and things they can do (methods). You can also create relationships
between various objects and data structures.
• 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.
Q2 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
double 64 bits
float 32 bits
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:
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:
underscore ( _ ) symbol
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".
long enough to be descriptive, but not too long. Also keep in mind:
Q6 OPERATORS IN JAVA
Arithmetic operator
Unary Operator
Comparison Operator
Short-Circuit Logical 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.
- subtraction operator
* multiplication operator
/ division operator
% remainder operator
operators.
class ArithmeticDemo {
System.out.println(result);
System.out.println(result);
System.out.println(result);
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
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;"
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.
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
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:
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.
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.
boolean result = (2>1); result = !result System.out.println("2 is geater than 1: " + result);
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:
operator meaning
== equal to
!= 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 shows
how you can take advantage of short-circuit logical evaluation to be sure that a division
operation will be valid before evaluating it:
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:
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
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.
distance b
distance b
0101(5)<< 1 1010(10)
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 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
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
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:
(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
Unit 2
The if statement
Syntax:
if(condition)
Example:
=====================================================
Output:
aNumber is equal to 5
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)
else
(aNumber == 5)
=================================================
====== Output:
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)
else if(Condition2)
}
Example:
int aNumber = 7;
if (aNumber == 5)
else if (aNumber == 7)
=====================================================
====== Output:
aNumber is equal to 7
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)
break;
break;
break;
default:
Example:
Example:
int aNumber = 7;
switch(aNumber)
{
break;
break;
break;
break;
=================================================================
== Output:
aNumber is equal to 7
Q3 Explain For loop ,While , and do-while 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.
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
declaration part of the loop. The increment/decrement statement is the part of the loop which
will eventually stop the loop from running.
Syntax:
a_variable_increment/decrement)
code to be executed;
Example:
for(int a = 1; a < 11; 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.
• 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.
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)
Example:
int num = 0;
================================================ 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 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
} while (condition);
Example:
int num = 5;
do{
=================================================== 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 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:
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:
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.
Example:
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