[go: up one dir, main page]

0% found this document useful (0 votes)
22 views86 pages

Unit 1

Uploaded by

Dr D Suneetha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views86 pages

Unit 1

Uploaded by

Dr D Suneetha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 86

UNIT-1

Introduction to OOP, Procedural Programming Language and Object Oriented Language,


Principles of OOP, Applications of OOP, History of JAVA, JAVA features, JVM, Program
Structure. Variables, Primitive Data Types, Identifiers, Literals, Operators, Expressions,
Precedence Rules and Associativity, Primitive Type Conversion and Casting, Flow of Control.
Classes and Objects, Class declaration, Creating Objects, Methods, Method Overloading

1.1 Aims and Objectives

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

Learn the origin of the Object Oriented Paradigm.

Know the advantages of Object Oriented Programming.

Recognize attributes and methods for given objects.

Use the dot notation to access attributes and methods of an object.

1.2 Introduction to OOP:

Oop’s is termed as Object-Oriented Programming. It is a programming language which is based


on objects and data. From 1980s the word 'object' has appeared in programming languages, with
almost all languages developed from 1990 having object-oriented features. It is widely accepted
that object-oriented programming is the most important and powerful way of creating software.
Many of the languages (such as C++, Object Pascal, Java, Python etc.) are multi-paradigm
programming languages that members support object-oriented programming

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

Features of object oriented programming are:

• Focus is on data rather than procedure.


• It follows bottom up approach.
• Data structures are designed such that they symbolize the objects.
• Member Functions that operate on the data members of an object are bind together in the data
structure.
• Data is hidden and cannot be accessed by external function.
• Objects may communicate with each other through function.

Object Oriented Programming Paradigm

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:

Object oriented language: Procedural programming language


OOP takes a bottom-up approach in POP follows a top-down approach.
designing a program.

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.

Data hiding is possible in OOP. No easy way for data hiding.


Inheritance is allowed in OOP. No such concept of inheritance in POP.
Operator overloading is allowed. Operator overloading is not allowed
C++, Java.
Pascal, Fortran.

Structure of Procedural programming language

Procedural programming is a programming paradigm, derived from structured programming,


based upon the concept of the procedure call. Procedures, also known as routines, subroutines,
or functions, simply contain a series of computational steps to be carried out. Any given
procedure might be called at any point during a program's execution, including by other
procedures or itself. The first major procedural programming languages first appeared circa
1960, including Fortran, ALGOL, COBOL and BASIC. Pascal and C were published closer to
the 1970s. The C language is structured, efficient and high level language. The structure of
Procedural programming is as follows

Main

Function
Function

Function Function

In above figure we have divided our program into multiple functions.

 In a multi-function program we use global variable to communicate between two


functions.
 Global variable can be use by any function at any time while local variables are
only used within the function.
 But it creates problem in large program because we can’t determine which
global variables (data) are used by which function.
 Also global variables are accessed by all the function so any function can
change its value at any time so all the function will be affected.
 It emphasis on algorithm (doing this ).
 Large programs are divided into smaller programs known as functions.
 Function can communicate by global variable.
 Data move freely from one function to another function.
 Functions change the value of data at any time from any place. (Functions
transform data from one form to another.)
 It uses top-down programming approach.

Object oriented language

 In object-oriented programming we divide program into multiple object.“An


Object is a thing in real world which has certain properties and method.”It may
be any place, person, bank account, bill or any item.

The definition of object oriented programming can be given as,

 “Object oriented programming is technique to divide program into multiple


partition which has data and method and it is known as class. We can create
multiple copies from that class.”

 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.4 Concepts of Object Oriented Programming

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

1.6 Advantages of OOPs


 Code Reuse and Recycling: Objects created for Object Oriented Programs can easily be
reused in other programs.
 Encapsulation: Once an Object is created, knowledge of its implementation is not
necessary for its use. In older programs, coders needed understand the details of a piece
of code before using it .Objects have the ability to hide certain parts of themselves from
programmers. This prevents programmers from tampering with values they shouldn't.
Additionally, the object controls how one interacts with it, preventing other kinds of
errors.
 Design Benefits: Large programs are very difficult to write. Object Oriented Programs
force designers to go through an extensive planning phase, which makes for better
designs with fewer flaws. In addition, once a program reaches a certain size, Object
Oriented Programs are actually easier to program than non-Object oriented ones.
 Software Maintenance: Programs are not disposable. Legacy code must be dealt with on
a daily basis, either to be improved upon or made to work with newer computers and
software. An Object Oriented Program is much easier to modify and maintain than a non-
Object Oriented Program. So although a lot of work is spent before the program is
written, less work is needed to maintain it over time.

1.8 History of java:

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

It promised Write Once, Run Anywhere" (WORA), providing no-cost run-times on


popular platforms. Fairly secure and featuring configurable security, it allowed network- and
file-access restrictions. Major web browsers soon incorporated the ability to run Java applets
within web pages, and Java quickly became popular.

Some features that make java better than C

