Notes
Notes
Notes
POP OOPs
POP lays emphasis on function rather OOPs lays emphasis on data rather
than on data than on functions
POP decides how the problem will be OOPs decides what the problem is.
solved
It is a top down approch of It is a zig zag approch of programming.
programming
Example C Example C++ , Java
Principles of OOPs
OR
Elements of OOPs
1. Classs
2. Object
3. Encapsulation
4. Data abstraction
5. Data hiding
6. Polymorphism
7. Inheritance
8. Data hiding
Objects:
In Java, an object is more than just a runtime entity; it’s the embodiment of a
class. These objects mirror real-world entities, complete with both state and
behavior. Think of a ‘Car’ object based on a ‘Car’ class. It possesses attributes
like color, brand, and speed, along with behaviors like ‘accelerate’ and ‘brake’.
This is where Java OOP concepts come to life.
Classes:
A class in Java serves as a blueprint for creating objects. It bundles data
(attributes) and behavior (methods) that define the object. Consider a ‘Car’
class; it defines attributes like color and methods like ‘accelerate()’. Essentially,
a class is a template that characterizes what can be instantiated as an object,
exemplifying OOPs concepts.
Data Abstraction:
Abstraction in Java involves concealing complexity while exposing only the
essential aspects. It’s realized through abstract classes and interfaces. For
instance, a ‘Vehicle’ interface declares a ‘move()’ method, but the actual
implementation is left to classes like ‘Car’ or ‘Bike’. This focus on “what an
object does” rather than “how it does it” is a core OOPs concept in Java.
Data Hiding
Data hiding means hiding the internal data within the class to prevent its direct
access from outside the class. Encapsulation promotes Data hiding using access
specifiers (public / private / protected ).
Inheritance:
Inheritance is a mechanism where a new class (subclass) derives attributes and
methods from an existing class (superclass). This fosters code reusability and
establishes a hierarchical relationship between classes. For example, an
‘ElectricCar’ class can inherit traits from the ‘Car’ class, showcasing the
practicality of Java OOPs concepts.
Polymorphism:
Polymorphism allows Java methods and objects to assume multiple forms. It
finds common use in method overloading (same method name, different
parameters) and method overriding (same method name and parameters in
subclass as in parent class). Consider a ‘draw()’ method implemented differently
in ‘Circle’, ‘Square’, and ‘Triangle’ classes as a prime example of polymorphism
in Java.
Encapsulation:
Encapsulation is a pivotal OOPs principle in Java. It entails bundling data
(attributes) and code (methods) into a cohesive unit. Moreover, it limits direct
access to an object’s components, preventing inadvertent interference.
Techniques like using private variables and offering public getter and setter
methods exemplify Java OOPs concepts put into practice.
Dynamic binding
In dynamic binding , process is executed at the time of execution of the
program.
History of Java:
James Gosling initiated the Java language project in June 1991 for use
in one of his many set-top box projects. The language, initially called
Oak after an oak tree that stood outside Gosling's office, also went by
the name Green and ended up later being renamed as Java, from a list
of random words.
Sun released the first public implementation as Java 1.0 in 1995. It
promised Write Once, Run Anywhere(WORA), providing no-cost run-
times on popular platforms.
On 13 November 2006, Sun released much of Java as free and open
source software under the terms of the GNU General Public License
(GPL).
On 8 May 2007, Sun finished the process, making all of Java's core code
free and open-source, aside from a small portion of code to which Sun
did not hold the copyright.
In 2010 , Oracle Corporation purchsed Sun Micro Systems. Now, Java
Programming Language is a part of Oracle Corp.
Features of Java
The prime reason behind creation of Java was to bring portability and
security feature into a computer language. Beside these two major
features, there were many other features that played an important
role in moulding out the final form of this outstanding language. Those
features are :
1) Simple
Java is easy to learn and its syntax is quite simple, clean and easy to
understand.The confusing and ambiguous concepts of C++ are either
left out in Java or they have been re-implemented in a cleaner way.
2) Object Oriented
3) Robust
4) Platform Independent
Unlike other programming languages such as C, C++ etc which are
compiled into platform specific machines. Java is guaranteed to be
write-once, run-anywhere language.
When it comes to security, Java is always the first choice. With java
secure features it enable us to develop virus free, temper free system.
Java program always runs in Java runtime environment with almost
null interaction with system OS, hence it is more secure.
6) Multi Threading
7) Architectural Neutral
9) High Performance
Java is an interpreted language, so it will never be as fast as a compiled
language like C or C++. But, Java enables high performance with the
use of just-in-time compiler.
10) Distributed
Java is also a distributed language. Programs can be designed to run on
computer networks. Java has a special class library for communicating
using TCP/IP protocols. Creating network connections is very much
easy in Java as compared to C/C++.
Compiler
A compiler in Java translates the entire source code into a machine-
code file or any intermediate code, and that file is then executed. It is
platform-independent. Java compiler can be operated by using the
“Javac.exe” command from the command prompt.
Byte code
A bytecode is basically an intermediate code generated by the
compiler after the compilation of its source code.
JVM
A Java virtual machine (JVM) is a virtual machine that enables a
computer to run Java programs as well as programs written in other
languages that are also compiled to Java bytecode.
BlueJ
BlueJ is an integrated development environment (IDE) for the Java
programming language, developed mainly for educational purposes,
but also suitable for small-scale software development. It runs with the
help of Java Development Kit (JDK).
Chapter 3
Data Types in Java
What is Token in Java?
They are the basic building blocks of any java program. As human
body is made of cells, in the same way java program is made up of
tokens.
Tokens are the smallest unit of the Java program. The compiler breaks down the
lines of code into tokens. Let's see an example to understand tokens.
int m= k + 50 ;
Keywords
Keywords are reserved words in programming languages. These are
used to indicate predefined terms and actions in a program. As a result,
these words are not allowed to be used as names of variables or
objects. It is case-sensitive and always written in lowercase. Java has
the following keywords:
Identifiers
Operators
Separators
These are the special symbols used to separate java tokens. These are
sometimes called punctuators. The separators have special meaning and thus
should not be used for anything else.
Brackets []: These are used to define arrays and represent single and multi-
dimension subscripts.
Braces {}: These mark the start and end of multi-line code blocks.
Assignment operator (=): It assigns values to variables. For example, a=10, here
we are giving value 10 to variable 'a'.
Example
Int myNum=5; // Integer (whole number)
Float myFloatNum=5.99f; // Floating point number
Char myLetter='D'; // Character
Boolean myBool=true; // Boolean
String myText="Hello"; // String
Data types are divided into two groups:
15 (Highest) () Parentheses
[] Array subscript
· Member selection
14 ++ Unary post-increment
-- Unary post-decrement
13 ++ Unary pre-increment
-- Unary pre-decrement
+ Unary plus
- Unary minus
! Unary logical negation
~ Unary bitwise complement
(type) Unary type cast
12 * Multiplication
/ Division
% Modulus
11 + Addition
- Subtraction
8 == Relational is equal to
!= Relational is not equal to
6 ^ Bitwise exclusive OR
5 | Bitwise inclusive OR
3 || Logical OR
2 ?: Ternary conditional
1 (Lowest) = Assignment
+= Addition assignment
-= Subtraction assignment
*= Multiplication assignment
/= Division assignment
%= Modulus assignment
Type Casting
In type casting, the source data type with a larger size is converted into the
destination data type with a smaller size.
1. Syntax Errors
The first type of error we are going to look at is a syntax error. The
syntax of Java is the rules that you need to follow for a properly
formatted code. Syntax errors are often spotted as you type. Syntax
errors can often get caught before attempting to compile and run the
program, but if you do attempt to compile and run, the program will
crash and fail to compile.
2. Run-time Errors
The next error type to examine is run-time errors. As the name implies,
these are errors that are only produced as the program runs. These
errors have code that compiles correctly and may run correctly under
some situations but does something either unexpected or incorrect.
Examples of run-time errors can be a user entering a String when the
program expects a number, looping too far and getting an index out of
bounds error, etc.
3. Logic Errors
The last type of error that we will examine is a class known as Logic
Errors. Logic errors are different from the other error types because
these errors do not cause any type of error from Java. Programs with
logic errors will compile, run, and finish successfully, however they will
not produce the correct results.
Let’s take a look at the example above. The program asks the user for
an input. If the user inputs the number 10, the program will print out
zero since 5 / 10 = 0.5, but since both values are integers, the value
gets truncated and the incorrect value is printed to the screen.
Unary Operators
Unary operators need only one operand. They are used to increment,
decrement, or negate a value.
– : Unary minus, used for negating the values.
+ : Unary plus indicates the positive value (numbers are positive
without this, however). It performs an automatic conversion to int
when the type of its operand is the byte, char, or short. This is called
unary numeric promotion.
++ : Increment operator, used for incrementing the value by 1. There
are two varieties of increment operators.
Post-Increment: Value is first used for computing the result
and then incremented.
Pre-Increment: Value is incremented first, and then the result
is computed.
– – : Decrement operator, used for decrementing the value by 1.
There are two varieties of decrement operators.
Post-decrement: Value is first used for computing the result
and then decremented.
Pre-Decrement: The value is decremented first, and then the
result is computed.
! : Logical not operator, used for inverting a boolean value.
Ternary operator
The ternary operator is a shorthand version of the if-else statement. It has
three operands and hence the name Ternary.
The general format is:
condition ? if true : if false
The above statement means that if the condition evaluates to true, then
execute the statements after the ‘?’ else execute the statements after the ‘:’.
In the prefix form, the operator is placed before the operand. The value of the
operand is incremented or decremented first, and then the result is used in the
expression. The syntax for prefix increment and decrement operators is as
follows:
++variable;
--variable;
Postfix Increment and Decrement Operators
In the postfix form, the operator is placed after the operand. The value of the
operand is used in the expression first, and then it is incremented or
decremented. The syntax for postfix increment and decrement operators is as
follows:
variable++;
variable--;
Now, let's dive deeper into these operators and see how they work with
examples.
Let's start with a simple example to understand the prefix increment operator.
int a =5;
int b =++a;
System.out.println("a: "+ a +", b: "+ b);
In this example, the value of a is used in the expression first, and then it is
incremented by 1. The output will be:
a: 6, b: 5
Prefix Decrement Operator
In this example, the value of a is used in the expression first, and then it is
decremented by 1. The output will be:
a: 4, b: 5
For instance, you can use the increment operator in a for loop to iterate through
an array.
int[] numbers ={1,2,3,4,5};
for(inti=0;i<numbers.length;i++){
System.out.println(numbers[i]);
}
Similarly, you can also use the decrement operator in a loop to iterate through
an array in reverse order.
int[] numbers ={1,2,3,4,5};
for(inti=numbers.length-1;i>=0;i--){
System.out.println(numbers[i]);
}
In this example, the variable i is decremented by 1 in each iteration of the loop
until it reaches 0.
Escape Sequences in Java
A character with a backslash (\) just before it is an escape sequence or escape
character. We use escape characters to perform some specific task. The total
number of escape sequences or escape characters in Java is 8. Each escape
character is a valid character literal. The list of Java escape sequences:
Escape Description
Characters
Ans. x= a*b+(1.0/2.0)*c*Math.pow(b,2);
8. Write an expression in java for:
Ans.
1. s=u*t+1/2.0*a*Math.pow(t,2)
2. d=Math.sqrt(l*l+b*b);
Ans.
1. (-b+Math.sqrt(b*b-4*a*c))/(2*a) and (-b-Math.sqrt(b*b-4*a*c))/(2*a)
2. (Math.pow(a,3)+Math.pow(b,3))/ (Math.pow(a,3)-Math.pow(b,3))
15.Write equivalent Java expressions for the following:
Ans.
1. Math.abs((a*a*a+b*b*b)/(a*a*a-b*b*b))
2. Math.cbrt((a+b)/(a*b))
16.Write equivalent Java expressions for the following:
Ans.
1. Math.pow(a+b,n)/Math.sqrt(3+b)
2. Z=(5*x*x*x+2*y)/(x+y);
17.Write equivalent Java expressions for the following:
Ans.
1. (a*a+b*b)/(a+b)
2. T=Math.sqrt(A*A+B*B+C*C);