0% found this document useful (0 votes)
7 views

Java_BSc(H)_Unit-1

Uploaded by

harimanoj25784
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Java_BSc(H)_Unit-1

Uploaded by

harimanoj25784
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

OBJECT ORINTED PROGRAMMING USING JAVA UNIT-1

Q.Features of Object-Oriented Programming?


Objects and Classes:
Objects are always called instances of a class which are created from class in java or
any other language.

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

Collection of objects is called class. It is a logical entity.

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

Data Abstraction and Encapsulation:

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:

RAMAKRISHNAREDDY NANDYALA 9848740143 1


OBJECT ORINTED PROGRAMMING USING JAVA UNIT-1

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

Flying Bird Non-Flying


Attributes: Bird

Robin Parrot Penguin Kiwi


Attributes: Attributes: Attributes: Attributes:
PROPERTY I NHERITANCE
In OOP, the concept of inheritance provides the idea of reusability. This means that we
can add additional features to an existing class without modifying it. This is possible by
deriving a new class from the existing one. The new class will have the combined features of
both the classes.

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

Circle Object Triangle Oval Object


Draw (Circle) Object Draw (Oval)

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

2) Creating objects from class definitions.


3) Establishing communication among objects.
Objects communicate with one another by sending and receiving information much the
same way as people pass messages to one another.

Object 1

Object 5 Object 2

Object 4 Object 3

N ETWORK OF OBJECTS COMMUNICATING BETWEEN THEM


****************************************************************

Q.What are the problems in procedure-oriented programming?

 Procedural programming mainly focuses on procedures or functions. Less attention is


given to the data.
 The data and functions are separate from each other.
 Global data is freely moving and is shared among various functions. Thus, it becomes
difficult for programmers to identify and fix issues in a program that originate due to
incorrect data handling.
 Changes in data types need to be carried out manually all over the program and in the
functions using the same data type.
 Limited and difficult code reusability.
 It does not model real-world entities (e.g., car, table, bank account, loan) very well
where we as a human being, perceive everything as an object.
 The procedural programming approach does not work well for large and complex
systems.

*******************************************************************

RAMAKRISHNAREDDY NANDYALA 9848740143 3


OBJECT ORINTED PROGRAMMING USING JAVA UNIT-1

Q.Explain features of Java?


Features of Java
A list of the most important features of the Java language is given below.

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.

RAMAKRISHNAREDDY NANDYALA 9848740143 4


OBJECT ORINTED PROGRAMMING USING JAVA UNIT-1

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

The English mining of Robust is strong. Java is robust because:

o It uses strong memory management.


o There is a lack of pointers that avoids security problems.
o There are exception handling and the type checking mechanism in Java. All these
points make Java 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

A thread can be defined as a process, a task, a path, to an execution or a block of code.


Simultaneous execution of two or more blocks of code within the same program is referred
to as multithreading. Java supports multithreading which allows to you to run many tasks
simultaneously. Java provides built in support for multithreading so that the user can design
such applications in most sophisticated way.

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

RAMAKRISHNAREDDY NANDYALA 9848740143 5


OBJECT ORINTED PROGRAMMING USING JAVA UNIT-1

*************************************************************************

Q.Explain about Java Virtual Machine?


JVM (Java Virtual Machine)
The Java achieves architecture neutrality because Java compiler produces an
intermediary code known as byte code for a machine that does not exist. This machine is
called the Java Virtual Machine. Following fig illustrates the process of compiling of java
program.

The JVM performs following operation:

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.

RAMAKRISHNAREDDY NANDYALA 9848740143 6


OBJECT ORINTED PROGRAMMING USING JAVA UNIT-1

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

It is the runtime data area in which objects are allocated.

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.

5) Program Counter Register

PC (program counter) register contains the address of the Java virtual machine instruction
currently being executed.

6) Native Method Stack

It contains all the native methods used in the application.

7) Execution Engine

It contains:

1. Interpreter: Read bytecode stream then execute the instructions.


2. Just-In-Time(JIT) compiler: It is used to improve the performance. JIT compiles
parts of the byte code that have similar functionality at the same time, and hence
reduces the amount of time needed for compilation. Here, the term "compiler" refers
to a translator from the instruction set of a Java virtual machine (JVM) to the instruction
set of a specific CPU.

Java Native Interface

RAMAKRISHNAREDDY NANDYALA 9848740143 7


OBJECT ORINTED PROGRAMMING USING JAVA UNIT-1

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.

