You are on page 1of 31

Chapter - 1

Introduction to OOPs Concept

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

What is OOPs Concept?


Object-oriented programming is a core of Java Programming, which is used for
designing a program using classes and objects. OOPs, can also be characterized
as data controlling for accessing the code. In this
approach, programmers define the data type of a data structure and the
operations that are applied to the data structure.

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.

Q1. Why object is called as Instance of a class?


Q2. Why class is called as composite data type?
Q3. Why class is called as user defined data type?

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.

int a=10, b=20;


int c=a+b;
c is allotted with the value at the time of execution of a program. It represents
dynamic binding.
Chapter 2
History and development of Java.

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

In java, everything is an object which has some data and behaviour.


Java can be easily extended as it is based on Object Model.

3) Robust

Java makes an effort to eliminate error prone codes by emphasizing


mainly on compile time error checking and runtime checking. But the
main areas which Java improved were Memory Management and
mishandled Exceptions by introducing automatic Garbage
Collector and Exception Handling.

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.

On compilation Java program is compiled into bytecode. This bytecode


is platform independent and can be run on any machine, plus this
bytecode format also provide security. Any machine with Java Runtime
Environment can run Java Programs.
5) Secure

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

Java multithreading feature makes it possible to write program that


can do many tasks simultaneously. Benefit of multithreading is that it
utilizes same memory and other resources to execute multiple threads
at the same time, like While typing, grammatical errors are checked
along.

7) Architectural Neutral

Compiler generates bytecodes, which have nothing to do with a


particular computer architecture, hence a Java program is easy to
intrepret on any machine.
8) Portable
Java Byte code can be carried to any platform. No implementation
dependent features. Everything related to storage is predefined,
example: size of primitive data types

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++.

Important terms used in


Java Programming Language
Interpreter
an Interpreter is a computer program that converts the high-level
program statement into Assembly-level language. It converts the code
into machine code when the program is run.

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.

// statement to understand token in Java

int m= k + 50 ;

int is a data type


m is a identifier
= is a assignment operator
K is a identifier
+ is a arithmetical operator
50 is a integer literal
; is a separator

There are 7 types of tokens in Java


1. Literal
2. Identifiers
3. Punctuators
4. Seperators
5. Keyword
6. Operator
7. Assignment operator

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:

abstract assert boolean break byte


case catch char class continue
default do double else enum
extends final finally float for
if implements import instanceof int
interface long native new null
package private protected public return
short static strictfp super switch
synchronised this throw throws transient
try void volatile while const

Identifiers

A method name, class name, variable name, or label is an identifier in


Java. The user typically defines these. The identifier names cannot be
the same as any reserved keyword. Let's see an example to understand
identifiers:

public class Test


{
public static void main(String[] args)
{
int num = 10;
}
}

Identifiers present in the above program are:

Test: The name of the class.


main: The name of a method.
String: A predefined class name.
args: A variable name.
num: A variable name.

There are rules for naming identifiers.


 The characters allowed are [A-Z], [a-z], [0-9], _ and $.
 Identifiers are case-sensitive. That is, “ninja” is not the same as
“NINJA”.
 Identifier names should not start with a digit. For example,
“007IamNinja” is an invalid identifier.
 Whitespace is not allowed inside an identifier.
 Keywords can’t be used as an identifier.

There are some naming conventions in Java

Naming conventions are used by Java developers for good


programming practice. These naming conventions are good
but its violation does not result an error.
 All class name must begin with Capital letter. Example String,
System etc…
 All function name must begin with a small letter and each
subsequent word should start with a capital letter. Example
equalsIgnoreCase(), isLetterOrDigit() etc….
 All constant variable should be in Capital Letter. Example PI.
Literals
Literals represent fixed values in a source code. They are also known as
constants.
There are Six types of literals in Java:
 Integer
 Floating Point
 Boolean
 Character
 String
 Null
Type Example
int 22
double 25.08
boolean true / false
char ‘N’ (always enclosed within single quotes)
string “Coding Ninjas” (always enclosed within double quotes)
NULL ‘\0’ (used for array and string termination)

Operators

As the name suggests, operators perform operations between different entities.