JAVA is Object-Oriented while C is procedural.


Most differences between the features of the two languages arise due to the use of
different programming paradigms. C breaks down to functions while JAVA breaks down
to Objects. C is more procedure-oriented while JAVA is data-oriented.

2. Java is an Interpreted language while C is a compiled language.

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.

3. C is a low-level language while JAVA is a high-level language.

C is a low-level language while JAVA is a high-level lagunage

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.

5. Pointer go backstage in JAVA while C requires explicit handling of pointers.

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.

JAVA supports function or method overloading-that is we can have two or more


functions with the same name(with certain varying parameters like return types to allow
the machine to differentiate between them). That it to say, we can overload methods
with the same name having different method signatures. JAVA(unlike C++), does not
support Operator Overloading while C does not allow 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.

9. The standard Input & Output Functions.

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.

10. Exception Handling in JAVA and the errors & crashes in C.

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.

Hardware and software requirements

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.

Hardware Requirement for Java

Minimum hardware requirement to download Java on your Windows operating


system as follows:

 Minimum Windows 95 software


 IBM-compatible 486 system
 Hard Drive and Minimum of 8 MB memory
 A CD-ROM drive
 Mouse, keyboard and sound card, if required

Software requirement for Java

Nowadays, Java is supported by almost every operating systems. whether it is a


Windows, Macintosh and Unix all supports the Java application development. So
you can download any of the operating system on your personal computer. Here
are the minimum requirement.

 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

Java is an object-oriented programming language. Everything in Java is an object.

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 .

Java is platform independent

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

Java supports Multi-threading .A thread is like a separate program, executing concurrently.


We can write Java programs that deal with many tasks at once by defining multiple threads. The
main advantage of multi-threading is that it doesn't occupy memory for each thread. It shares a
common memory area. Threads are important for multi-media, Web applications, etc.

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:

Java virtual Machine is the heart of entire java program execution process.

The diagram shows the block diagram of JVM.


It takes the .Class file as input and converts the byte code into machine language that is executed
by processor.

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

The JVM memory has been divided into:

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

 PC(Program counter) registers:

Program Counter is a register which stores the address the method Instruction to be
executed.

 Native Method stacks:

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

1. Desktop GUI Applications:


Java provides GUI development through various means like Abstract Windowing Toolkit
(AWT), Swing and JavaFX. While AWT contains a number of pre-constructed components such
as menu, button, list, and numerous third-party components, Swing, a GUI widget toolkit,
additionally provides certain advanced components like trees, tables, scroll panes, tabbed panel
and lists. JavaFX, a set of graphics and media packages, provides Swing interoperability, 3D
graphic features and self-contained deployment model which facilitates quick scripting of Java
applets and applications.

2. Mobile Applications:

Java Platform, Micro Edition (Java ME or J2ME) is a cross-platform framework to build


applications that run across all Java supported devices, including feature phones and smart
phones. Further, applications for Android, one of the most popular mobile operating systems, are
usually scripted in Java using the Android Software Development Kit (SDK) or other
environments.

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.

5. Web Servers and Application Servers:

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

C:/> java Example

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

1) Single line comments: it has single line as comment. It is represented as //


For example
//This is a java single line comment
2) Multi line comment: If we want to write multiple lines of description then we can use
multi line comment it starts with /* and ends with */ for example

/* This is java multi line comment.

Which can have multiple lines? */

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

2. Reserved words (keywords)


There are 50 keywords currently defined in the Java language (see Table bellow). These
keywords, combined with the syntax of the operators and separators, form the foundation
of the Java language. These keywords cannot be used as names for a variable, class, or
method

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

public class Simple{


public static void main(String args[]){
A obj=new A();
System.out.println(obj.a);//Compile Time Error
obj.msg();//Compile Time Error
}
}
In the above program variable a , msg() method is of private type so they can’t be
accessed outside the class
 public: 'public' members of a class are accessible everywhere. Outside the class. So any
other program can read them and use them.
class A{
public int a=40;
public void msg()
{
System.out.println("Hello java");
}
}

public class Simple{


public static void main(String args[]){
A obj=new A();
System.out.println(obj.a);
obj.msg();
}
}
Output:
40
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");
}
}

public class Simple{


public static void main(String args[]){
A obj=new A();
System.out.println(obj.a);//Compile Time Error
obj.msg();//Compile Time Error
}
}

 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");
}
}

public class Simple{


public static void main(String args[]){
A obj=new A();
System.out.println(obj.a);
obj.msg();
}
}
Output;
40

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

Statements in Java can be broadly classified into three categories:

 Declaration statement
 Expression statement
 Control flow statement

Declaration Statement

A declaration statement is used to declare a variable. For example,

int num;

int num2 = 100;

String str;

Expression Statement

An expression with a semicolon at the end is called an expression statement. For example,

/Increment and decrement expressions

num++;

++num;

num--;

--num;

//Assignment expressions

num = 100;
num *= 10;

//Method invocation expressions

System.out.println("This is a statement");

someMethod(param1, param2);