*************************************************************************

Q.Explain about Java tokens?


What is token in Java?
The Java compiler breaks the line of code into text (words) is called Java tokens. These are the
smallest element of the Java program. The Java compiler identified these words as tokens.The Java
compiler translates these tokens into Java bytecode. Further, these bytecodes are executed inside the
interpreted Java environment.

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:

Here's the complete list of all keywords in Java programming.

Java Keywords List

abstract assert boolean break byte

case catch char class const

continue default do double else

enum extends final finally float

for goto if implements import

instanceof int interface long native

RAMAKRISHNAREDDY NANDYALA 9848740143 8


OBJECT ORINTED PROGRAMMING USING JAVA UNIT-1

new package private protected public

return short static strictfp super

switch synchronized this throw throws

transient try void volatile while

*********

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.

Some valid identifiers are:

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.

Types of Literals in Java

Generally, there are 5 types of literals that can be further expanded into various other
literals.

RAMAKRISHNAREDDY NANDYALA 9848740143 9


OBJECT ORINTED PROGRAMMING USING JAVA UNIT-1

The five main Literal types are:

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

Example of String Literal:


String Company = “DataFlair”;//Valid String Literal

RAMAKRISHNAREDDY NANDYALA 9848740143 10


OBJECT ORINTED PROGRAMMING USING JAVA UNIT-1

String Company = DataFlair;//Invalid as there is no double quote.


*********

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.

RAMAKRISHNAREDDY NANDYALA 9848740143 11


OBJECT ORINTED PROGRAMMING USING JAVA UNIT-1

Operator Operation

+ Addition

- Subtraction

* Multiplication

/ Division