Whenever the compiler sees an operator, it tokenizes it and proceeds further.
Java has other operators based on their functionality. In total, there are eight
types of operators in Java.
Let's see these operators along with their examples.
Operator Examples
Arithmetic +. - . * , / , %
Assignment =. += , - = ,*=, /=
Unary ++ , -- ,≠
Logical &&, ||
Relational ==, ≠, ≥, ≤
Ternary condition?stat1:stat2
Bitwise &,|,~,^
Shift >>,<<,>>>

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.

 Parenthesis (): Used for function calls and parameters.

 Comma (,): These separate statements. For example, separate parameters.

 Semicolon ( : ): It invokes the initialization list.

 Asterisk (*): This is used to generate pointer variables.

 Assignment operator (=): It assigns values to variables. For example, a=10, here
we are giving value 10 to variable 'a'.

Java Data Types


As explained in the previous chapter, a variable in Java must be a specified data type:

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:

 Primitive data types -


includes byte, short, int, long, float, double, boolean and char
 Non-primitive data types - such as String, Arrays and Classes (you
will learn more about these in a later chapter)

Primitive Data Types


A primitive data type specifies the size and type of variable values, and it has no additional
methods.

There are eight primitive data types in Java:

Data Default Wrapper


Size Description
Type Values class

1 Stores whole numbers from -128 to 127 or [


byte 0 Byte
byte ± (27) ]

2 Stores whole numbers from -32,768 to


short 0 Short
bytes 32,767or [±(215) ]

4 Stores whole numbers from -2,147,483,648


int 0 Integer
bytes to 2,147,483,647± (231)

Stores whole numbers from -


8
long 9,223,372,036,854,775,808 to 0 Long
bytes
9,223,372,036,854,775,807or [ ± (2308) ]

4 Stores fractional numbers. Sufficient for


float 0.0 Float
bytes storing 6 decimal digits
8 Stores fractional numbers. Sufficient for
double 0.0 Double
bytes storing 15 decimal digits

boolean 1 bit Stores true or false value false Boolean

2 Stores a single character/letter or ASCII


char ‘\U0000’ Character
bytes values

Operator Precedence Table


The following table describes the precedence and associativity of operators
used in Java.

Precedence Operator Type

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

10 << Bitwise left shift


>> Bitwise right shift with sign extension
>>> Bitwise right shift with zero extension

9 < Relational less than


<= Relational less than or equal
> Relational greater than
>= Relational greater than or equal
instanceof Type comparison (objects only)

8 == Relational is equal to
!= Relational is not equal to

7 & Bitwise AND

6 ^ Bitwise exclusive OR

5 | Bitwise inclusive OR

4 && Logical AND

3 || Logical OR

2 ?: Ternary conditional

1 (Lowest) = Assignment
+= Addition assignment
-= Subtraction assignment
*= Multiplication assignment
/= Division assignment
%= Modulus assignment

Type Casting

Type Conversion (Implicit Type Casting)


Type conversion is a process in which the data type is automatically converted
into another data type. The compiler does this automatic conversion at compile
time. If the source and destination data types are compatible, then automatic
type conversion takes place.
For type conversion to take place, the destination data type must be larger than
the source type. In short, the below flow chart has to be followed.

Flow chart for Type Conversion


In type conversion, the source data type with a smaller size is converted into
the destination data type with a larger size.

Type Casting (Explicit Type Casting)


Type casting is a process in which the programmer manually converts one data
type into another data type. For this the casting operator (), the parenthesis is
used. Unlike type conversion, the source data type must be larger than the
destination type in type casting. The below flow chart has to be followed for
successful type casting.

Flow chart for Type Casting

In type casting, the source data type with a larger size is converted into the
destination data type with a smaller size.

Introduction to errors in Java


The basic types of errors: syntax errors, run-time errors, and logical
errors. Each of the different types has different characteristics and
being able to understand these characteristics can help the debug
process. Let’s take a look at each of these one at a time.

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 ‘:’.

Introduction to Increment and Decrement Operators


The increment (++) and decrement (–) operators are unary operators in Java,
which means they operate on a single operand. They are used to increase or
decrease the value of an integer, floating-point, or character variable by 1.
These operators can be applied in two ways: prefix and postfix.

Prefix Increment and Decrement Operators

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.

Examples of Increment and Decrement Operators


Prefix Increment Operator

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 incremented by 1, and then the result is


assigned to b. The output will be:
a: 6, b: 6
Postfix Increment Operator

Now, let's look at an example of the postfix 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

Here's an example of the prefix decrement operator.


int a =5;
int b =--a;
System.out.println("a: "+ a +", b: "+ b);