Control Flow Statement

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
}

8. The main() method


Why should we write main () method?
If main method is not written in a java program JVM will not execute it, main () is the
starting point for JVM to start execution of a java program. Next to class is

public static void main (String args[])

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.

How to call a method?

Create a object to class to which the method belongs to. The syntax of creating the object
is:

Classname objectname=new classname();

Then the method is called as objectname.method();

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.

public static void main (string args[])

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[].

What happens if Sting args[] is not written in main() method?

When main () method is written without String args[] as


Public static void main ().The code will compile but JVM cannot run the code because it
cannot recognize the main () method as the method from where it should start execution
of java program.JVM looks for main () method with string type as parameter.
Based on above discussion the java program is as below

If we write a C or C++ program initially we include the header files by using

#include<stdio.h>

This means a request to C/C++ compiler to include the header file

1. What is header file?

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;

Difference between import and include:

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

let us write our first java program

 The first statement should be import i.e


Import java.lang.System;
That means System is class which is present in language (lang ) sub package that lang
sub package is located in the root package called java. In the above statement the import
statement imports only system class in lang package if we want to import all the classes
and interfaces in a package we use ‘ *’ i.e
Import java.lang.* //* indicates all the classes and interfaces
 Every java program should have at least one class that is as follows
//This is structure of java program
Import java.lang.*;
Class Demo
{
Public static void main(String args[])
{
Statements;
}
}

Output:

C:\>javac Demo.java

C:\>java Demo
Hello world

Example2:

/* This is the first java program


Which prints hello world */
Import java.lang.System;
Class Demo
{
Public static void main(String args[])
{
System.out.print(“Hello World”);
}
}

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

printStream obj.print(“Hello World”);

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

Then we can see the result

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

int a=10; //here a is a variable

Float b=2.3; // b is a variable which is of type float

Char c=’c’; // c is a variable which is of char type

int a, b, c; // declares three ints, a, b, and c.

int d = 3, e, f = 5; // declares three more ints, initializing

Naming Rules and Conventions


While naming Java variables we have to follw some naming rules. Such as:
1. Variable names are case-sensitive.
2. Variable name can be an unlimited-length sequence of Unicode letters and digits.
3. Variable name must begin with either a letter or the dollar sign "$", or the underscore
character "_".
4. Characters except the dollar sign "$" and the underscore character "_" for example, '+' or '?'
or '@' are invalid for a variable name.
5. No white space is permitted in variable names.
6. Variable name we choose must not be a keyword or reserved word.

Java Variable Types


Java has different of variables different types depending upon where are they declared following
are four types of variables.
Local Variables
The scope of local variable is within the block or a method body are a constructor Local
variables are created when control enters into the block or constructor of method's body and are
destroyed once the control exits from the block.
Local variables are only visible to blocks where they are declared; they are not accessible to
outside block.
Instance Variables or Non-Static Fields
Variables that are non-static and declared out the block or a constructor or a method is called
instance variable. Instance variables are created when an object of a class is created by
using new keyword. Objects store their states in non-static instance variables.
Class Variables or Static Fields
Class variables in Java are fields declared with static keyword. Modifier static informs the
compiler that there will be only one copy of such variables created regardless of how many
objects of this class are created. Static variables are created when a class is loaded into the
memory by the class loader and destroyed when a class is destroyed or unloaded. Visibility of
static fields will depend upon access modifiers. Default vales given to the static members will
follow the same rule as it is done in instance variables.

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.

Example: Java Variable Example: multiplying of Two Numbers


class Simple{
public static void main(String[] args){
int a=5;
int b=6;
int c=a*b;
System.out.println(c);
}}

Output:

30
Dynamic Initialization:

Initialization is referred as the process of assigning a value to a variable at declaration time. A


variable is initialized once in its life time. But for class members, the compulsion is not so strict.
If you don't initialize them then compiler takes care of the initialization process. In Java
programmers are allowed to initialize a variable at run time also. Initializing a variable at run
time is called dynamic initialization. The following example which shows how Dynamic
Initialization works

// example on dynamic initilization.