% Modulo Operation (Remainder after 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.

Operator Example Equivalent to

= a = b; a = b;

+= a += b; a = a + b;

-= a -= b; a = a - b;

*= a *= b; a = a * b;

RAMAKRISHNAREDDY NANDYALA 9848740143 12


OBJECT ORINTED PROGRAMMING USING JAVA UNIT-1

/= a /= b; a = a / b;

%= a %= b; a = a % b;

Relational (Comparison) Operators

Relational operators are used to comparison between two operands. For example,

// check if a is less than b


a < b;

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

== Is Equal To 3 == 5 returns false

!= Not Equal To 3 != 5 returns true

> Greater Than 3 > 5 returns false

< Less Than 3 < 5 returns true

>= Greater Than or Equal To 3 >= 5 returns false

<= Less Than or Equal To 3 <= 5 returns true

Increment and Decrement (Unary) Operators


Java has two very useful operators not generally found in many other languages. These
are increment (++) and decrement (--) operators. The operators ++ adds 1 to the operand
while – subtracts 1 from the operand. Both are unary operators and are used in the following
form:
++m or m++; --m or m--;

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.

RAMAKRISHNAREDDY NANDYALA 9848740143 14


OBJECT ORINTED PROGRAMMING USING JAVA UNIT-1

Ex: sai instanceof student;


The statement is true if the object sai belongs to the class student.
DOT operator:
The dot (.) operator is used to access the instance variables and methods of class
objects.
Ex: sai.age; sai.total_marks ();

*********************

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:

o Line Oriented: It begins with a pair of forwarding slashes (//).


o Block-Oriented: It begins with /* and continues until it founds */ or /** and continues
until it founds */.

*************************************************************************
RAMAKRISHNAREDDY NANDYALA 9848740143 15
OBJECT ORINTED PROGRAMMING USING JAVA UNIT-1

Q.write about Java Naming Conventions?


Java naming convention is a rule to follow as you decide what to name your identifiers such
as class, package, variable, constant, method, etc.

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.

Advantage of Naming Conventions in Java


By using standard Java naming conventions, you make your code easier to read for yourself
and other programmers. Readability of Java program is very important. It indicates that less
time is spent to figure out what the code does.

The following table shows the popular conventions used for the different identifiers.

Identifiers Naming Rules Examples


Type

Class It should start with the uppercase public class Employee


letter. {
It should be a noun such as Color, //code snippet
Button, System, Thread, etc. }

Interface It should start with the uppercase interface Printable


letter. {
It should be an adjective such as //code snippet
Runnable, Remote, ActionListener. }

Method It should start with lowercase letter.class Employee


It should be a verb such as main(), {
print(), println(). // method
If the name contains multiple words, void draw(){
start it with a lowercase letter //code snippet
followed by an uppercase letter such }
as actionPerformed(). }

Variable It should start with a lowercase letter class Employee


such as id, name. {
It should not start with the special //variable
characters like & (ampersand), $ int id;

RAMAKRISHNAREDDY NANDYALA 9848740143 16


OBJECT ORINTED PROGRAMMING USING JAVA UNIT-1

(dollar), _ (underscore). //code snippet


If the name contains multiple words, }
start it with the lowercase letter
followed by an uppercase letter such
as firstName, lastName.
Avoid using one-character variables
such as x, y, z.

Package It should be a lowercase letter such as //package


java, lang. package com.javatpoint;
If the name contains multiple words, it class Employee
should be separated by dots (.) such as {
java.util, java.lang. //code snippet
}

Constant It should be in uppercase letters such class Employee


as RED, YELLOW. {
If the name contains multiple words, it //constant
should be separated by an static final int MIN_AGE =
underscore(_) such as 18;
MAX_PRIORITY. //code snippet
It may contain digits but not as the }
first letter.

*************************************************************************

Q.Explain about structure of java program?


A typical structure of a Java program contains the following elements:

RAMAKRISHNAREDDY NANDYALA 9848740143 17


OBJECT ORINTED PROGRAMMING USING JAVA UNIT-1

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:

//First Java Program


o Multi-line Comment: It starts with a /* and ends with */. We write between these two
symbols. For example:

1. /*It is an example of
2. multiline comment*/
o Documentation Comment: It starts with the delimiter (/**) and ends with */. For
example:

1. /**It is an example of documentation comment*/

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:

RAMAKRISHNAREDDY NANDYALA 9848740143 18


OBJECT ORINTED PROGRAMMING USING JAVA UNIT-1

1. import java.util.Scanner; //it imports the Scanner class only


Interface Section
It is an optional section. We can create an interface in this section if required. We use
the interface keyword to create an interface. An interface is a slightly different from the
class. It contains only constants and method declarations. Another difference is that it
cannot be instantiated. We can use interface in classes by using the implements keyword. An
interface can also be used with other interfaces by using the extends keyword. 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:

class Student //class definition


{
}

Class Variables and Constants


In this section, we define variables and constants that are to be used later in the program. In
a Java program, the variables and constants are defined just after the class definition. The
variables and constants store values of the parameters. It is used during the execution of the
program.

For example:

class Student //class definition


{
String sname; //variable
int id;
double percentage;
}
RAMAKRISHNAREDDY NANDYALA 9848740143 19
OBJECT ORINTED PROGRAMMING USING JAVA UNIT-1

Main Method Class


In this section, we define the main() method. It is essential for all Java programs. Because
the execution of all Java programs starts from the main() method. In other words, it is an entry
point of the class. It must be inside the class. Inside the main method, we create objects and
call the methods. We use the following statement to define the main() method:

public static void main(String args[])


{
}
*************************************************************************
Q.Write a simple java program?
class Simple
{
public static void main(String args[])
{
System.out.println(“Shashish”);
}
}

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.

RAMAKRISHNAREDDY NANDYALA 9848740143 20


OBJECT ORINTED PROGRAMMING USING JAVA UNIT-1

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.

*************************************************************************

Q.Explain data types in java?


Data Types in Java
Data types specify the different sizes and values that can be stored in the variable. There are
two types of data types in Java:

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

RAMAKRISHNAREDDY NANDYALA 9848740143 21


OBJECT ORINTED PROGRAMMING USING JAVA UNIT-1

Boolean Data Type


The Boolean data type is used to store only two possible values: true and false. This data type
is used for simple flags that track true/false conditions.

The Boolean data type specifies one bit of information, but its "size" can't be defined
precisely.

Example:

Boolean one = false

Byte Data Type


The byte data type is an example of primitive data type. It isan 8-bit signed two's complement
integer. Its value-range lies between -128 to 127 (inclusive). Its minimum value is -128 and
maximum value is 127. Its default value is 0.

Example:

byte a = 10, byte b = -20

Short Data Type


The short data type is a 16-bit signed two's complement integer. Its value-range lies between
-32,768 to 32,767 (inclusive). Its minimum value is -32,768 and maximum value is 32,767.
Its default value is 0.

Example:

short s = 10000, short r = -5000


Int Data Type
The int data type is a 32-bit signed two's complement integer. Its value-range lies between -
2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value is -
2,147,483,648and maximum value is 2,147,483,647. Its default value is 0.

Example:

int a = 100000, int b = -200000

RAMAKRISHNAREDDY NANDYALA 9848740143 22


OBJECT ORINTED PROGRAMMING USING JAVA UNIT-1

Long Data Type


The long data type is a 64-bit two's complement integer. Its value-range lies between -
9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)(inclusive). Its
minimum value is - 9,223,372,036,854,775,808and maximum value is
9,223,372,036,854,775,807. Its default value is 0.

Example:

long a = 100000L, long b = -200000L

Float Data Type


The float data type is a single-precision 32-bit IEEE 754 floating point. Its value range is
unlimited. It is recommended to use a float (instead of double) if you need to save memory
in large arrays of floating-point numbers.

Example:
float f1 = 234.5f

Double Data Type


The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range is
unlimited. The double data type is generally used for decimal values just like float. The
double data type also should never be used for precise values, such as currency. Its default
value is 0.0d.

Example:

double d1 = 12.3

Char Data Type


The char data type is a single 16-bit Unicode character. The char data type is used to store
characters.

Example:

char letter = 'A'

*************************************************************************

Q) Explain types of variables in java?

RAMAKRISHNAREDDY NANDYALA 9848740143 23


OBJECT ORINTED PROGRAMMING USING JAVA UNIT-1

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.

A local variable cannot be defined with "static" keyword.

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.

Example to understand the types of variables in java

public class A
{
static int m=100;//static variable

RAMAKRISHNAREDDY NANDYALA 9848740143 24


OBJECT ORINTED PROGRAMMING USING JAVA UNIT-1

void method()
{
int n=90;//local variable
}
public static void main(String args[])
{
int data=50;//instance variable
}
}//end of class

*************************************************************************

Q) Explain about type casting in java?