In this example, the value of a is decremented by 1, and then the result is


assigned to b. The output will be:
a: 4, b: 4
Postfix Decrement Operator

Lastly, let's see an example of the postfix decrement 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
decremented by 1. The output will be:
a: 4, b: 5

Use Cases of Increment and Decrement Operators


Increment and decrement operators are commonly used in loops and other
control structures. They can simplify the code and make it more readable.

Using Increment Operator in a Loop

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

In this example, the variable i is incremented by 1 in each iteration of the loop


until it reaches the length of the array.

Using Decrement Operator in a Loop

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:

List of Java Escape Characters


In Java, there is a total of eight escape sequences that are described in the
following table.

Escape Description
Characters

\t It is used to insert a tab in the text at this point.

\' It is used to insert a single quote character in the text at this


point.

\" It is used to insert a double quote character in the text at this


point.

\r It is used to insert a carriage return in the text at this point.

\\ It is used to insert a backslash character in the text at this


point.

\n It is used to insert a new line in the text at this point.

\f It is used to insert a form feed in the text at this point.

\b It is used to insert a backspace in the text at this point.


Converting Arithmetical Expression to Java Expression
1. Write a Java expression for the following: 5/10+ x5 + 4/ bx3
Ans. 5.0/10.0 + Math.pow(x,5) + 4.0/ b * Math.pow(x, 3)
2. Write the Java expression for ax5 + bx3 + c
Ans. a * Math.pow(x, 5) + b * Math.pow(x, 3) + c
3. Write down java expression for :
T = square root (A2 + B2 + C2)
Ans. double T = Math.sqrt(Math.pow(A, 2) + Math.pow(B, 2) + Math.pow(C, 2));
4. Write the Java expression for:
(A2 + B2 )/ 2ab
Ans. (Math.pow(a, 2) + Math.pow(b, 2)) / (2 * a * b)
5. Write the java expressions for each of the following:
(i) x = e|2x – 4x|
(ii) s=√(sin(a) + tan(a) – e2x)
Ans:
(i) x = Math.exp(Math.abs(2*x-4*x))
(ii) s = Math.sqrt(Math.sin(a)+Math.tan(a)-Math.exp(2*x))
6. Write an expression for:

Ans. (x + Math.pow (y, 2)) / (Math.cbrt(3)+y)


7. Write Java expression for following.

Ans. x= a*b+(1.0/2.0)*c*Math.pow(b,2);
8. Write an expression in java for:

Ans. A= ( Math.pow((a+b),2 ) * Math.pow((a-b),3)) / 2*a*b


9. Write an expression in java for:

Ans. X=Math.abs(A)+ Math.abs(B) +(Math.pow(A,3)+Math.pow(B,4))


10.Write an expression in java for:

Ans. x=Math.sqrt ((2 * Math.pow(x,3) + 3*Math.pow(y,2) ) / (x+y)


11.Write an expression in java for:

Ans. A= Math.sqrt(Math.pow(p,x) + Math.pow(q,2));


12.Write equivalent Java expressions for the following:
Ans.
1. Math.sqrt(a+b)
2. 1/3.0*Math.pow(a,3)+1/3.0*Math.pow(b,3)
13.Write equivalent Java expressions for the following:

Ans.
1. s=u*t+1/2.0*a*Math.pow(t,2)
2. d=Math.sqrt(l*l+b*b);

14.Write equivalent Java expressions for the following:

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

18.Write equivalent Java expressions for the following:


ax5+bx3+c
Ans. a*Math.pow(x,5)+b*Math.pow(x,3)+c

Scanner Class in Java




In Java, Scanner is a class in java.util package used for obtaining the input of the
primitive types like int, double, etc. and strings.
Using the Scanner class in Java is the easiest way to read input in a Java
program, though not very efficient if you want an input method for scenarios
where time is a constraint like in competitive programming.

Java Scanner Input Types


Scanner class helps to take the standard input stream in Java. So, we need some
methods to extract data from the stream. Methods used for extracting data are
mentioned below:
Method Description

nextBoolean() Used for reading Boolean value

nextByte() Used for reading Byte value

nextDouble() Used for reading Double value

nextFloat() Used for reading Float value

nextInt() Used for reading Int value


Method Description

nextLine() Used for reading Line value

nextLong() Used for reading Long value

nextShort() Used for reading Short value

next().charAt(0) Used for character input

You might also like