class DynInitilization {

public static void main(String args[])

int a=2, b =8;

// c is dynamically initialized int

int c = Math.sqrt(a*b);

System.out.println(" Square root is: " + c);

Output:

Square root is: 4

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

Following table shows variables types and their default values

data type Default value

boolean false

char \u0000

int,short,byte / long 0 / 0L

float /double 0.0f / 0.0d

any reference type null

The Scope and Lifetime of Variables

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

//example on scope of a variable

class ScopDemo

public static void main(String args[])

int a; // visible to complete main block

a = 1;

if(a >=0)

// begun a new scope

int b = 4; // visible only to this block

// a and b are visible here

System.out.println(“a and b: " + a + " " + b);

System.out.println( “b:”+b) //This statement raises an Error as b not known here

// a is still known here.

System.out.println("a is " + a);

}
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:

An expression is defined as combination of variables, literals, and operators. An expression is a


statement that can convey a value

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

What is the difference between float and double?


Float can represent up to 7 digits accurately after decimal point, whereas double can represent up
to 15 digits accurately after decimal point.

Let us take an example


float a=5.7F
the variable ‘a’ is having a value 5.7 F if F is not written at the end, by default JVM would
have taken it as double and allocates 8 bytes by placing F or f at the end of a value we can ask
the JVM to consider it as a float value and allocates only 4 bytes. Double precision, as denoted
by the double keyword, uses 64 bits to store a value. Double precision is actually faster than
single precision on some modern processors that have been optimized for high-speed
mathematical calculations

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,

Int a=10 //valid

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

Operators are divided into 4 types:

Arithmetic, bitwise, relational, and logical

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 program to perform all the arithmetic operations


Arith.java
import java.io.*;
class Arthe
{
public static void main(String args[])
{
int a,b,c,d;
a=8;
b=4;
//arithmetic addition
c=a+b;
System.out.println("The Sum is :"+c);
//aritmetic subtraction
d=a-b;
System.out.println("The Subtraction is :"+d);
//arithmetic division
c=a/b;
System.out.println("The Divsion is :"+c);
//arithmetic multiplication
d=a*b;
System.out.println("The multiplication is :"+d);
}
}
output:
c:/>javac Arthe.java
c:/>java
The Sum is :12
The Subtraction is :4
The Divsion is :2
The multiplication is :32
.
The Modulus Operator
The modulus operator, %, returns the remainder of a division operation. It can be applied to
Floating-point and integer types. The following demonstrates the %

// 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

Arithmetic Compound Assignment Operators


Java provides special operators that can be used to combine an arithmetic operation with an
assignment.
a = a + 9;
This can be written as:
a += 9;
In the above statement += compound assignment operator . Both statements perform the same
Operation they increase the value of a by 9.
Here is another example,
a = a % 2;
which can be expressed as
a %= 2;
Thus, any statement of the form
var = var op expression;
Increment and Decrement
This operator increases the value of a variable by 1,i.e.
int a=1;
++a makes a=2 //increments a by 1
a++ makes a=3 //increments a by 1

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 NOT


Also called the bitwise complement, the unary NOT operator, ~, inverts all of the bits of its
operand. For example, the number 42,which has the following bit pattern?
00101010
becomes
11010101
after the NOT operator is applied.
The Bitwise AND
The AND operator, &, produces a 1 bit if both operands are also 1. A zero is produced in all
other cases. Here is an example:
00101010 42
& 00001111 15
00001010 10

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

Shift Operators: (left shift and right shift)

The Left Shift


The left shift operator, <<, shifts all of the bits in a value to the left a specified number of times.
It has this general form:
value << num
Here, num specifies the number of positions to left-shift the value in value. That is, the <<
moves all of the bits in the specified value to the left by the number of bit positions specified by
num.
The Right Shift
The right shift operator, >>, shifts all of the bits in a value to the right a specified number of
times. Its general form is shown here:
value >> num
Here, num specifies the number of positions to left-shift the value in value. That is, the >>
moves all of the bits in the specified value to the right by the number of bit positions specified by
num.
ShiftBits.java
class ShiftBits
{
public static void main(String args[])
{
byte b=6;
int c,d;
//left shift
c=b<<2;
//right shift
d=b>>3;
System.out.println("The left shift result is :"+c);
System.out.println("The right shift result is :"+d);
}
}
output:
D:\>javac ShiftBits.java
D:\>java ShiftBits
The left shift result is :24
The right shift result is :0

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.

public class Test {

public static void main(String args[]) {


int a = 10;
int b = 20;

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 Assignment Operator


The assignment operator is the single equal sign, =. The assignment operator works in Java
much as it does in any other computer language. It has this general form:
var = expression;
Here, the type of var must be compatible with the type of expression. The assignment operator
does have one interesting attribute that you may not be familiar with: it allows you to create a
chain of assignments. For example, consider this fragment:
int x, y, z;
x = y = z = 100; // set x, y, and z to 100

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

Type cast operator:


A cast expression converts, at run time, a value of one numeric type to a similar value of another
numeric type; or confirms, at compile time, that the type of an expression is boolean; or checks,
at run time, that a reference value refers to an object whose class is compatible with a specified
reference type or list of reference types.

The parentheses ( ) and the type or list of types they contain are sometimes called the cast
operator.

Syntax:

Identifier2 = (type) identifier1;


Example:
num 1= (int) num2;
instanceofoperator:
Instanceof operator and isInstance() method both are used for checking the class of the object.
But main difference comes when we want to check the class of object dynamically. In this case
isInstance() method will work. There is no way we can do this by instanceof operator.

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

// prints true as i is instance of class


// Integer
System.out.println(i instanceof Integer);
}
}
output:
true
new operator:
It is a operator which is used in the creation object and allocate memory in heap dynamically
(at runtime)

Example for creation of object to above class Simple is as follows


Simple s=new Simple ();
in the above statement 's' is the instance which allocates memory at runtime.

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

Primitive type conversion and casting:


Sometimes one type of value is assigned to another type. If the two types are compatible, then
Java will perform the conversion automatically (this is also called as implicit type conversion)
However, not all types are compatible, and thus, not all type conversions are implicitly allowed.
So we have the cast them by using cast operator which performs explicit conversion.
Automatic
Conversion (implicit conversion)
When one type of data is assigned to another type of variable, an automatic type conversion will
take place if the following two conditions are met:
• The two types are compatible.
• The destination type is larger than the source type.
widening conversion takes place if conditions met. For example, the int type is having 4 bytes of
memory and byte has 1 byte so int holds byte values and no explicit cast statement is required.
int a; //needs 32 bits
byte b=45; //needs the 8 bits
a=b; // here 8 bits data is placed in 32 bit storage. Thus widening takes place.

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 or Automatic Type Conversion

Widening conversion takes place when two data types are automatically converted. This happens
when:

The two data types are compatible.


When we assign value of a smaller data type to a bigger data type.
For Example, in java the numeric data types are compatible with each other but no automatic
conversion is supported from numeric type to char or boolean. Also, char and boolean are not
compatible with each other.
class Test
{
public static void main(String[] args)
{
int i = 100;

//automatic type conversion


long l = i;

//automatic type conversion


float f = l;
System.out.println("Int value "+i);
System.out.println("Long value "+l);
System.out.println("Float value "+f);
}
}
Output:
Int value 100
Long value 100
Float value 100.0

Casting Incompatible Types


If we want to store int value to byte this conversion is not done automatically because byte to
smaller than int this should be done manually and sometimes called as narrowing
conversion .Since you are explicitly making the value narrower so that it will fit into the target
type.The conversion between two incompatible types, done by castoperator. A cast is simply an
explicit type conversion. It has this general form:
Destination-variable= (target-datatype) value Here, target-datatype specifies the desired type
to convert the specified value to. For example,
int a=1234;
byte b=(byte) a;
The above code converts the in to byte. If the integer value is larger than the byte, then it will be
reduced to modulo byte's range.

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)