Type Casting in Java
In Java, type casting is a method or process that converts a data type into another data type
in both ways manually and automatically. The automatic conversion is done by the compiler
and manual conversion performed by the programmer.

Type casting

Convert a value from one data type to another data type is known as type casting.

Types of Type Casting

There are two types of type casting:

o Widening Type Casting or Automatic Type Casting


o Narrowing Type Casting or Manual Type Casting

Widening Type Casting


Converting a lower data type into a higher one is called widening type casting. It is also
known as implicit conversion or casting down. It is done automatically. It is safe because
there is no chance to lose data. It takes place when:
RAMAKRISHNAREDDY NANDYALA 9848740143 25
OBJECT ORINTED PROGRAMMING USING JAVA UNIT-1

o Both data types must be compatible with each other.


o The target type must be larger than the source type.

byte -> short -> char -> int -> long -> float -> double

WideningTypeCastingExample.java

public class WideningTypeCastingExample


{
public static void main(String[] args)
{
int x = 7;
//automatically converts the integer type into long type
long y = x;
//automatically converts the long type into float type
float z = y;
System.out.println("Before conversion, int value "+x);
System.out.println("After conversion, long value "+y);
System.out.println("After conversion, float value "+z);
}
}

Output

Before conversion, the value is: 7


After conversion, the long value is: 7
After conversion, the float value is: 7.0

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.

Narrowing Type Casting


Converting a higher data type into a lower one is called narrowing type casting. It is also
known as explicit conversion or casting up. It is done manually by the programmer. If we
do not perform casting then the compiler reports a compile-time error.

double -> float -> long -> int -> char -> short -> byte

NarrowingTypeCastingExample.java

public class NarrowingTypeCastingExample


RAMAKRISHNAREDDY NANDYALA 9848740143 26
OBJECT ORINTED PROGRAMMING USING JAVA UNIT-1

