Java_BSc(H)_Unit-1
Java_BSc(H)_Unit-1
They have states and behaviour. These objects always correspond to things found in the
real world, i.e., real entities. So, they are also called a run-time entity of the world.
When we treat animals as objects, it has states like colour, name, breed etc.,
Class
A class can also be defined as a blueprint from which you can create an individual object.
Class doesn't consume any space.
EXAMPLE.
Person Object
Name Data
Basic Pay
Salary ( ) Methods
Tax ( )
R EPRESENTATION OF AN O BJECT
The wrapping up of data and methods into a single unit (called class) is known as
encapsulation. Data encapsulation is the most striking feature of a class. The data is not
accessible to the outside world and only these methods, which are wrapped in the class, can
access it. These methods provide the interface between the object’s data and the program.
Data
Information Information
and
Method
E NCAPSULATION – O BJECTS AS “ BLACK BOXES ”
Abstraction refers to the act of representing essential features without including the
background details or explanation.
Inheritance:
Inheritance is the process by which objects of one class acquire the properties of objects
of another class. Inheritance supports the concept of hierarchical classification.
Bird
Attributes:
Feathers, Lay
Polymorphism
Polymorphism is another important OOP concept. Polymorphism means the ability to
take more than one form. For example, an operation may exhibit different behaviour in
different instances. The behaviour depends upon the types of data used in the operation.
Shape
Draw()
POLYMORPHISM
Dynamic Binding:
Binding refers to the linking of a procedure call to the code to be executed in response
to the call. Dynamic binding means that the code associated with a given procedure call is
not known until the time of the call at runtime.
Message Communication:
An object-oriented program consists of a set of objects that communicate with each
other. The process of programming in an object-oriented language, therefore, involves the
following basic steps:
1) Creating classes that define objects and their behaviour.
RAMAKRISHNAREDDY NANDYALA 9848740143 2
OBJECT ORINTED PROGRAMMING USING JAVA UNIT-1
Object 1
Object 5 Object 2
Object 4 Object 3
*******************************************************************
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Interpreted
8. High Performance
9. Multithreaded
10. Distributed
11. Dynamic
Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand. According
to Sun Microsystem, Java language is a simple programming language because:
o Java syntax is based on C++ (so easier for programmers to learn it after C++).
o Java has removed many complicated and rarely-used features, for example, explicit
pointers, operator overloading, etc.
Object-oriented
Java is true Object-Oriented Language. Java comes with a set of classes, which we can use
in our programs. The object model in Java is simple and easy to extend.
Platform Independent
Java combines with both compiler and Interpreter. First java compiler translates the source
code into byte codes as intermediate files. In second, Java Interpreter generates the byte code
into machine code. It can be ported to any platform without any problem. I.e. Java programs
can be easily moved from one computer to another. This is the one of major advantages of
Java.
Secured
All the Java that provides the user is nothing but secured programming techniques. Java
implements a separate security manager so that the user can be benefited in implementing the
objects with ease of use.
Robust
Portable
Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't
require any implementation.
High-performance
Java is faster than other traditional interpreted programming languages because Java
bytecode is "close" to native code. It is still a little bit slower than a compiled language
(e.g., C++). Java is an interpreted language that is why it is slower than compiled languages,
e.g., C, C++, etc.
Distributed
Java is designed for distributed environments like Internet. Java objects are distributed
over the network and get executed remotely on demand.
Multi-threaded
Dynamic
Java is a dynamic language. It supports the dynamic loading of classes. It means classes are
loaded on demand. It also supports functions from its native languages, i.e., C and C++.
*************************************************************************
o Loads code
o Verifies code
o Executes code
o Provides runtime environment
JVM Architecture
Let's understand the internal architecture of JVM. It contains classloader, memory area,
execution engine etc.
1) Classloader
Classloader is a subsystem of JVM which is used to load class files. Whenever we run the
java program, it is loaded first by the classloader.
2) Class(Method) Area
Class(Method) Area stores per-class structures such as the runtime constant pool, field and
method data, the code for methods.
3) Heap
4) Stack
Java Stack stores frames. It holds local variables and partial results, and plays a part in method
invocation and return.
Each thread has a private JVM stack, created at the same time as thread.
A new frame is created each time a method is invoked. A frame is destroyed when its method
invocation completes.
PC (program counter) register contains the address of the Java virtual machine instruction
currently being executed.
7) Execution Engine
It contains:
Java Native Interface (JNI) is a framework which provides an interface to communicate with
another application written in another language like C, C++, Assembly etc. Java uses JNI
framework to send output to the Console or interact with OS libraries.
*************************************************************************
Types of Tokens
Java token includes the following:
o Keywords
o Identifiers
o Literals
o Operators
o Separators
o Comments
Keywords: These are the pre-defined reserved words of any programming language.
Each keyword has a special meaning. It is always written in lower case. Java provides the following
keywords:
*********
Identifier:
Identifiers are used to name a variable, constant, function, class, and array. It usually defined by
the user. It uses letters, underscores, or a dollar sign as the first character. The label is also known
as a special kind of identifier that is used in the goto statement. Remember that the identifier name
must be different from the reserved keywords. There are some rules to declare identifiers are:
o The first letter of an identifier must be a letter, underscore or a dollar sign. It cannot start
with digits but may contain digits.
o The whitespace cannot be included in the identifier.
o Identifiers are case sensitive.
1. PhoneNumber
2. PRICE
3. radius
4. a
5. a1
6. _phonenumber
7. $circumference
8. jagged_array
9. 12radius //invalid
********
Literals in Java
Literals have a constant value and a fixed data type and are often known as constants in
Java. Literals are assigned to a variable to provide a value to the variable.
Generally, there are 5 types of literals that can be further expanded into various other
literals.
Integer Literal
Float/Double Literal
Character Literal
Boolean Literal
String Literal
Integer Literal:
Integer literals are basically a number sequence that doesn’t contain any decimal point in
between them.
They are integers having a base value of 10; i.e; containing values between 0 to 9. It can be
a positive value(+) or a negative value(-) but it cannot contain any point in between them.
Example: 1000, 1234, +78, -82, etc.
Floating Point Literal:
Floating-point literals are values that contain a decimal point in between them. Floating-
point literals are generally double data type by default.
Example:
float val_double=1.7732; //By default the compiler assigns double datatype.
Character Literal:
Character Literals in java are represented with a single quote. Character literal contains only
one character.
Example
char ch = ‘A’;
Boolean Literal:
A boolean literal is a literal that contains only two values true and false. It is declared using
the keyword boolean. It is a very useful literal to declare flag variables in different
programs to terminate a looping sequence.
String Literal:
Two or more characters which is enclosed with in a double quotation mark that is called as
string literal.
Operators
In programming, operators are the special symbol that tells the compiler to perform a special
operation. Java provides different types of operators that can be classified according to the
functionality they provide. There are eight types of operators in Java, are as follows:
o Arithmetic Operators
o Assignment Operators
o Relational (Comparison) Operators
o Increment/Decrement (Unary) Operators
o Logical Operators
o Conditional (Ternary) Operators
o Bitwise Operators
o Special Operators
Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations on variables and data. For
example,
a + b;
Here, the + operator is used to add two variables a and b. Similarly, there are various other
arithmetic operators in Java.
Operator Operation
+ Addition
- Subtraction
* Multiplication
/ Division
Assignment Operators
Assignment operators are used in Java to assign values to variables. For example,
int age;
age = 5;
Here, = is the assignment operator. It assigns the value on its right to the variable on its left.
That is, 5 is assigned to the variable age.
Let's see some more assignment operators available in Java.
= a = b; a = b;
+= a += b; a = a + b;
-= a -= b; a = a - b;
*= a *= b; a = a * b;
/= a /= b; a = a / b;
%= a %= b; a = a % b;
Relational operators are used to comparison between two operands. For example,
Here, < operator is the relational operator. It checks if a is less than b or not.
It returns either true or false.
Operator Description Example
Logical operators
RAMAKRISHNAREDDY NANDYALA 9848740143 13
OBJECT ORINTED PROGRAMMING USING JAVA UNIT-1
Logical operators are used to form compound conditions by combining two or more
relational expressions.
Operator Meaning
&& Logical AND
|| Logical OR
! Logical NOT
Conditional operator
The ? : is a ternary operator available in Java. The operator is used to construct
conditional expression in Java.
Syntax: exp1 ? exp2 : exp3;
The exp1 is evaluated first. If it returns true, the exp2 is evaluated, else the exp3 is
evaluated.
Ex: c = (a>b? a : b );
Bitwise operators
Java has set of bitwise operators to manipulate data at bit level. Bitwise operators may
not be applied for float or double.
Operator Meaning
& Bitwise AND
! Bitwise OR
^ Bitwise exclusive OR
Bitwise one’s
~
complement
<< Shift left
>> Shift right
>>> Shift right with zero fill
Special operators
Java supports special operators such as instanceof operator and member selection
operator.
Instanceof:
It is an object reference operator and returns true if the object on the left side is the
instance of the class given on right side otherwise it returns false.
*********************
Separators
The separators in Java is also known as punctuators. There are different separators in Java,
are as follows:
o Square Brackets []: It is used to define array elements. A pair of square brackets
represents the single-dimensional array, two pairs of square brackets represent the two-
dimensional array.
o Parentheses (): It is used to call the functions and parsing the parameters.
o Curly Braces {}: The curly braces denote the starting and ending of a code block.
o Comma (,): It is used to separate two values, statements, and parameters.
o Assignment Operator (=): It is used to assign a variable and constant.
o Semicolon (;): It is the symbol that can be found at end of the statements. It separates
the two statements.
o Period (.): It separates the package name form the sub-packages and class. It also
separates a variable or method from a reference variable.
***************
Comments
Comments allow us to specify information about the program inside our Java code. Java
compiler recognizes these comments as tokens but excludes it form further processing. The
Java compiler treats comments as whitespaces. Java provides the following two types of
comments:
*************************************************************************
RAMAKRISHNAREDDY NANDYALA 9848740143 15
OBJECT ORINTED PROGRAMMING USING JAVA UNIT-1
But, it is not forced to follow. So, it is known as convention not rule. These conventions are
suggested by several Java communities such as Sun Microsystems and Netscape.
All the classes, interfaces, packages, methods and fields of Java programming language are
given according to the Java naming convention. If you fail to follow these conventions, it
may generate confusion or erroneous code.
The following table shows the popular conventions used for the different identifiers.
*************************************************************************
Documentation Section
The documentation section is an important section but optional for a Java program. It
includes basic information about a Java program. The information includes the author's
name, date of creation, version, program name, company name, and description of the
program. Whatever we write in the documentation section, the Java compiler ignores the
statements during the execution of the program. To write the statements in the documentation
section, we use comments. The comments may be single-line, multi-
line, and documentation comments.
o Single-line Comment: It starts with a pair of forwarding slash (//). For example:
1. /*It is an example of
2. multiline comment*/
o Documentation Comment: It starts with the delimiter (/**) and ends with */. For
example:
Package Statement
The package declaration is optional. It is placed just after the documentation section. In this
section, we declare the package name in which the class is placed. Note that there can
be only one package statement in a Java program. It must be defined before any class and
interface declaration.
We use the keyword package to declare the package name. For example:
package shashish; //where shashish is the package name
Import Statements
The package contains the many predefined classes and interfaces. If we want to use any class
of a particular package, we need to import that class. The import statement represents the
class stored in the other package. We use the import keyword to import the class. It is written
before the class declaration and after the package statement. We use the import statement in
two ways, either import a specific class or import all classes of a particular package. In a Java
program, we can use multiple import statements. For example:
interface car
{
void start();
void stop();
}
Class Definition
In this section, we define the class. It is vital part of a Java program. Without the class, we
cannot create any Java program. A Java program may conation more than one class definition.
We use the class keyword to define the class. The class is a blueprint of a Java program. It
contains information about user-defined methods, variables, and constants. Every Java
program has at least one class that contains the main() method. For example:
For example:
public static void main(String args[ ]) is the most important Java method. When you start
learning java programming, this is the first method you encounter.
public
This is the access modifier of the main method. It has to be public so that java runtime can
execute this method. Remember that if you make any method non-public then it’s not
allowed to be executed by any program, there are some access restrictions applied.
static
When java runtime starts, there is no object of the class present. That’s why the main
method has to be static so that JVM can load the class into memory and call the main
method. If the main method won’t be static, JVM would not be able to call it because there
is no object of the class is present.
void
Java programming mandates that every method provide the return type. Java main method
doesn’t return anything, that’s why it’s return type is void.
main
This is the name of java main method. It’s fixed and when we start a java program, it looks
for the main method.
String args[]
Java main method accepts a single argument of type String array. This is also called as java
command line arguments.
*************************************************************************
1. Primitive data types: The primitive data types include boolean, char, byte, short, int,
long, float and double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces,
and Arrays
The Boolean data type specifies one bit of information, but its "size" can't be defined
precisely.
Example:
Example:
Example:
Example:
Example:
Example:
float f1 = 234.5f
Example:
double d1 = 12.3
Example:
*************************************************************************
Or
Explain scope of variable in java?
A variable is a user defined word it has some storage area.
Or
A variable is a container which holds the value while the Java program is executed. A variable
is assigned with a data type. Variable is a name of memory location. There are three types of
variables in java:
Local Variable
Instance Variable
Static Variable
1) Local Variable
A variable declared inside the body of the method is called local variable. You can use this
variable only within that method and the other methods in the class aren't even aware that the
variable exists.
2) Instance Variable
A variable declared inside the class but outside the body of the method, is called an instance
variable. It is not declared as static
.It is called an instance variable because its value is instance-specific and is not shared
among instances.
3) Static variable
A variable that is declared as static is called a static variable. It cannot be local. You can
create a single copy of the static variable and share it among all the instances of the class.
Memory allocation for static variables happens only once when the class is loaded in the
memory.
public class A
{
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
public static void main(String args[])
{
int data=50;//instance variable
}
}//end of class
*************************************************************************
Type casting
Convert a value from one data type to another data type is known as type casting.
byte -> short -> char -> int -> long -> float -> double
WideningTypeCastingExample.java
Output
In the above example, we have taken a variable x and converted it into a long type. After that,
the long type is converted into the float type.
double -> float -> long -> int -> char -> short -> byte
NarrowingTypeCastingExample.java
{
public static void main(String args[])
{
double d = 166.66;
//converting double data type into long data type
long l = (long)d;
//converting long data type into int data type
int i = (int)l;
System.out.println("Before conversion: "+d);
//fractional part lost
System.out.println("After conversion into long type: "+l);
//fractional part lost
System.out.println("After conversion into int type: "+i);
}
}
Output
Here, we have used the valueOf() method of the Java String class to convert the int type
variable into a string.
Here, we have used the parseInt() method of the Java Integer class to convert a string type
variable into an int variable.
****************************************************************
Conditional control statements are used to change the sequence of program execution based
on the condition.
Decision-Making statements:
As the name suggests, decision-making statements decide which statement to execute and
when. Decision-making statements evaluate the Boolean expression and control the program
flow depending upon the result of the condition provided. There are two types of decision-
making statements in Java, i.e., If statement and switch statement.
1) If Statement:
In Java, the "if" statement is used to evaluate a condition. The control of the program is
diverted depending upon the specific condition. The condition of the If statement gives a
Boolean value, either true or false. In Java, there are four types of if-statements given below.
1. Simple if statement
2. if-else statement
3. if-else-if ladder
4. Nested if-statement
1) Simple if statement:
It is the most basic statement among all control flow statements in Java. It evaluates a Boolean
expression and enables the program to enter a block of code if the expression evaluates to
true.
if(condition) {
statement 1; //executes when condition is true
}
2) if-else statement
The if-else statement is an extension to the if-statement, which uses another block of code,
i.e., else block. The else block is executed if the condition of the if-block is evaluated as
false.
Syntax:
if(condition) {
statement 1; //executes when condition is true
}
else{
statement 2; //executes when condition is false
3) if-else-if ladder:
The if-else-if statement contains the if-statement followed by multiple else-if statements. In
other words, we can say that it is the chain of if-else statements that create a decision tree
where the program may enter in the block of code where the condition is true. We can also
define an else statement at the end of the chain.
if(condition 1) {
statement 1; //executes when condition 1 is true
}
else if(condition 2) {
statement 2; //executes when condition 2 is true
}
else {
statement 3; //executes when all the conditions are false
}
4. Nested if-statement
In nested if-statements, the if statement can contain a if or if-else statement inside another if
or else-if statement.
if(condition 1) {
statement 1; //executes when condition 1 is true
if(condition 2) {
statement 2; //executes when condition 2 is true
}
else{
statement 3; //executes when condition 2 is false
}
}
Switch Statement:
In Java, Switch statements are similar to if-else-if statements. The switch statement contains
multiple blocks of code called cases and a single case is executed based on the variable which
is being switched. The switch statement is easier to use instead of if-else-if statements. It also
enhances the readability of the program.
o The case variables can be int, short, byte, char, or enumeration. String type is also
supported since version 7 of Java
o Cases cannot be duplicate
o Default statement is executed when any of the case doesn't match the value of
expression. It is optional.
o Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, next case is executed.
o While using switch statements, we must notice that the case expression will be of the
same type as the variable. However, it will also be a constant value.
switch (expression){
case value1:
statement1;
break;
.
.
.
case valueN:
statementN;
break;
default:
default statement;
}
Conditional operator (?:):
Conditional operator or also called as ?: operator or ternary operator. This operator is
used instead of block if statement. The general syntax of conditional operator is as:
expr1? expr2: expr3;
Here first of all expr1 is computed, which is a conditional expression. If expr1 is true,
then expr2 will be executed. But if expr1 is false, then expr3 will be executed. Note that expr2
and expr3 are either a single constant value or a single variable or an arithmetic expression.
For example, below is an if statement having a and b two variables as:
a=10; b=5;
if (a>b)
c=a-b;
else
c=b-a;
RAMAKRISHNAREDDY NANDYALA 9848740143 31
OBJECT ORINTED PROGRAMMING USING JAVA UNIT-1
The above if statement can be write by using the conditional operator in a single statement
as:
c= (a>b)? a-b: b-a;
*************************************************************************
In programming, sometimes we need to execute the block of code repeatedly while some
condition evaluates to true. However, loop statements are used to execute the set of
instructions in a repeated order. The execution of the set of instructions depends upon a
particular condition.
In Java, we have three types of loops that execute similarly. However, there are differences
in their syntax and condition checking time.
1. for loop
2. while loop
3. do-while loop
In Java, for loop is similar to C and C++. It enables us to initialize the loop variable, check
the condition, and increment/decrement in a single line of code. We use the for loop only
when we exactly know the number of times, we want to execute the block of code.
Java provides an enhanced for loop to traverse the data structures like array or collection. In
the for-each loop, we don't need to update the loop variable. The syntax to use the for-each
loop in java is given below.
The while loop is also used to iterate over the number of statements multiple times. However,
if we don't know the number of iterations in advance, it is recommended to use a while loop.
Unlike for loop, the initialization and increment/decrement doesn't take place inside the loop
statement in while loop.
It is also known as the entry-controlled loop since the condition is checked at the start of the
loop. If the condition is true, then the loop body will be executed; otherwise, the statements
after the loop will be executed.
while(condition){
//looping statements
}
The flow chart for the while loop is given in the following image.
The do-while loop checks the condition at the end of the loop after executing the loop
statements. When the number of iteration is not known and we have to execute the loop at
least once, we can use do-while loop.
It is also known as the exit-controlled loop since the condition is not checked in advance. The
syntax of the do-while loop is given below.
do
{
//statements
} while (condition);
The flow chart of the do-while loop is given in the following image.
*************************************************************************
Jump statements are used to transfer the control of the program to the specific statements. In
other words, jump statements transfer the execution control to the other part of the program.
There are two types of jump statements in Java, i.e., break and continue.
As the name suggests, the break statement is used to break the current flow of the program
and transfer the control to the next statement outside a loop or switch statement. However, it
breaks only the inner loop in the case of the nested loop.
The break statement cannot be used independently in the Java program, i.e., it can only be
written inside the loop or switch statement.
Unlike break statement, the continue statement doesn't break the loop, whereas, it skips the
specific part of the loop and jumps to the next iteration of the loop immediately.
*************************************************************************
Q.How many ways can we read data from the keyboard in Java?
There are many ways to read data from the keyboard. For example:
o InputStreamReader
o Console
o Scanner
o DataInputStream etc.
InputStreamReader class
InputStreamReader class can be used to read data from keyboard.It performs two tasks:
BufferedReader class
BufferedReader class can be used to read data line by line by readLine() method.
In this example, we are connecting the BufferedReader stream with the InputStreamReader
stream for reading the line by line data from the keyboard.
import java.io.*;
class G5{
public static void main(String args[])throws Exception{
System.out.println("Welcome "+name);
}
}
Output:Enter your name
Shashish
Welcome Shashish
Java Console Class
The Java Console class is be used to get input from console. It provides methods to read texts
and passwords.
If you read password using Console class, it will not be displayed to the user.
The java.io.Console class is attached with system console internally. The Console class is
introduced since 1.5.
String text=System.console().readLine();
System.out.println("Text is: "+text);
Using Scanner class
From Java 1.5 Scanner class was introduced. This class accepts a File, InputStream, Path
and, String objects, reads all the primitive data types and Strings (from the given source)
token by token using regular expressions. By default, whitespace is considered as the
delimiter (to break the data into tokens).
To read data from keyboard you need to use standard input as source (System.in). For each
datatype a nextXXX() is provided namely, nextInt(), nextShort(), nextFloat(), nextLong(),
nextBigDecimal(), nextBigInteger(), nextLong(), nextShort(), nextDouble(), nextByte(),
nextFloat(), next().
Java DataInputStream Class
Java DataInputStream class allows an application to read primitive data from the input stream
in a machine-independent way.
Java application generally uses the data output stream to write data that can later be read by
a data input stream.
// Driver Class
class GFG {
// main function
public static void main (String[] args) {
int a=10000;
System.out.printf("%,d%n",a);
}
}
Output
10,000
// Driver Class
class GFG {
// main function
public static void main(String[] args)
{
// declaring double
double a = 3.14159265359;
Output
3.141593
3.142
3.14
// Driver Function
class GFG {
// main function
public static void main(String[] args)
{
int a = 10;
Boolean b = true, c = false;
Integer d = null;
System.out.printf("%B\n", d);
}
}
Output
true
TRUE
false
FALSE
// Driver Class
class GFG {
// main function
public static void main(String[] args)
{
char c = 'g';
// Formatting Done
System.out.printf("%c\n", c);
Output
g
G
// Driver Class
class GFG {
// main function
public static void main(String[] args)
{
String str = "geeksforgeeks";
str = "GFG";
// Vice-versa not possible
System.out.printf("%S \n", str);
System.out.printf("%s \n", str);
}
}
Output
geeksforgeeks
GEEKSFORGEEKS
GFG
GFG
// Driver Class
class GFG {
// main function
public static void main(String[] args)
{
Date time = new Date();
Output
Current Time: 11:32:36
Hours: 11 Minutes: 32 Seconds: 36
11:32:36 am 198 198000000 +0000
*************************************************************************