System.out.println(n+ " is positive no");


}
else
System.out.println(n+ " is Negative no");
}
}
output:
javac A.java
java A
-1 is Negative no

The if-else-if Ladder


A common programming construct that is based upon a sequence of nested if is the if-else-if
ladder. It looks like this:
if(condition)
statement;
else if(condition)
statement;
else if(condition)
statement;
...
else
statement;
The if statements are executed from the top down. As soon as one of the conditions controlling
the if is true, the statement associated with that if is executed, and the rest of the ladder is
bypassed. If none of the conditions is true, then the final else statement will be executed.
Example Program:
Write a Java Program to test whether a given character is Vowel or Consonant?
Vowel.java
import java.io.*;
class Vowel
{
public static void main(String args[]) throws IOException
{
char ch;
ch=(char)System.in.read();
if(ch=='a')
System.out.println("Vowel");
else if(ch=='e')
System.out.println("Vowel");
else if(ch=='i')
System.out.println("Vowel");
else if(ch=='o')
System.out.println("Vowel");
else if(ch=='u')
System.out.println("Vowel");
else
System.out.println("consonant");
}
}
output:
javac Vowel.java
java Vowel
e
Vowel

The Switch statement


The switch statement is Java’s multi way branch statement. It provides an easy way to dispatch
execution to different parts of your code based on the value of an expression. As such, it often
provides a better alternative than a large series of if-else-if statements. Here is the general form
of a switch statement:
switch (expression)
{
case value1:
// statement sequence
break;
case value2:
// statement sequence
break;
...
case valueN:
// statement sequence
break;
default:
// default statement sequence
}
The expression must be of type byte, short, int, or char; each of the values specified in the case
statements must be of a type compatible with the expression. Each case value must be a unique
literal (that is, it must be a constant, not a variable). Duplicate case values are not allowed. The
switch statement works like this: The value of the expression is compared with each of theliteral
values in the case statements. If a match is found, the code sequence following that case
statement is executed. If none of the constants matches the value of the expression, then the
default statement is executed. However, the default statement is optional. If no case matches
and no default is present, then no further action is taken. The break statement is used inside the
switch to terminate a statement sequence. When a break statement is encountered, execution
branches to the first line of code that follows the entire switch statement. This has the effect of
―jumping out‖ of the switch.

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

Nested switch Statements


You can use a switch as part of the statement sequence of an outer switch. This is called a
nested switch. Since a switch statement defines its own block, no conflicts arise between the
case constants in the inner switch and those in the outer switch. For example, the following
fragment is perfectly valid:

switch(expression) //outer switch


{
case 1: switch(expression) // inner switch
{
case 4: //statement sequence
break;
case 5: //statement sequence
break;
} //end of inner switch
break;
case 2: //statement sequence
break;
default: //statement sequence
} //end of outer switch
There are three important features of the switch statement to note:
o The switch differs from the if in that switch can only test for equality, whereas if can evaluate
any type of Boolean expression. That is, the switch looks only for a match between the value of
the expression and one of its case constants.
 No two case constants in the same switch can have identical values. Of course, a switch
statement and an enclosing outer switch can have case constants in common.
 A switch statement is usually more efficient than a set of nested ifs.
Iteration Statements
Java’s iteration statements are for, while, and do-while. These statements create what we
commonly call loops. As you probably know, a loop repeatedly executes the same set of
instructions until a termination condition is met.
i. while
The while loop is Java’s most fundamental loop statement. It repeats a statement or block while
its controlling expression is true. Here is its general form:
while(condition)
{
// body of loop
increment or decrement statement
}
The condition can be any Boolean expression. The body of the loop will be executed as long as
the conditional expression is true. When condition becomes false, control passes to the next line
of code immediately following the loop. The curly braces are unnecessary if only a single
statement is being repeated.
Example program:
Write a java program to add all the number from 1 to 10.
WhileTest.java
import java.io.*;
import java.io.*;
class WhileTest
{
public static void main(String args[])
{
int i=1,sum=0;
while(i<=10)
{
sum=sum+i;
i++;
}
System.out.println("The sum is :"+sum);
}
}
output:
javac WhileTest.java
java WhileTest
The sum is :55
ii. do-while statement
However, sometimes it is desirable to execute the body of a loop at least once, even if the
conditional expression is false to begin with. In other words, there are times when you would like
to test the termination expression at the end of the loop rather than at the beginning Fortunately,
Java supplies a loop that does just that: the do-while. The do-while loop always executes its
body at least once, because its conditional expression is at the bottom of the loop. Its
general form is:
do {
// body of loop
} while (condition);
Each iteration of the do-while loop first executes the body of the loop and then evaluates the
conditional expression. If this expression is true, the loop will repeat. Otherwise, the loop
terminates. As with all of Java’s loops, condition must be a Boolean expression.
Example program:
Write a java program to add all the number from 1 to 10. (using do-while)
WhileTest.java
import java.io.*;
class WhileTest
{
public static void main(String args[])
{
int i=1,sum=0;
do
{
sum=sum+i;
i++;
} while(i<=10);
System.out.println("The sum is :"+sum);
}
}
output:
javac WhileTest.java
java WhileTest
The sum is :55

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

Enter your choice


1 Addition
2 Subtraction
3 Multiplicaton
1
Enter two Numbers
2
3
The addition is :5
iii. for statement
You were introduced to a simple form of the for loop in Chapter 2. As you will see, it is a
powerful and versatile construct. Beginning with JDK 5, there are two forms of the for loop.
The first is the traditional form that has been in use since the original version of Java. The second
is the new ―for-each‖ form. Both types of for loops are discussed here, beginning with the
traditional form. Here is the general form of the traditional for statement:
for(initialization; condition; iteration)
{
// body
}
The for loop operates as follows. When the loop first starts, the initialization portion of the loop
is executed. Generally, this is an expression that sets the value of the loop control variable,
which acts as a counter that controls the loop. It is important to understand that the initialization
expression is only executed once. Next, condition is evaluated. This must be a Boolean
expression. It usually tests the loop control variable against a target value. If this expression is
true, then the body of the loop is executed. If it is false, the loop terminates.
Example program: same program using the for loop
ForTest.java
import java.io.*;
class ForTest
{
public static void main(String args[])
{
int i, sum=0;
for(i=1;i<=10;i++)
{
sum=sum+i;
}
System.out.println("The sum is :"+sum);
}
}
javac ForTest.java
java ForTest
The sum is :55

There are some important things about the for loop


1. The initialization of the loop controlling variables can be done inside the for loop.
Example:
for(int i=1;i<=10;i++)
2. We can write any boolean expression in the place of the condition for second part the loop.
Example: where b is a boolean data type
boolean b=false;
for(int i=1; !b;i++)
{
//body of the loop
b=true;
}
This loop executes until the b is set to the true;
3. We can also run the loop infinitely, just by leaving all the three parts empty.
Example:
for( ; ;)
{
//body of the loop
}
For each version of the for loop:
The for loop also provides another version, which is called Enhanced Version of the for loop.
The general form of the for loop will be as follow:
for(type itr_var:collection)
{
//body of the loop
}
Here, type is the type of the iterative variable of that receives the elements from collection, one
at a time, from beginning to the end. The collection is created sung the array.
Example program:
Write a java program to add all the elements in an array?
ForEach.java
import java.io.*;
class ForEach
{
public static void main(String args[])
{
int a[]={12,13,14,15,16};
int sum=0;
for(int x:a)
{
sum=sum+x;
}
System.out.println("The sum is :"+sum);
}
}
javac ForEach.java
java ForEach
The sum is :70

3. The Jump Statements


Java supports three jump statements: break, continue, and return. These statements transfer
control to another part of your program.
i. break statement
In Java, the break statement has three uses. First, as you have seen, it terminates a statement
sequence in a switch statement. Second, it can be used to exit a loop. Third, it can be used as
a ―civilized‖ form of goto.
Using break to Exit a Loop
By using break, you can force immediate termination of a loop, bypassing the conditional
expression and any remaining code in the body of the loop. When a break statement is
encountered inside a loop, the loop is terminated and program control resumes at the next
statement following the loop. Here is a simple example:
// Using break to exit a loop.
class BreakLoop
{
public static void main(String args[])
{
for(int i=0; i<100; i++)
{
if(i == 10) break; // terminate loop if i is 10
System.out.println("i: " + i);
}
System.out.println("Loop complete.");
}
}
output:
javac BreakLoop.java
javac BreakLoop
i:0
i:1
i:2
i:3
i:4
i:5
i:6
i:7
i:8
i:9

Using break as a Form of Goto


In addition to its uses with the switch statement and loops, the break statement can also be
employed by itself to provide a ―civilized‖ form of the goto statement. For example, the goto
can be useful when you are exiting from a deeply nested set of loops. To handle such situations,
Java defines an expanded form of the break statement. By using this form of break, you can, for
example, break out of one or more blocks of code.
The general form of the labeled break statement is shown here:
break label;
Most often, label is the name of a label that identifies a block of code. This can be a stand-alone
block of code but it can also be a block that is the target of another statement. When this form of
break executes, control is transferred out of the named block. The labeled block must enclose
the break statement, but it does not need to be the immediately enclosing bloc. To name a block,
put a label at the start of it. A label is any valid Java identifier followed by a colon. Once you
have labeled a block, you can then use this label as the target of a break
statement.
Example code:
class Break
{
public static void main(String args[])
{
boolean t = true;
first: {
second: {
third: {
System.out.println("Before the break.");
if(t) break second; // break out of second block
System.out.println("This won't execute");
}
System.out.println("This won't execute");
}
System.out.println("This is after second block.");
}
}
}
output:
javac Break.java
java Break
Before the break.
This is after second block.

ii. continue statement


Sometimes it is useful to force an early iteration of a loop. That is, you might want to continue
running the loop but stop processing the remainder of the code in its body for this particular
iteration. In while and do-while loops, a continue statement causes control to be transferred
directly to the conditional expression that controls the loop. In a for loop, control goes first to the
iteration portion of the for statement and then to the conditional expression. For all three loops,
any intermediate code is bypassed. Here is an example program that uses continue to cause two
numbers to be printed on each line:

// 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

Here all the numbers from 1 to 10 except 5 are printed. as 1,2,3,4,6,7,8,9,10.


iii. return statement
The last control statement is return. The return statement is used to explicitly return from
a method. That is, it causes program control to transfer back to the caller of the method.
As such, it is categorized as a jump statement.
Example code
class Test
{
public static void main(String args[])
{
int a=3,b=4;
int x=method(a,b);
System.out.println("The sum is :"+x);
}
static int method(int x,int y) // called method
{
return (x+y);
}
}
output:

After computing the result the control is transferred to the caller method, that main in this case.

The sum is :7

Classes and objects:

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.

The general form 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 methods and instance variable collectively called as members.
• Variable declared within the methods are called local variables.example

Let us define a simple calss

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.

The creation of object to a class is done as follows

Classname objectname=new calssname();

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”

Here is a complete program that uses the Simple class:

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.

Example of creating method:

public static int minn(int n1, int n2) {


int min;
if (n1 > n2)
min = n2;
else
min = n1;

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 −

the return statement is executed.


it reaches the method ending closing brace.
The methods returning void is considered as call to a statement. Lets consider an example −

System.out.println("cse!");
The method returning value can be understood by the following example −

int result = sum(6, 9);


Example:

Let us add methods to simple calss as follows

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

1.Which of the following is not a part of OOP?


A. Type checking
B. Multitasking
C. Polymorphism
D. Information hiding
2. Who invented OOP?
A) Alan Kay
B) Andrea Ferro
C) Dennis Ritchie
D) Adele Goldberg

3. Why Java is Partially OOP language?


A) It supports usual declaration of primitive data types
B) It doesn’t support all types of inheritance
C) It allows code to be written outside classes
D) It does not support pointers

4.When OOP concept did first came into picture?


A) 1980’s
B) 1970’s
C) 1993
D) 1995
5.Which feature of OOP indicates code reusability?
A) Encapsulation
B) Inheritance
C) Abstraction
D) Polymorphism

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

7. Which feature of OOP is indicated by the following code?


class student{int marks;};
classtopper:public student{int age; topper(int age){this.age=age;}};

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

9.Which feature may be violated if we don’t use classes in a program?


A) Inheritance can’t be implemented
B) Object must be used is violated
C) Encapsulation only is violated
D) Basically all the features of OOP gets violated

10. ___________ underlines the feature of Polymorphism in a class.


A) Nested class
B) Enclosing class
C) Inline function
D) Virtual Function

11.Java programming was developed by

A)Mozillacoorporation

B)Microsoft

C)sun Microsystems
D)Amazon Inc.

12.Earlier name of Java programming Language is

A)D

B)OAK

C)Ecllipse

D)NetBean

13.Which of the following personality is called as father of Java Programming language

A)Bjarne Stroustrup

B)Larry Page

C)James Gosling

D)none of the above

14.Why OAK was renamed to Java ?

A)because the language was unsuccessful , so they created another version and
changed its name to java.

B)because there was another language called Oak

C)none of the above

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

16.Which is not the feature of OOP in general defination

A)code reusability
B)Modularity

C)Duplicate/Redundant Data

D)Efficient code

17.Which feature allows open recursion ,among the following

A)Use of this pointer

B)Use of pointer

C)Use of pass by value

D)Use of parameterized constructor.

18.Java does not contain datatypes like

A)struct

B)union

C)both A)&B)

D)none of the above.

19.Which of the following tool is used to execute java code

A)javadoc

B)java

C)javac

D)rmic

20.Which is not a keyword in java

A)strictfp

B)enum

C)instance of

D)transient
21.In the beginning , Java was created in order to –

A)Create Strong Programming alternative to C++

B)Perform Operations on the Internet

C)Connect many household machines

D)Create high performance OS

22.Java was publicly realeased in

A)May 27,1993

B)May 27,1994

C)May 27,1995

D)May 27,1992

23.the first public implementation was

A)Java 0.1

B)Java preminum 1.0

C)java 1.1

D)java 1.0

24.Following file is human readable in Java programming language.

A).obj

B).java

C).class

D).jar

25. How many primitive data types are there in Java?


A)6

B)7
C)8

D)9

26.In Java byte, short, int and long all of these are

A)signed

B) unsigned

C) Both of the above

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

28. Size of float and double in Java is

A)32 and 64

B)64 and 64

C) 32 and 32

D) 64 and 32

29.intx = 0, y = 0 , z = 0 ;

x = (++x + y-- ) * z++;


What will be the value of "x" after execution ?

A) -2

B)-1

C) 0

D) 1

30.int ++a = 100 ;

System.out.println( ++a ) ;

What will be the output of the above fraction of code ?

A) 100

B)Displays error as ++a is not enclosed in double quotes in println statement

C) Compiler displays error as ++a is not a valid identifier

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?

A) 1 < x < 100 || x < 0


B)((x < 100) && (x > 1)) || (x < 0)

C) ((x < 100) && (x > 1)) && (x < 0)

D) (1 > x > 100) || (x < 0)

32. What will be the output after compiling and running following code?

public class Test{

public static void main(String... args){

intx =5; x *= 3 + 7;

System.out.println(x);

}}

A)22

B)50

C) 10

D) Compilation fails with an error at line 4

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{

public static void main(String args[]){

intx=7;

if(x==2); // Note the semicolon

System.out.println("NumberSeven");

System.out.println("NotSeven");

What would the output of the program be?

A)NumberSeven NotSeven

B) NumberSeven

C)NotSeven

D) Error
35. What is the value of a[1] after the following code is executed?

int[] a = {0, 2, 4, 1, 3};

for(inti = 0; i<a.length; i++)

a[i] = a[(a[i] + 3) % a.length];

A) 0

B) 1

C) 2

D) 3

36. Which of the following for loops will be an infinite loop?

A) for(; ;)

B) for(i=0 ; i<1; i--)

C) for(i=0; ; i++)

D) All of the above

37. Evaluate the value of the expression?6 - 2 + 10 % 4 + 7

A)10
B)12
C)13
D)14
38. Which of the following assignment operator does not exist in Java?
A)>>

B) %=

C)>>>
D)<<

39. The order of precedence from highest to lowest is :

A)&&, /, |,{}

B)%, <=, &&, =

C)<, !, ==, ++

D) +, -, [], !=

40.The && and || operators

A) Combine two numeric values

B)Compare two boolean values

C)Combine two boolean values

D)none of the above

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

43. Which of these keywords can be used to prevent Method overriding?


A) static
B) constant
C) protected
D) final

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”

Public interface Status

/* insert qualifier here */int MY_VALUE =10;

A)final,native,private
B)final,static,protected
C)final,private,abstract
D) final, static, public

46. Which of these is supported by method overriding in Java?

A)Abstraction
B)Encapsulation
C)Polymorphism
D) None of the mentioned

47.Which of these class is superclass of every class in Java?

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

1.[B] 11.[C] 21.[C] 31.[B] 41.[A]

2.[A] 12.[B] 22.[C] 32.[B] 42.[B]

3.[A] 13.[C] 23.[D] 33.[A] 43.[D]

4.[B] 14.[B] 24.[B] 34.[A] 44.[D]

5.[B] 15.[C] 25.[C] 35.[B] 45.[D]

6.[D] 16.[C] 26.[A] 36.[D] 46.[C]

7.[D] 17.[A] 27.[B] 37.[C] 47.[B]

8.[A] 18.[C] 28.[A] 38.[D] 48.[C]

9.[D] 19.[B] 29.[C] 39.[B] 49.[C]

10.[D] 20.[B] 30.[C] 40.[C] 50.[C]

You might also like