{
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

Before conversion: 166.66


After conversion into long type: 166
After conversion into int type: 166

Example: Type conversion from int to String


class Main {
public static void main(String[] args) {
// create int type variable
int num = 10;
System.out.println("The integer value is: " + num);

// converts int to string type


String data = String.valueOf(num);
System.out.println("The string value is: " + data);
}
}
Output

The integer value is: 10


The string value is: 10

In the above program, notice the line

RAMAKRISHNAREDDY NANDYALA 9848740143 27


OBJECT ORINTED PROGRAMMING USING JAVA UNIT-1

String data = String.valueOf(num);

Here, we have used the valueOf() method of the Java String class to convert the int type
variable into a string.

Example: Type conversion from String to int


class Main {
public static void main(String[] args) {
// create string type variable
String data = "10";
System.out.println("The string value is: " + data);

// convert string variable to int


int num = Integer.parseInt(data);
System.out.println("The integer value is: " + num);
}
}
Output

The string value is: 10


The integer value is: 10

In the above example, notice the line

int num = Integer.parseInt(data);

Here, we have used the parseInt() method of the Java Integer class to convert a string type
variable into an int variable.
****************************************************************

Q.Explain about conditional control statements or decision


making and branching statements?
Java compiler executes the code from top to bottom. The statements in the code are executed
according to the order in which they appear. However, Java provides statements that can be
used to control the flow of Java code. Such statements are called control flow statements. It
is one of the fundamental features of Java, which provides a smooth flow of program.

Conditional control statements are used to change the sequence of program execution based
on the condition.

RAMAKRISHNAREDDY NANDYALA 9848740143 28


OBJECT ORINTED PROGRAMMING USING JAVA UNIT-1

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

Let's understand the if-statements one by one.

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.

Syntax of if statement is given below.

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

RAMAKRISHNAREDDY NANDYALA 9848740143 29


OBJECT ORINTED PROGRAMMING USING JAVA UNIT-1

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.

Syntax of if-else-if statement is given below.

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.

Syntax of Nested if-statement is given below.

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.

RAMAKRISHNAREDDY NANDYALA 9848740143 30


OBJECT ORINTED PROGRAMMING USING JAVA UNIT-1

Points to be noted about switch statement:

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.

The syntax to use the switch statement is given below.

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;

*************************************************************************

Q.Explain about looping statements or iterative statements?


Loop Statements

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

Java for 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.

1. for(initialization, condition, increment/decrement) {


2. //block of statements
3. }

The flow chart for the for-loop is given below.

RAMAKRISHNAREDDY NANDYALA 9848740143 32


OBJECT ORINTED PROGRAMMING USING JAVA UNIT-1

Java for-each loop

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.

1. for(data_type var : array_name/collection_name){


2. //statements
3. }

Java while loop

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.

The syntax of the while loop is given below.

while(condition){
//looping statements
}

The flow chart for the while loop is given in the following image.

RAMAKRISHNAREDDY NANDYALA 9848740143 33


OBJECT ORINTED PROGRAMMING USING JAVA UNIT-1

Java do-while loop

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.

*************************************************************************

Q.Explain about jumping statements in java?


Jump Statements

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.

Java break statement

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.

RAMAKRISHNAREDDY NANDYALA 9848740143 34


OBJECT ORINTED PROGRAMMING USING JAVA UNIT-1

The break statement cannot be used independently in the Java program, i.e., it can only be
written inside the loop or switch statement.

Java continue 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:

o connects to input stream of keyboard


o converts the byte-oriented stream into character-oriented stream

BufferedReader class

BufferedReader class can be used to read data line by line by readLine() method.

Example of reading data from keyboard by InputStreamReader and BufferdReader


class

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{

InputStreamReader r=new InputStreamReader(System.in);


BufferedReader br=new BufferedReader(r);

System.out.println("Enter your name");


String name=br.readLine();
RAMAKRISHNAREDDY NANDYALA 9848740143 35
OBJECT ORINTED PROGRAMMING USING JAVA UNIT-1

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.

Let's see a simple example to read text from console.

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.

Java DataInputStream class declaration

Let's see the declaration for java.io.DataInputStream class:

public class DataInputStream extends FilterInputStream implements DataInput


*************************************************************************

RAMAKRISHNAREDDY NANDYALA 9848740143 36


OBJECT ORINTED PROGRAMMING USING JAVA UNIT-1

Q.Explain about formatted output using printf()?


Sometimes in programming, it is essential to print the output in a given specified format.
Most users are familiar with the printf function in C.
Formatting Using Java Printf()
printf() uses format specifiers for formatting. There are certain data types are mentioned
below:
 For Number Formatting
 Formatting Decimal Numbers
 For Boolean Formatting
 For String Formatting
 For Char Formatting
 For Date and Time Formatting
i). For Number Formatting
The number itself includes Integer, Long, etc. The formatting Specifier used is %d.
Below is the implementation of the above method:
Java
// Java Program to demonstrate
// Use of printf to
// Formatting Integer
import java.io.*;

// Driver Class
class GFG {
// main function
public static void main (String[] args) {
int a=10000;

System.out.printf("%,d%n",a);
}
}

RAMAKRISHNAREDDY NANDYALA 9848740143 37


OBJECT ORINTED PROGRAMMING USING JAVA UNIT-1

Output
10,000

ii). For Decimal Number Formatting


