Unit 1
Unit 1
Object oriented programming aims to implement real world entities like inheritance, hiding,
polymorphism etc in programming. OOP is to bind together the data and the functions that
operate on them so that no other part of code can access this data except that function.
Objectives
The theme of object-oriented paradigm is to remove the problems that come across procedural
language such as reusability. It mainly provides privacy to the data members within its function
(member function) from outside world. OOP allows decomposition of a problem into a number
of elements called objects and then binds data and function around these objects. The data
associated with the function will be accessed by object associated with that function only.
However, function of one object can call the function of other objects. The following fig1.1
depicts the objects communication
Data members
Data members
Communicate
Member functions
Member functions
Object1 Object2
The object-oriented paradigm deals with active objects instead of passive objects. We encounter
many active objects in our daily life: a vehicle, an automatic door, a dishwasher and so on. The
action to be performed on these objects is included in the object: the objects need only to receive
the appropriate stimulus from outside to perform one of the actions.
A file in an object-oriented paradigm can be packed with all the procedures—called methods in
the object-oriented paradigm—to be performed by the file: printing, copying, deleting and so on.
The program in this paradigm just sends the corresponding request to the object.
1.3 Procedural programming language and object oriented language:
Program is divided into objects depending Program is divided into small chunks based on
on the problem. the functions.
Each object controls its own data. Each function contains different data.
Focuses on security of the data irrespective Follows a systematic approach to solve the
of the algorithm. problem.
The main priority is data rather than Functions are more important than data in a
function in a program. program
The functions of the objects are linked via Different parts of a program are interconnected
message passing. via parameter passing.
Main
Function
Function
Function Function
The structure of the Object oriented program is shown in the below figure:
Two objects can communicate via the function without knowing the data
of each another.
We can represent a class by two ways as shown in the below figure:
Out of these two methods, first method to represent object is widely used.
It emphasis on data rather than algorithm.
Program is divided into multiple portions known as Class/objects.
Class: We are using class as user defined data type to create object.
Data encapsulation: Data and function both are combined into one portion
known as class.
Data hiding: Data cannot be accessed outside the class and provides the
fundamental of private and public data.
Interface: Object can communicate via the Interface.
Inheritance: We can create one object which acquire properties and
method of another object.
Polymorphism: We can use one method for the multiple uses.
Dynamic binding: Two procedures are linked during the time of execution.
Follows up bottom-up
1. Classes
2. Objects
3. Dynamic Binding
4. Message Passing
5. Inheritance.
6. Abstraction
7. Encapsulation.
8. Polymorphism
Classes
A class is a user defined blueprint from which objects are created. It represents the set of
member functions and member variables that are common to all objects of one type.
Flower
color: String
Turn()
Pick()
In the above figure Flower is class name and it has member functions as Turn() ,Pick() and
member variables as color.
Objects:
Instance of class is called as object. Objects have states and behaviors. Example: A
dog has states - color, name, breed as well as behaviors – wagging the tail,
barking, eating.
Class
object Dog
color
d1
name,breed
Barking()
In the above diagram d1 is object to Dog class which acts as instance and access the variables
and methods of Dog class
Dynamic Binding:
In JAVA programming language objects are allocated their memory at the time of execution
using the new operator. After allocation of memory the instance variables are binds with their
associated methods at the time of execution. This type of data binding is also called dynamic
binding or late binding or execution time binding or run time binding.
Message Passing
Message passing is a type of communication between processes. Message passing is a form of communication used
in parallel programming and object-oriented programming. Communications are completed by the sending of
messages (functions, signals and data packets) to recipients through network.
Object 1
Object 2 Object 3
In the above figure one object interacts with another object by invoking methods (or
functions) on that object. Through the interaction of objects, programmers achieve a higher
order of functionality which has complex behavior.
Inheritance:
It is defined as acquiring the properties from base class to derived class. By these we can
achieve code reusability .The base class can be called as parent class and derived class can be
called as child class.
Flower
Color: String
Rose
Smell: String
In the above figure Class Rose acquires the properties of Flower data member that is color.
Abstraction:
Abstraction is defined as hiding the back ground details to the outside world. Only the
functionality will be provided to user. Let us consider an real time example of ATM machine the
use inserts the card and enter the pin for transition and does the transition but he doesn’t know
the working mechanism used internally for reading the card and how the card has been connect
the his account number.
Encapsulation:
Combining of data members and member functions into single unit is called
encapsulation. Encapsulation also hides the data to other class. Consider a real time example of
encapsulation; in a company there are different sections like the accounts section, finance
section, sales section etc. The finance section handles all the financial transactions and keeps
records of all the data related to finance. Similarly the sales sections handle all the sales related
activities and keep records of all the sales. Now there may arise a situation when for some reason
an official from finance section needs all the data about sales in a particular month. In this case,
he is not allowed to directly access the data of sales section. He will first have to contact some
other officer in the sales section and then request him to give the particular data. This is what
encapsulation is. Here the data of sales section and the employees that can manipulate them are
wrapped under a single name “sales section”.
Polymorphism:
It is a Greek word which is Ploy means many morphism means forms .It is defined as
one method can be implemented in many forms which means one method can perform different
tasks.
Lets us take an example of a car. A car has a gear transmission system. It has four front gears
and one backward gear. When the engine is accelerated then depending upon which gear is
engaged different amount power and movement is delivered to the car. The action is same
applying gear but based on the type of gear the action behaves differently or you can say that it
shows many forms.
Polymorphism can be achieved statically and dynamically
1.5 Applications of oop:
There are mainly 4 type of applications that can be created using java programming:
Standalone Application
It is also known as desktop application or window-based application. An application
that we need to install on every machine such as media player, antivirus etc. AWT and Swing are
used in java for creating standalone applications.
Web Application
An application that runs on the server side and creates dynamic page, is called web
application, Currently, servlet, jsp, struts, etc. technologies are used for creating web applications
in java.
Enterprise Application
An application that is distributed in nature, such as banking applications etc.It has the
advantage of high level security, load balancing and clustering. In java, EJB is used for creating
enterprise applications.
Mobile Application
An application that is created for mobile devices. Currently Android and Java ME
are used for creating mobile applications
Java is inherited form 2 languages that are C and C++.It is pure Object oriented
language. The history of java starts with Green Team. Initially it is called as Stealth project. Sun
Microsystems initiated this project to develop a language for digital devices. It was invented by
James Gosling Mike Sheridan, and Patrick Naugton initiated the Java language project in June
1991.The language was initially called Oak after an oak tree that stood outside Gosling's office.
Later the project went by the name Green and was finally renamed Java.
Why the name Java? James Gosling and his team members consuming a lot of coffee while
developing the language from Java coffee and a good quality coffee was exported to entire world
from place called 'Java Island' so the team members renamed it as Java and the symbol of java is
language is coffee cup and saucer .Sun Micro Systems formally released java in 1995.In 1995,
Time magazine called Java one of the Ten Best Products of 1995.the first version of java JDK
1.0 released in(January 23, 1996).
We all know what a compiler does. It takes your code & translates it into machine-level
code. That’s exactly what happens with our C code-it gets ‘compiled’. While with JAVA,
the code is first transformed to what is called the bytecode. This bytecode is then
executed by the JVM(Java Virtual Machine). So we can say, JAVA code is more portable.
4. C uses the top-down approach while JAVA uses the bottom-up approach.
In C, formulating the program begins by defining the whole and then splitting them into
smaller elements. JAVA(and C++ and other OOP languages) follows the bottom-up
approach where the smaller elements combine together to form the whole.
When it comes to JAVA, we don’t need the *’s & &’s to deal with pointers & their
addressing. More formally, there is no pointer syntax required in JAVA. It does what it
needs to do. While in JAVA, we do create references for objects.
6. The Behind-the-scenes Memory Management with JAVA & The User-Based Memory
Management in C.
Remember ‘malloc’ & ‘free’? Those are the library calls used in C to allocate & free
chunks of memory for specific data(specified using the keyword ‘sizeof’). Hence in C, the
memory is managed by the user while JAVA uses a garbage collector that deletes the
objects that no longer have any references to them.
7. JAVA supports Method Overloading while C does not support overloading at all.
8. Unlike C, JAVA does not support Preprocessors, & does not really them.
The preprocessor directives like #include & #define, etc are considered one of the most
essential elements of C programming. However, there are no preprocessors in JAVA.
JAVA uses other alternatives for the preprocessors. For instance, public static final is
used instead of the #define preprocessor. Java maps class names to a directory and file
structure instead of the #include used to include files in C.
Although this difference might not hold any conceptual(intuitive) significance, but it’s
maybe just the tradition. C uses the printf & scanf functions as its standard input &
output while JAVA uses the System.out.print & System Resources and
Information..read functions.
When an error occurs in a Java program it results in an exception being thrown. It can
then be handled using various exception handling techniques. While in C, if there’s an
error, there IS an error.
If you have passion to learn Java programming and you wants to write and test
your own Java codes, then first of all you will required to download a Java
environment on your computer. Here we have given you some of the essential
hardware and software configuration environment which is required with any
operating system.
Operating System
Java SDK or JRE 1.6 or higher
Java Servlet Container (Free Servlet Container available)
Supported Database and library that supports the database connection
with Java.
1.8.1 Features or BUZZ Words:
Java is the most powerful language .Its main objective was to make it simple ans secure
language.java has some excellent features which play an important role in the popularity of this
language. The features are
Simple
Object-Oriented
Portable
Platform independent
Secured
Robust
Architecture-neutral
Scalability
Interpreted
High Performance
Multithreaded
Distributed
Dynamic
Simple:
Java is simple language to learn because all syntaxes are based on C and C++.Some of the
difficult concept like Pointers, operator overloading in C and C++ has been eliminated in java to
make it simple. So the programmers who know C or C++ will find java as familiar language.
Object-oriented
What is an Object?
Object is a thing that exists in the world and can be distinguished from others for example a
pen, a book, a bench ect .
The languages like c and C++ are platform dependent means which depends on particular
operating system. Java is platform independent which means compiled into platform specific
machines while Java is a write once, run anywhere language.
Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java is
secured because No explicit pointer, Java Programs run inside a virtual machine sandbox
Classloader: Class loader in Java is a part of the Java Runtime Environment (JRE)
which is used to load Java classes into the Java Virtual Machine dynamically. It adds
security by separating the package for the classes of the local file system from those
that are imported from network sources.
Bytecode Verifier: It checks the code fragments for illegal code that can violate
access right to objects.
Security Manager: It determines what resources a class can access such as reading
and writing to the local disk.
Java language provides these securities by default. Some security can also be provided by an
application developer explicitly through SSL, JAAS, Cryptography, etc.
Robust
Robust simply means strong. Java is robust because it uses strong memory management. There is
a lack of pointers that avoids security problems. There is automatic garbage collection in java
which runs on the Java Virtual Machine to get rid of objects which are not being used by a Java
application anymore. There are exception handling and the type checking mechanism in Java.
All these points make Java robust.
Architecture-neutral
The Java designers made several hard decisions in the Java language and the Java Virtual
Machine in an attempt to alter this situation. Their goal was “write once; run anywhere,
anytime , forever.” To a great extent, this goal was accomplished.
Portable
Java is portable because it facilitates you to carry the Java byte code to any platform. It doesn't
require any implementation.
High-performance
Java is faster than other traditional interpreted programming languages because Java byte code
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 distributed because it facilitates users to create distributed applications in Java. We can
write programs which capture information and distributed it to clients. This is possible because
java can handle TCP/IP protocols.
Multi-threaded
Dynamic
Java is a dynamic language. It supports dynamic loading of classes. It means classes are
loaded on demand. It also supports functions from its native languages, i.e., C and C++.
Scalability:
Java platform can be implemented on wide range of computers with varying levels of
resources. This is possible because java is compact and platform independent.
Java virtual Machine is the heart of entire java program execution process.
Class Loader:
First of all the .java file written by the programmer will be compiles by java compiler the it
generates .Class file called as byte code this .class file will be given to class loader .It loads .class
file into memory. Then it checks the byte code is proper or not it was suspicious the execution is
rejected, if it is proper sufficient memory will be allocated for execution.
Method Area:
Method area stores code of variables and code in the methods (functions)
Heap:
This is area where the objects are created. Whenever JVM loads a class, a method and
heap area is immediately created in it.
Java Stacks:
Method area is used to store methods. If java program requires more memory to store
data and results then java stacks are used.
Program Counter is a register which stores the address the method Instruction to be
executed.
Native methods such as C and C++ functions will be executed in native method stack .To
execute native methods it requires native method library these are connected to JVM by native
method interface.
Execution Engine contains interpreter and JIT(Just It Tie ) compiler which are responsible for
converting byte code to machine instructions .This will be given to interpreter as byte code is
error free interpreted runs it faster.JVM uses both interpreter and compiler .This technique is
called adaptive optimizer.
Java Applications
2. Mobile Applications:
3. Embedded Systems:
Embedded systems, ranging from tiny chips to specialized computers, are components of larger
electromechanical systems performing dedicated tasks. Several devices, such as SIM cards, blue-
ray disk players, utility meters and televisions, use embedded Java technologies. According to
Oracle, 100% of Blu-ray Disc Players and 125 million TV devices employ Java.
4. Web Applications:
Java provides support for web applications through Servlets, Struts or JSPs. The easy
programming and higher security offered by the programming language has allowed a large
number of government applications for health, social security, education and insurance to be
based on Java. Java also finds application in development of eCommerce web applications using
open-source eCommerce platforms, such as Broadleaf.
The Java ecosystem today contains multiple Java web servers and application servers. While
Apache Tomcat, Simple, Jo!, Rimfaxe Web Server (RWS) and Project Jigsaw dominate the web
server space, WebLogic, WebSphere, and Jboss EAP dominate commercial application server
space.
6. Enterprise Applications:
Java Enterprise Edition (Java EE) is a popular platform that provides API and runtime
environment for scripting and running enterprise software, including network applications and
web-services. Oracle claims Java is running in 97% of enterprise computers. The higher
performance guarantee and faster computing in Java has resulted in high frequency trading
systems like Murex to be scripted in the language. It is also the backbone for a variety of banking
applications which have Java running from front user end to back server end.
7. Scientific Applications:
Java is the choice of many software developers for writing applications involving scientific
calculations and mathematical operations. These programs are generally considered to be fast
and secure, have a higher degree of portability and low maintenance. Applications like
MATLAB use Java both for interacting user interface and as part of the core system.
Program Structure:
As java is pure object oriented language everything in java program should place in
class even main should be placed in a class.
sample program
class Example
{
public static void main(String args[])
{
System.out.println("Hello World");
}
}
Output:
C:/>javac Example.java
Hello World
1. Comments
While writing a program it is important it should be readable and understandable for this purpose
we use comments .When we write a comment in a program we can understand what the is
program is doing and users can understand the code. There are 3 types of comments
3) Java documentation comments: these are used for giving description for every feature
in a java program. This description proves helpful in creation of .html file called API It
starts wit /** and ends with */ for example
/** description about a class */
Code
/** description about method */
Method code
3. Modifiers(Access Specifies):
An access specifier is a key word that tells us how to access the members of a class .We can use
access specifiers before a class and its members. There are four access specifiers available in
Java:
private: 'private' members of a class are not accessible anywhere outside the class. They
are accessible only within the class by the methods of that class.
Example:
class A{
private int a=40;
private void msg()
{
System.out.println("Hello java");
}
}
Protected: The protected access modifier is accessible within package and outside the
package but through inheritance only.
The protected access modifier can be applied on the data member, method and constructor.
It can't be applied on the class.
class A{
protected int a=40;
protected void msg()
{
System.out.println("Hello java");
}
}
default: If no access specifier is given, then the Java compiler uses a 'default' access
specifier. 'default' members are accessible outside the class, but within the same
directory. ·
class A{
int a=40;
void msg()
{
System.out.println("Hello java");
}
}
We generally use private for instance variables, and public for methods: In Java, classes
cannot be declared by using 'private'. If we declare those class are not accessed by java
compiler. But inner classes can be specified as public
4. Statements
A statement specifies an action in a Java program, such as assigning the sum of x and y
to z, printing a message to the standard output, writing data to a file, etc.
Declaration statement
Expression statement
Control flow statement
Declaration Statement
int num;
String str;
Expression Statement
An expression with a semicolon at the end is called an expression statement. For example,
num++;
++num;
num--;
--num;
//Assignment expressions
num = 100;
num *= 10;
System.out.println("This is a statement");
someMethod(param1, param2);
By default, all statements in a Java program are executed in the order they appear in the
program. Sometimes you may want to execute a set of statements repeatedly for a
number of times or as long as a particular condition is true.
5. Blocks
A block in Java is a group of one or more statements enclosed in braces. A block begins
with an opening brace ({) and ends with a closing brace (}). Between the opening and
closing braces, you can code one or more statements. For example:
int i, j;
i = 1;
j = 2;
A block is itself a type of statement. As a result, any time the Java language requires a
statement, you can substitute a block to execute more than one statement.
6. Classes
Class is the collection data members and member functions. Since as java is pure object
oriented programming language, we cannot write java program without a class .In java
class is a keyword and then write the class name i.e.
Class Demo
{
Statements;
}
The class code stars with {and ends with} in the above program inside a class we have
written main () method.
7. Methods
A method is a set of code which is referred to by name and can be called (invoked) at any
point in a program simply by utilizing the method's name. Think of a method as a
subprogram that acts on data and often returns a value.
Each method has its own name. When that name is encountered in a program, the
execution of the program branches to the body of that method. When the method is
finished, execution returns to the area of the program code from which it was called, and
the program continues on to the next line of code.
Syntax:
Returntype Method name()
{
Code
}
JVM is the program written by java soft people and main () is written by us. Since
main () method should be available to JVM, it should be declared as public.
As main () is a method and a method is executed by calling a method.
Create a object to class to which the method belongs to. The syntax of creating the object
is:
We call main () method without creating an object .such methods are called static
methods and should be declared as static. If a method is not returning any value then
should be defined as void before method name .void means no value i.e. main () method
returns nothing. main () method is followed by String args[] main () method also accepts
some data from us. For example, it accepts group of strings, which is also called as sting
type array.
args[] is a array of string type it stores group of stings ,it also stores numbers but
stores it in the form of string only. The values passed to main are called as arguments
these arguments are stored in args[].
#include<stdio.h>
A header file is the file which contains functions code of function in a program. For example
<stdio.h> contains functions like printf(),sacnf() etc., so if we what to use this functions we have
include<stdio.h>. But in java to include a header file by using import statement.
Example:
Import java.lang.system;
When we use include statement the compiler goes to library and searches for that particular
header file .if it was found it copies the content of header file into program where the # include is
statement is written. Thus if program has 3lines and header file has 100 lines finally it has 103
lines which occupies the program memory which is wasted and processor tie is wasted. But in
java we use import statement instead of include by using import Java JVM go to library execute
the code there and substitute the result into program .so the addition storage for header file saved
and processor time is not wasted.
The import statement is used to import classes or interfaces which lo located in packages.
A package is a kind of directory that contains group of classes and interfaces. Java has several
such packages in its library.
Java library
|
Packages
|
Class’s |interfaces
|
Methods
Output:
C:\>javac Demo.java
C:\>java Demo
Hello world
Example2:
In the above program to display hello world we print() method in java method are called by
using objectname.methodname().print() method belongs to printStream class so call it by
creating object to printStream calss
But it is not possible to create object to printStream class directly, so it is alternatively called as
System.out.Here System is the class name and out is static variable in System class .out is called
a field in System class .i.e.
System.out.print(“Hello World”);
Finally, save the above program by Demo.java .Now go to System prompt and compile by using
java compiler as follows
javac prorgramname.java
After compiling java program the .class file is generated that contains byte code instructions.
This file is executed by JVM as:
Java calssname
Output:
C:\>javac Demo.java
C:\>java Demo
Hello world
Variables:
Variable is memory location which holds values. A variable is assigned with a data type. Here
are three types of variables in java: local, instance and static. Variable is name of reserved area
allocated in memory. In other words, it is a name of memory location. It is a combination of
"vary + able" that means its value can be changed.
Syntax:
Datatype variablename=value;
The type is one of Java’s atomic types, or the name of a class or interface. Thevariablename is the name
of the variable. You can initialize the variable by specifying an equal sign and a value. Keep in mind that
the initialization expression must result in a value of the same (or compatible) type as that specified for
the variable. To declare more than one variable of the specified type, use a comma separated list
Method Parameters
While passing values to member methods we need parameter variables. Parameters are not
fields; they are always called variables and used only to copy their values into the formal
parameters. Variables or values passed to a method by caller are called actual parameters, and
the callee receives these values in formal parameters. Formal parameters are local variables to
that particular method.
Output:
30
Dynamic Initialization:
class DynInitilization {
int c = Math.sqrt(a*b);
Output:
In the above example a ,b are declared locally as constant values and However, c is initialized
dynamically. The program uses another of Java’s built-in methods, sqrt ( ), which is a member of
the Math class, to compute the square root of its argument.
Variable Initialization
Variable Initialization ME
assigning a value to variables. In Java, you can assign a value to variables in two ways:
1. Static - This means that the memory is determined for variables when the program
starts.
2. Dynamic - Dynamic means that in Java, you can declare variables anywhere in the
program, because when the statement is executed the memory is assigned to the
boolean false
char \u0000
int,short,byte / long 0 / 0L
The scope of a variable is defined as within the block or outside the block. Block starts with an
opening curly brace and ended by a closing curly brace. A block defines a scope. Thus, each time
you start a new block, you are creating a new scope. A scope determines what objects are visible
to other parts of your program. Lifetime of a variable is defined as how long the variable exists
before it is destroyed. Destroying variables refers to de-allocating the memory that was allotted
to the variables it was declared It also determines the lifetime of those objects.
Languages like C and C++ defines the scope in two ways i.e. local and global variables .local
variables are the variables that are defined inside main() method global variables are that are
defined outside the main() method
However, these traditional scopes do not fit well with Java’s strict, object-oriented model. In
Java we have the two major scopes that are those defined by a class and those defined by a
method.
The scope defined by a method begins with its opening curly brace; variables declared inside a
scope is not visible to code that is defined outside that scope. Thus, when we declare a variable
within a scope, we are localizing that variable and protecting it from unauthorized access.
Indeed, the scope rules provide the foundation for encapsulation.
Scopes can be nested. That can be defined as block within a block we are creating a new, nested
scope. When this occurs, the outer block scope encloses the inner block scope. This means that
objects declared in the outer scope will be visible to code within the inner scope. However, the
reverse is not true. Objects declared within the inner scope will not be visible outside it. Let us
take an example for demonstration of above concept
class ScopDemo
a = 1;
if(a >=0)
}
Separators
In Java, there are a few characters that are used as separators. The most commonly used
separator in Java is the semicolon. As you have seen, it is used to terminate statements. The
separators are shown in the following table:
Expression:
for example:
int a=10;
int b=20;
int c=a+b;
Data types:
A variable is a memory location which holds data and the type of the data has to be specified i.e.
int a; //here int is the type of variable a
In Java we have eight primitive types of data: byte, short, int, long, char, float, double, and
boolean.
The primitive types are also commonly referred to as simple types; these can be put in four
groups:
• Integers:It has byte, short, int, and long, which are for whole-valued
signed numbers.
• Floating-point: It has float and double, which represent numbers with fractional precision.
• Characters this has char, which represents symbols in a character set,
like letters and numbers.
• Boolean: It is a special type for representing
true/false values.
Integer types:
Numbers without fractional parts and decimal parts is called integers
Data Type Size range
byte 1 bytes 128 to +127
Long 8 bytes -9223372036854775808
to
+9223372036854775807
Int 4 bytes -2147483648 to
+2147483647
short 2 bytes -32768 to +32767
For example long is a signed 64-bit type and is useful for those occasions where an int type is
not large enough to hold the desired value. The range of a long is quite large. This makes it
useful when big, whole numbers are needed.
Floating-Point Types
Floating-point numbers, also known as real numbers, are used when evaluating expressions that
require fractional precision
Data Type Size range
Float 4 bytes 1.4e–045 to 3.4e+038
Double 8 bytes 4.9e–324 to 1.8e+308
Characters
This data type represents a single character
Data Type Size range
Char 2 bytes 0 to 65536
Characters are represented as char in java. In C/C++ char is 8 bits wide. This is not the case in
Java. Instead, Java uses Unicode to represent characters. Unicode defines a fully international
character set that can represent all of the characters found in all human languages. It is a
unification of dozens of character sets, such as Latin, Greek, Arabic, Cyrillic, Hebrew, Katakana,
Hangul, and many more. For this purpose, it requires 16 bits. Thus, in
Java char is a 16-bit type. The range of a char is 0 to 65,536.
char a=’h’
Here ‘a’ is a variable of type character which stores ‘h’ as a value.
Booleans
Java has a primitive type, called boolean, which have two values either true or false
This is the type returned by all relational operators, as in the case of a < b. boolean is also the
type required by the conditional expressions that govern the control statements such as if and
for. True or false are represented as 0(false) or 1(true)
Identifiers:
Identifiers are used for class names, method names, and variable names. An identifier may be
uppercase and lowercase letters, numbers, or the underscore and dollar-sign characters. They
must not begin with a number, lest they be confused with a numeric literal. Again, Java is case-
sensitive, so VALUE is a different identifier than Value.
Some examples of valid identifiers are
MinVal,a,cse@23,
Invalid are
a-b,3c,a/b
example
int a-b=20;//invalid
ConstantVariables
Using final you can define variables whose values never change. You MUST place an initial
value into such a "constant" variable. If you do not place this initial value, Java will never let
you assign a value at a later time because you cannot do anything to change the value of a final
(constant) variable.
final int ageLimit = 21; // this value cannot be changed
Literals
A literal represents a value that is stored into a variable directly in the program. See the
following
Examples:
boolean a= true;
short s = 1;
In the preceding statements, the right hand side values are called literals because these values are
being stored into the variables shown at the left hand side. As the data type of the variable
changes, the type of the literal also changes. So we have different types of literals. These are as
follows:
Integer literals
Float literals
Character literals
String literals
Boolean literals
Integer Literals
They represent the fixed integer values like 55,-1, 345450, etc. All these numbers belong to
decimal system.
int a=0x1c;// here 0x1c is hexadecimal value
.
Float Literals
They represent fractional numbers. These are the numbers with decimal points like 3.0,-1.2 etc
which should of float or double type variables. While writing these literals, we can use E or e for
scientific notation, F or f for float literal, and o or ct for double literal {this is the default and
generally omitted).
Double x=154.25;
Float b=2.3F // floating value
Character Literals
Character literals have characters like A, b, 9, etc, Special characters, like? , @, etc., Unicode
characters, like \u0042 (this represents a in ISO Latin 1 character set)., Escape sequence
(backslash codes) like \n, \b, etc.Character literals should be enclosed in single quotation marks.
The preceding unicode characters and escape sequence can also be represented as strings.
String Literals
String literals represent objects of String class. For example, cse , amith, AP16cz1234, etc. will
come under string literals, which can be directly stored into a String object.
Boolean Literals
Boolean literals represent only two values-true and false.
Operators:
Operator is a symbol which performs operations, operator has to be placed between operands .i.e.
X - Y
Operand Operand
unary
In Java, unary arithmetic operators are used to increasing or decreasing the value of an
operand. Increment operator adds 1 to the value of a variable, whereas the decrement operator
decreases a value.
Increment and decrement unary operator works as follows:
Syntax:
val++;
val--;
These two operators have two forms: Postfix and Prefix. Both do increment or decrement in
appropriate variables. These two operators can be placed before or after of variables. When it is
placed before the variable, it is called prefix. And when it is placed after, it is called postfix.
Following example table, demonstrates the work of Increment and decrement operators with
postfix and prefix:
Example Description
val = a++; Store the value of "a" in "val" then increments.
val = a--; Store the value of "a" in "val" then decrements.
val = ++a; Increments "a" then store the new value of "a" in "val".
val = --a; Decrements "a" then store the new value of "a" in "val".
Programs to Show How Assignment Operators Works
Example:
public class unaryop {
public static void main(String[] args) {
int r = 6;
System.out.println("r=: " + r++);
System.out.println("r=: " + r);
int x = 6;
System.out.println("x=: " + x--);
System.out.println("x=: " + x);
int y = 6;
System.out.println("y=: " + ++y);
int p = 6;
System.out.println("p=: " + --p);
}}
Output:
r=: 6 r=: 7 x=: 6 x=: 5 y=: 7 p=: 5
Ternary operators: ternary operator is also known as the conditional operator. This operator
consists of three operands and is used to evaluate Boolean expressions. The goal of the operator
is to decide, which value should be assigned to the variable. The operator is written as −
variable x = (expression) ? value if true: value if false
public class Test {
public static void main(String args[])
{
int a, b;
a = 10;
b = (a == 1) ? 20: 30;
System.out.println( "Value of b is : " + b );
b = (a == 10) ? 20: 30;
System.out.println( "Value of b is : " + b ); }}
Output
Value of b is : 30Value of b is : 20
Arithmetic Operators these operators perform mathematical operations like addition, subtraction,
multiplication etc
The operands of the arithmetic operations are of numeric type. The Boolean operands are not
allowed to perform arithmetic operations. The basic arithmetic operators are: addition,
subtraction, multiplication, and division.
// Example of % operator.
class Modlusdemo
{
public static void main(String args[])
{
int x = 42;
double y = 42.25;
System.out.println("x mod 10 = " + x % 10);
System.out.println("y mod 10 = " + y % 10);
}
}
output:
javac Modlusdemo.java
java Modlusdemo
x mod 10 = 2
y mod 10 = 2.25
Writing ++ before a variable is called pre incrementation and writing ++ after a variable is called
post incrementation. In pre incrementation; incrementation is done first and any other operation
is done next. In post incrementation, all the other operations are done first and incrementation is
done only at the last. Let us take an example
IncDec.java
// Example on ++ and --
class IncDecDemo
{
public static void main(String args[])
{
int a = 1;
int b = 2;
int c;
int d;
c = ++b; //pre increment
d = a--; //post decrement
c++; //post increment
d--; //post decrement
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
}
output::
javac IncDecDemo.java
java IncDecDemo
a=0
b=3
c=4
d=0
The Bitwise
Java defines several bitwise operators that can be applied to the integer types, long, int, short,
char, and byte. These operators act upon the individual bits of their operands. They are
summarized in the following table:
These operators are again classified into 3 categories: Logical operators, Shift operators, and
Relational operator
The Bitwise Logical Operators
The bitwise logical operators are &, |, ^, and ~. The following table shows the outcome of each
operation. The bitwise operators are applied to each individual bit within each operand.
The Bitwise OR
The OR operator, |, combines bits such that if either of the bits in the operands is a 1, then the
resultant bit is a 1, as shown here:
00101010 42
| 00001111 15
00101111 47
The Bitwise XOR
The XOR operator, ^, combines bits such that if exactly one operand is 1, then the result is
1.Otherwise, the result is zero. The following example shows the effect of the ^. This example
also demonstrates a useful attribute of the XOR operation. Notice how the bit pattern of 42 is
inverted wherever the second operand has a 1 bit. Wherever the second operand has a 0 bit, the
first operand is unchanged. You will find this property useful when performing some types of bit
manipulations.
00101010 42
^ 00001111 15
00100101 37
Using the Bitwise Logical Operators
The following program demonstrates the bitwise logical operators:
BitLogic.java
// Demonstrate the bitwise logical operators.
class BitLogic
{
public static void main(String args[])
{
int a = 3; // 0 + 2 + 1 or 0011 in binary
int b = 6; // 4 + 2 + 0 or 0110 in binary
int c = a | b;
int d = a & b;
int e = a ^ b;
int f = (~a & b) | (a & ~b);
int g = ~a & 0x0f;
System.out.println(" a|b = " +c);
System.out.println(" a&b = " +d);
System.out.println(" a^b = " +e);
System.out.println("~a&b|a&~b = " + f);
System.out.println(" ~a = " + g);
}
}
output:
D:\>javac BitLogic.java
D:\>java BitLogic\
a|b =7
a&b=2
a^b =5
~a&b|a&~b =5
~a = 12
Relational Operators
The relational operators determine the relationship that one operand has to the
other.Specifically, they determine equality and ordering. The relational operators are shown here:
The outcome of these operations is a boolean value. The relational operators are most frequently
used in the expressions that control the if statement and the various loop statements.Any type in
Java, including integers, floating-point numbers, characters, and Booleans can be compared
using the equality test, ==, and the inequality test, !=. Notice that in Java equality is denoted with
two equal signs, not one. (Remember: a single equal sign is the assignment operator.) Only
numeric types can be compared using the ordering operators. That is, only integer, floating-point,
and character operands may be compared to see which is greater or less than the other.
System.out.println("a == b = " + (a == b) );
System.out.println("a != b = " + (a != b) );
System.out.println("a > b = " + (a > b) );
System.out.println("a < b = " + (a < b) );
System.out.println("b >= a = " + (b >= a) );
System.out.println("b <= a = " + (b <= a) );
}}
Output
a == b = false
a != b = true
a > b = false
a < b = true
b >= a = true
b <= a = false
Short-Circuit Logical Operators (|| and &&)
Java provides two interesting Boolean operators not found in many other computer languages.
These are secondary versions of the Boolean AND and OR operators, and are known as short
circuit logical operators. When we use || operator if left hand side expression is true, then the
result will be true, no matter what is the result of right hand side expression. In the case of && if
the left hand side expression results true, then only the right hand side expression is evaluated.
Example 1: (expr1 || expr2) Example2: (expr1 && expr2)
& and &&
Java has two operators for performing logical And operations: & and &&. Both combine two
Boolean expressions and return true only if both expressions are true.
Here’s an example that uses the basic And operator (&):
if ( (salesClass == 1) & (salesTotal >= 10000.0) )
commissionRate = 0.025;
Here, the expressions (salesClass == 1) and (salesTotal >= 10000.0) are evaluated separately.
Then the & operator compares the results. If they’re both true, the & operator returns true. If one
is false or both are false, the &operator returns false.
The && operator is similar to the & operator, but can make your code a bit more efficient.
Because both expressions compared by the & operator must be truefor the entire expression to
be true, there’s no reason to evaluate the second expression if the first one returns false.
The & operator always evaluates both expressions. The && operator evaluates the second
expression only if the first expression is true.
Conditional operators
The ? Operator
Java includes a special ternary (three-way) operator that can replace certain types of if-then-else
statements. This operator is the ? It can seem somewhat confusing at first, but they? Can be used
very effectively once mastered.
The ? has this general form:
expression1 ? expression2 : expression3
Here, expression1 can be any expression that evaluates to a boolean value. If expression1 is
true, then expression2 is evaluated; otherwise, expression3 is evaluated. The result of the?
Operation is that of the expression evaluated. Both expression2 and expression3 are required to
return the same type, which can’t be void. Here is an example of the way that the ? is employed:
Test.java
class Test
{
public static void main(String args[])
{
int x=4,y=6;
int res= (x>y)?x:y;
System.out.println("The result is :"+res);
}
}
output:
D:\>javac Test.java
D:\>java Test
The result is :6
dot(.)operator:
The (.) operator is also known as member operator it is used to access the member of a package
or a class.
example
System.out.println(i);
The parentheses ( ) and the type or list of types they contain are sometimes called the cast
operator.
Syntax:
instanceof operator and isInstance() method both return a boolean value. Consider an example:
public class Test
{
public static void main(String[] args)
{
Integer i = new Integer(5);
Operator Precedence
Table shows the order of precedence for Java operators, from highest to lowest. Notice that the
first row shows items that you may not normally think of as operators: parentheses, square
brackets, and the dot operator. Technically, these are called separators, but they act like
operators in an expression. Parentheses are used to alter the precedence of an operation. As you
know from the previous chapter, the square brackets provide array indexing. The dot operator is
used to dereference objects.
Using Parentheses
Parentheses raise the precedence of the operations that are inside them. This is often necessary to
obtain the result you desire. For example, consider the following expression:
a >> b + 3
This expression first adds 3 to b and then shifts a right by that result. That is, this expression can
be rewritten using redundant parentheses like this:
a >> (b + 3)
However, if you want to first shift a right by b positions and then add 3 to that result, you will
need to parenthesize the expression like this:
(a >> b) + 3
When you assign value of one data type to another, the two types might not be compatible with
each other. If the data types are compatible, then Java will perform the conversion automatically
known as Automatic Type Conversion and if not then they need to be casted or converted
explicitly. For example, assigning an int value to a long variable.
Widening conversion takes place when two data types are automatically converted. This happens
when:
import java.io.*;
class CastTest
{
public static void main(String args[])
{
int a=258;
byte b;
b=(byte) a;
System.out.print(" The result is :" +b);
}
}
output
javac CastTest.java
java CastTest
The result is : 2
Control Statements
The control statements are used to control the flow of execution and branch based on the status
of a program.In a program, we modify and repeat the data several times. We need some tools for
these modifications that will control the flow of the program, and to perform this type of tasks
Java Provides control statements. The control statements in Java are categorized into 3
categories:
i. Selection statements
ii. Iteration statements
iii. Jump statements
The selection statements include: if and switch. These are used to choose different Paths of
execution based on the outcome of the conditional expression.
if statement: This is the Java's conditional branch statement. This is used to route the execution
through two different paths. The general form of the
if statement will be as follow:
if (conditional expression)
{
statement1
}
else
{
statement2
}
Here the statements inside the block cane single statement or multiple statements. The
conditional expression is any expression that returns the Boolean value. The else clause is
optional. The if works as follows: if the conditional expression is true, then statement1 will be
executed. Otherwise statement2 will be executed.
Example:
Write a java program to find whether the given number is greater than other number or
not?
Gret.java
import java.io.*;
class Gret
{
public static void main(String args[])
{
int a,b;
a=10,b=20;
if(a>b)
{
System.out.println(a+" is greater than "+b);
}
else
{
System.out.println(a+" is lessthan"+b);
}
}
}
output
javac Gret.java
java Gret
10 is lessthan 20
Nested if: The nested if statement is an if statement, that contains another if and else inside it.
The nested if are very common in programming. When we nest ifs, the else always associated
with the nearest if.
The general form of the nested if will be as follow:
if(conditional expresion1)
{
if(conditional expression2)
{
statements1;
}
else
{
satement2;
}
}
else
{
statement3;
}
Example program:
Write a java Program to test whether a given number is positive or negative.
Positive.java
import java.io.*;
class Positive
{
public static void main(String args[]) throws IOException
{
int n;
DataInputStream x=new DataInputStream(System.in);// which takes input from keyboard
n=Integer.parseInt(x.readLine());//converts the input into integer
if(n>-1)
{
if(n>0)
System.out.println(n+ " is positive no");
}
else
System.out.println(n+ " is Negative no");
}
}
<<<< give the output of the above program>>>
class A
{
public static void main(String args[])
{
int n=-1;
if(n>-1)
{
if(n>0)
Write a Java Program to test whether a given character is Vowel or Consonant? ( Using
Switch)
SwitchTest.java
class SwitchTest
{
public static void main(String args[])
char ch;
ch=(char)System.in.read();
switch(ch)
{
//test for small letters
case 'a': System.out.println("vowel");
break;
case 'e': System.out.println("vowel");
break;
case 'i': System.out.println("vowel");
break;
case 'o': System.out.println("vowel");
break;
case 'u': System.out.println("vowel");
break;
//test for capital letters
case 'A': System.out.println("vowel");
break;
default: System.out.println("Consonant");
}
}
}
javac SwitchTest.java
java SwitchTest
a
vowel
The break statement is optional. If you omit the break, execution will continue on into the next
case. It is sometimes desirable to have multiple cases without break statements between them.
For example, consider the following program.
class Switch
{
public static void main(String args[])
{
int month = 4;
String season;
switch (month)
{
case 12:
case 1:
case 2: season = "Winter";
break;
case 3:
case 4:
case 5: season = "Spring";
break;
case 6:
case 7:
case 8: season = "Summer";
break;
case 9:
case 10:
case 11: season = "Autumn";
break;
default: season = "Bogus Month";
}
System.out.println("April is in the " + season + ".");
}
}
javac Switch.java
java Switch
April is in the Spring
Note 1: Here the final value of the i will be 11. Because the body is executed first, then the
condition is verified at the end.
Note 2: The do-while loop is especially useful when you process a menu selection, because you
will usually want the body of a menu loop to execute at least once.
Example program: Write a Java Program to perform various operations like addition,
Subtraction, and multiplication based on the number entered by the user. And Also
Display
the Menu.
DoWhile.java
import java.io.*;
class DoWhile
{
public static void main(String args[]) throws IOException
{
int n,sum=0,i=0;
DataInputStream dis=new DataInputStream(System.in);
do
{
System.out.println("Enter your choice");
System.out.println("1 Addition");
System.out.println("2 Subtraction");
System.out.println("3 Multiplicaton");
n=Integer.parseInt(dis.readLine());
System.out.println("Enter two Numbers");
int a=Integer.parseInt(dis.readLine());
int b =Integer.parseInt(dis.readLine());
int c;
switch(n)
{
case 1: c=a+b;
System.out.println("The addition is :"+c);
break;
case 2: c=a-b;
System.out.println("The difference is :"+c);
break;
case 3: c=a*b;
System.out.println("The multiplication is :"+c);
break;
default:System.out.println("Enter Correct Number");
}
} while(n<=3);
}
}
output:
javac DoWhile.java
// Demonstrate continue.
class Continue
{
public static void main(String args[])
{
for(int i=1; i<=10; i++)
{
if (i%5 == 0) continue;
System.out.print(i + " ,");}
}
}
output:
javac Continue.java
java Continue
1
2
3
4
6
7
8
9
10
After computing the result the control is transferred to the caller method, that main in this case.
The sum is :7
Class:
Class is defined as collection of data members and member functions.It is defined by using a
keyword class,the general syntax of a class is
Class Classname
{
Datamembers;//variables
Memberfunctions;//methods
}
The data or variables, defined within the class are called, instance variable.
The methods also contain the code.
The Class:
A class is a template or blueprint that is used to create objects.
Class representation of objects and the sets of operations that can be applied to such objects.
A class consists of Data members and methods.
The primary purpose of a class is to hold data/information. This is achieved with attributes which
are also known as data members.
The member functions determine the behavior of the class, i.e. provide a definition for
supporting various operations on data held in the form of an object.
Class Classname
{
Datamembers;//variables
Memberfunctions;//methods
}
• The data or variables, defined within the class are called, instance variable.
• The methods also contain the code.
• The methods and instance variable collectively called as members.
• Variable declared within the methods are called local variables.example
Example:
Simple.java
class Simple
{//data member- instance variables
String name;
String branch;
Object:
Object is defined as instance of a class. We know that the class code is along with method code
is stored in method area of ‘JVM’. When object is created memory is created on ‘heap’ and JVM
produces unique reference to the object.
In the above statement classname is name of the class to which you want to create a
object .objectname is any name that you can assign ,new is a keyword which is used to allocate
memory at runtime classname() is a default constructor.
Simple object
There are many ways to initialize the object. The object contains the instance variable.
The variable can be assigned values with reference of the object.
i.e
s.name=”sai”
s.branch=”cse”
Simplemain.java
class Simple
{ //datamember- instance variaables
String name;
String branch;
}
class Simpemain
{
Public satic void main(String args[])
{
//declaring the object and instantiating object
Simple s = new Simple();
// assign values to Simple’s instance variables
s.name=”Sai”;
s.branch=”Cse”;
System.out.println(s.name+"is studying " +s.branch);
}
}
When you compile this program, you will find that two .class files have been created, one for
Simple and one for simplemain. The Java compiler automatically puts each class into its own
.class file. It is not necessary for both the Simple and the Simplemain class to actually be in the
same source file. To run this program, you must execute Simplemain.class. When you do, you
will see the output as
OUTPUT:
C:/>javac Simplemain.java
C:/>java Simplemain
Sai is studying Cse
<<<<<<<<< Add about subclasses>>>>>>>
Methods:
A Java method is a collection of statements that are grouped together to perform an operation.
When you call the System.out.println() method, for example, the system actually executes
several statements in order to display a message on the console.
Creating methods
Classes usually consist of two things: data members (instance variables) and member function
(methods).
This is the general form of a method:
type methodname(parameter-list) {
// body of method
}
Here, type specifies the type of data returned by the method. This can be any valid type,
Including class types that you create. If the method does not return a value, its return type must
be void. The method name of the method is specified by name. This can be any legal identifier
other than those already used by other items within the current scope. The parameter-list is a
sequence of type and identifier pairs separated by commas. Parameters are essentially variables
that receive the value of the arguments passed to the method when it is called. If the method has
no parameters, then the parameter list will be empty. Methods that have a return type other than
void return a value to the calling routine using the following form of the return statement:
return value; Here, value is the value returned.
return min;
}
Calling methods
There are two ways in which a method is called i.e., method returns a value or returning nothing
(no return value).
The process of method calling is simple. When a program invokes a method, the program control
gets transferred to the called method. This called method then returns control to the caller in two
conditions, when −
System.out.println("cse!");
The method returning value can be understood by the following example −
We have created Simple class with data members it can also contain most of the time, we will
use methods to access the instance variables defined by the class.
class Simple
{
//datamember- instance variaables
String name;
String branch;
//data member-methods
void studying()
{
System.out.println(name +" is studying " +branch);
}
}
class Simpemain
{
public static void main(String args[])
{
//declaring two objects object and instantiating objects
Simple s1 = new Simple();
Simple s2 = new Simple();
// assign values to Simple’s instance variables
s1.name="Sai";
s1.branch="Cse";
s2.name="Arun";
s2.branch="IT";
//Calling method by using object
s1.studying ();
s2.studying ();
}
}
output:
javac Simpemain.java
java Simpemain
Sai is studying Cse
Arun is studying IT
Returning a Value
A method can also return the value of specified type. In this case the type of the method should
be clearly mentioned. The method after computing the task returns the value to the caller of the
method.
BoxDemo.java
class Box
{
double width, height, depth;
double volume()
{
return (width*height*depth);
}
}
class BoxDemo
{
public static void main(String args[])
{
Box mybox1 = new Box();
// assign values to mybox1's instance variables
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
double vol;
//calling the method
vol= mybox1.volume();
System.out.println("the Volume is:"+vol);
}
}
output:
javac BoxDemo.java
java BoxDemo
the Volume is:3000.0
Adding a method that takes the parameters
We can also pass arguments to the method through the object. The parameters separated with
comma operator. The values of the actual parameters are copied to the formal parameters in the
method. The computation is carried with formal arguments, the result is returned to the caller of
the method, if the type is mentioned.
Example:
class Box
{
double width, height, depth;
double volume(double w,double h,double d)
{
width=w;
height=h;
depth=d;
return (width*height*depth);
}
}
class BoxDemo
{
public static void main(String args[])
{
Box mybox1 = new Box();
double vol;
//calling the method
vol= mybox1.volume(10,20,30);
System.out.println("the Volume is:"+vol);
}
}
Output:
output:
javac BoxDemo.java
java BoxDemo
the Volume is:6000.0
Method Overloading:
In Java it is possible to define two or more methods within the same class that share the same
name, as long as their parameter declarations are different. When this is the case, the methods are
said to be overloaded, and the process is referred to as method overloading. Method overloading
is one of the ways that Java supports polymorphism.When an overloaded method is invoked,
Java uses the type and/or number of arguments as its guide to determine which version of the
overloaded method to actually call. Thus, overloaded methods must differ in the type and/or
number of their parameters. While overloaded methods may have different return types, the
return type alone is insufficient to distinguish two versions of a method. When Java encounters a
call to an overloaded method, it simply executes the version of the method whose parameters
match the arguments used in the call.
Here is a simple example that illustrates method overloading:
// Demonstrate method overloading.
class OverloadDemo
{
void test()
{
System.out.println("No parameters");
}
// Overload test for one integer parameter.
void test(int a)
{
System.out.println("a: " + a);
}
}
class Overload
{
public static void main(String args[])
{
OverloadDemo ob = new OverloadDemo();
double result;
// call all versions of test()
ob.test();
ob.test(10);
}
}
Output:
javac Overload.java
java Overload
No parameters
a:10
The test() method is overloaded two times, first version takes no arguments, second version takes
one argument. When an overloaded method is invoked, Java looks for a match between
arguments of the methods. Method overloading supports polymorphism because it is one way
that Java implements the ―one interface, multiple methods‖ paradigm.
Example2:
class DisplayOverloading3
{
public void cal(int c, int num)
{
int x=c+num;
System.out.println("with 2 parameters:"+x);
}
public void cal(int a,int b,int d)
{ int z=a+b+d;
System.out.println("with 3 parameters:"+z );
}
}
class Sample3
{
public static void main(String args[])
{
DisplayOverloading3 obj = new DisplayOverloading3();
obj.cal(1,2);
obj.cal(5,4,7);
}
}
output:
javac Sample3.java
java Sample3
with 2 parameters:3
with 3 parameters:16
Summary
------------------------
In this unit, we have learned the basics of the Java like operators ,varibles structure of java program and
JVM architecture along with part of Java,, we also discussed different data types, used in a program.
Control statements are very useful to a programmer for writing better and complex programs, since they
are designed to implement any sort of logic. Whatever the programmer wishes to do in a program, he can
do it with the help of control statements. Since the Procedure oriented a pproach is not suitable for
managing bigger and complex projects, another approach called Object oriented approach is invented.
Object oriented approach advocate using classes and objects in writing programs. I we also learn about
creating methods, method over loading .
Review Questions
-------------------------
1. Define class and object in java.
2. Define the structure of JVM?
3.
4. List and explain Java buzzwords. Which factors are making Java famous language.
5. Give the naming conventions in Java
6. Discuss the principles of object oriented languages in detail.
7. How to use break and continue statements in java?
8. Write about the role of JVM, JAVA API in developing the platform independent java program
with suitable example.
9. Relate objects, classes and methods.
10. What is data abstraction? Differentiate data and procedural abstractions
Programs related to the topics discussed in this unit>
---------------------------------------------------------------------------
1. Write a java program using ternary operator to find maximum of three numbers.
2. What are the two control structures used in java for making decisions? Explain with an example
program.
3. Write a program that shows an Employee class which contains various methods for accessing
employee’s personal information and methods for paying an employee.
4. Design a class that represents a bank account and construct the methods to i) Assign initial
values ii) Deposit an amount iii) Withdraw amount after checking balance iv) Display the name
and balance.
5. Write a java program to illustrate the increment & decrement operators, shift operators and
ternary operator.
6. How to perform type casting in java? Differentiate it from primitive type conversion with an
example program.
7. Write a java program to illustrate the usage of conditional statements and looping statements.
8. Write simple code for sort the employee name, employee salary?
9. Write simple code for Overloading by changing number of arguments
Multiple Choice Questions
6. If different properties and functions of a real world entity is grouped or embedded into a single
element, what is it called in OOP language?
A) Inheritance
B) Polymorphism
C) Abstraction
D) Encapsulation
A)Inheritance
B)Polymorphism
C)Inheritance and polymorphism
D) Encapsulation and Inheritance
8. How many basic features of OOP are required for a programming language to be purely OOP?
A) 7
B) 6
C) 5
D) 4
A)Mozillacoorporation
B)Microsoft
C)sun Microsystems
D)Amazon Inc.
A)D
B)OAK
C)Ecllipse
D)NetBean
A)Bjarne Stroustrup
B)Larry Page
C)James Gosling
A)because the language was unsuccessful , so they created another version and
changed its name to java.
D)because the name was not relevant to the language they created
15.Whiuch was the first purely object oriented programming language developed.
A)Java
B)c++
c)smalltalk
D)kotlin
A)code reusability
B)Modularity
C)Duplicate/Redundant Data
D)Efficient code
B)Use of pointer
A)struct
B)union
C)both A)&B)
A)javadoc
B)java
C)javac
D)rmic
A)strictfp
B)enum
C)instance of
D)transient
21.In the beginning , Java was created in order to –
A)May 27,1993
B)May 27,1994
C)May 27,1995
D)May 27,1992
A)Java 0.1
C)java 1.1
D)java 1.0
A).obj
B).java
C).class
D).jar
B)7
C)8
D)9
26.In Java byte, short, int and long all of these are
A)signed
B) unsigned
D) None of these
27.The smallest integer type is ......... and its size is ......... bits.
A) short, 8
B)byte, 8
C) short, 16
D) short, 16
A)32 and 64
B)64 and 64
C) 32 and 32
D) 64 and 32
29.intx = 0, y = 0 , z = 0 ;
A) -2
B)-1
C) 0
D) 1
System.out.println( ++a ) ;
A) 100
D) None of these
31. Which of the following is the correct expression that evaluates to true if the number x is
between 1 and 100 or the number is negative?
32. What will be the output after compiling and running following code?
intx =5; x *= 3 + 7;
System.out.println(x);
}}
A)22
B)50
C) 10
33. In java, ............ can only test for equality, where as .......... can evaluate any type of the
Boolean expression.
A)switch, if
B)if, switch
C) if, break
D) continue, if
34. Consider the following program written in Java.
class Test{
intx=7;
System.out.println("NumberSeven");
System.out.println("NotSeven");
A)NumberSeven NotSeven
B) NumberSeven
C)NotSeven
D) Error
35. What is the value of a[1] after the following code is executed?
A) 0
B) 1
C) 2
D) 3
A) for(; ;)
C) for(i=0; ; i++)
A)10
B)12
C)13
D)14
38. Which of the following assignment operator does not exist in Java?
A)>>
B) %=
C)>>>
D)<<
A)&&, /, |,{}
C)<, !, ==, ++
D) +, -, [], !=
41. Which of this keyword can be used in a subclass to call the constructor
of superclass?
A)super
B)this
C)extent
D)extends
42. What is the process of defining a method in a subclass having same name & type signature as a
method in its superclass?
A) Method overloading
B) Method overriding
C) Method hiding
D) None of the mentioned
44. Which of these is correct way of calling a constructor having no parameters, of superclass A by
subclass B?
A) super(void);
B) superclass.();
C) super.A();
D) super();
45. At line number 2 below, choose 3 valid data-type attributes/qualifiers among “final, static, native,
public, private, abstract, protected”
A)final,native,private
B)final,static,protected
C)final,private,abstract
D) final, static, public
A)Abstraction
B)Encapsulation
C)Polymorphism
D) None of the mentioned
A)Stringclass
B)Objectclass
C)Abstractclass
D) ArrayList class
48. Which of these method of Object class can clone an object?
A)Objectcopy()
B)copy()
C)Objectclone()
D) clone()
49.Which of these method of Object class is used to obtain class of an object at run time?
A)get()
B)void getclass()
C)class getclass()
D) None of the mentioned
50. What is the output of this program?
class Output
{
publicstaticvoid main(String args[])
{
Object obj =newObject();
System.out.print(obj.getclass());
}
}
a)Object
b)classObject
c)classjava.lang.Object
d) Compilation Error
Answers