Decimal Number Formatting can be done using print() and format specifier %f .
Below is the implementation of the above method:
Java
// Java Programs to demonstrate
// Use of Printf() for decimal
// Number Formatting
import java.io.*;

// Driver Class
class GFG {
// main function
public static void main(String[] args)
{
// declaring double
double a = 3.14159265359;

// Printing Double Value with


// different Formatting
System.out.printf("%f\n", a);
System.out.printf("%5.3f\n", a);
System.out.printf("%5.2f\n", a);
}
}

RAMAKRISHNAREDDY NANDYALA 9848740143 38


OBJECT ORINTED PROGRAMMING USING JAVA UNIT-1

Output
3.141593
3.142
3.14

iii). For Boolean Formatting


Boolean Formatting can be done using printf and ( ‘%b’ or ‘%B’ ) depending upon the
result needed.
Below is the implementation of the above method:
Java
// Java Programs to demonstrate
// Use of Printf() for decimal
// Boolean Formatting
import java.io.*;

// Driver Function
class GFG {
// main function
public static void main(String[] args)
{
int a = 10;
Boolean b = true, c = false;
Integer d = null;

// Fromatting Done using printf


System.out.printf("%b\n", a);
System.out.printf("%B\n", b);
System.out.printf("%b\n", c);

RAMAKRISHNAREDDY NANDYALA 9848740143 39


OBJECT ORINTED PROGRAMMING USING JAVA UNIT-1

System.out.printf("%B\n", d);
}
}

Output
true
TRUE
false
FALSE

iv). For Char Formatting


Char Formatting is easy to understand as it need printf() and Charracter format specifier
used are ‘%c’ and ‘%C’.
Below is the implementation of the above method:
Java
// Java Program to Formatt
//
import java.io.*;

// Driver Class
class GFG {
// main function
public static void main(String[] args)
{
char c = 'g';

// Formatting Done
System.out.printf("%c\n", c);

RAMAKRISHNAREDDY NANDYALA 9848740143 40


OBJECT ORINTED PROGRAMMING USING JAVA UNIT-1

// Converting into Uppercase


System.out.printf("%C\n", c);
}
}

Output
g
G

v). For String Formatting


String Formatting requires the knowledge of Strings and format specifier used ‘%s’ and
‘%S’.
Below is the implementation of the above method:
Java
// Java Program to implement
// Printf() for String Formatting
import java.io.*;

// Driver Class
class GFG {
// main function
public static void main(String[] args)
{
String str = "geeksforgeeks";

// Formatting from lowercase to


// Uppercase
System.out.printf("%s \n", str);
System.out.printf("%S \n", str);

RAMAKRISHNAREDDY NANDYALA 9848740143 41


OBJECT ORINTED PROGRAMMING USING JAVA UNIT-1

str = "GFG";
// Vice-versa not possible
System.out.printf("%S \n", str);
System.out.printf("%s \n", str);
}
}

Output
geeksforgeeks
GEEKSFORGEEKS
GFG
GFG

vi). For Date and Time Formatting


Formatting of Date and Time is not as easy as the data-type used above. It uses more than
simple format specifier knowledge can be observed in the example mentioned below.
Below is the implementation of the above method:
Java
// Java Program to demonstrate use of
// printf() for formatting Date-time
import java.io.*;
import java.util.*;

// Driver Class
class GFG {
// main function
public static void main(String[] args)
{
Date time = new Date();

RAMAKRISHNAREDDY NANDYALA 9848740143 42


OBJECT ORINTED PROGRAMMING USING JAVA UNIT-1

System.out.printf("Current Time: %tT\n", time);

// Another Method with all of them Hour


// minutes and seconds seperated
System.out.printf("Hours: %tH Minutes: %tM Seconds: %tS\n",
time,time, time);

// Another Method to print the time


// Followed by am/pm , time in milliseconds
// nanoseconds and time-zone offset
System.out.printf("%1$tH:%1$tM:%1$tS %1$tp %1$tL %1$tN %1$tz %n",
time);
}
}

Output
Current Time: 11:32:36
Hours: 11 Minutes: 32 Seconds: 36
11:32:36 am 198 198000000 +0000
*************************************************************************

RAMAKRISHNAREDDY NANDYALA 9848740143 43

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy