Java Unit1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 57

UNIT-1

1. Introduction to OOP:

OOP Stands for Object Oriented Programming.


The main aim of OOPs is to design the object oriented programming languages (OOPL).
If any language supports all the OOPs principles is known as object oriented programming languages.
Examples: C++, JAVA, PHP, .NET, Python, Android, Selenium, Hadoop. Etc.
The main objective of OOP is to store the client input data in the form of “Objects” instead of
functions and procedures.
In OOPs, every object has data and behavior (methods), identify by a unique name, which achieves
through class and happened at object creation.
OOP is focuses mainly on classes and objects.
OOPs mainly used to develop System Softwares like driver softwares, operating system, compiler
softwares, interpreter softwares etc.

Advantages of OOP:
Code Reusability:
1) In object-oriented programming, one class can easily move to another application if we want to use
its properties.
2) For example, a client already having account in Facebook and now he want to register in LinkedIn
application. By using his Facebook credentials, he can register in LinkedIn application, instead of a
separate registration. Therefore, write once and use anywhere leads to re-usability.
Easily identify the bug:
1) When we are programing with procedural programming language takes a lot of time to identify errors
and resolve it.
2) But in object Oriented Programming due to modularity of classes we can easily identify the errors.

2. Procedural Programming Language Vs Object Oriented Language:


Procedure oriented programming:
It uses a set of procedures or functions to perform a task.
When the programmer wants to write a program, he will first divide the task into separate sub tasks,
each of which is expressed as functions.
If we require any extension to the function then we need to recreate the entire program.
In C language, the problem is divided in to sub-problems or sub-procedures. These sub-problems are
again divided continuously until the sub-problem is simple enough to be solved and controlled from a
main( ) function. For example: factorial program.

1
Object Oriented Programming:
Object oriented programming language like C++ and Java uses classes and objects in the programs.
A class is a module that which contains collection of methods (functions) and data (variables) to
perform a specific task.
The main task is divided in to several modules and these are represented as classes.
The method of class that contains the logic to perform operations and variable is used to handle the
client data.
The Object is a memory holds the end users data as part of main memory.
The goal of this methodology is to achieve reliability, reusability and extensibility.
It is easy to modify and extend the features of application, which is possible with Inheritance principle
and no need any recreation.

Comparison:

Procedure Oriented Programming (POP) Object Oriented Programing (OOP)


1) A program is divided in to sub problems 1) A Program is divided in to parts or modules
called as functions. called as objects.
2) It follows Top Down approach 2) It follows Bottom Up Approach
3) In POP, the operations are carried out 3) In OOP, the operations are carried out
through functions. through data rather than functions.
4) It has access specifiers names as public,
4) It does not have access specifiers.
private, etc.
5) Adding new functions leads to recreation
5) It is easy to add new data and methods.
and not easy also.
6) In POP, Data can move freely from 6) In OOP, objects can move and communicate
function to function in the system by using with each other through access specifiers
global data sharing. otherwise, it is not possible.
7) In OOP, Overloading is possible in the form
7) In POP, Overloading is not possible. of function and operator overloading.
8) In POP, it does not have any feature to 8) In OOP, Data Abstraction / Hiding provides
hide the data. It is less secured. more securable.
9) Examples: C, FORTAN, COBOL, etc. 9) Examples: C++, JAVA, .NET, Python, etc.

2
OOPS Principles (concepts):
Object Oriented Programming Structure (OOPS) is a concept with collection of principles named as
follows:
1) Class/Object
2) Encapsulation
3) Data Abstraction
4) Inheritance
5) Polymorphism

1)Class/Object:

Object:

Object is a memory that holds the end users data as a part of main memory (RAM).
Every object has properties and can perform certain actions.
The properties can be represented by variables in our programming.
For example: String name; int age; char sex;
The actions of object are performed by methods. For example, ‘Ravi’ is an object and he can perform
some actions like talking( ), walking( ), eating( ). etc.
So an object contains both variables and methods.

Advantages of storing the data in the form of object:

1. Security: It provides to the data from un-authenticated users.

2. Data can be identified and accessed very easily.

Class:

Class is a container with collection of variables and methods.


Variables are used to handle the clients input data.
Method can contain the logic to perform operations for specific task.
A class is created by using the keyword ‘class’.
A class describes the properties and actions performed by its objects.
A java program can have many numbers of classes and every class should be identified with a unique
class name.
3
It is mandatory to write every java program in the form of class then only JVM allows us to store the
end users data in the form of objects.

Syntax of class:

class classname
{
// List of variables
// List of Methods
}
Example of class:

class Person
{
String name;
int age;
char sex;

void talk( )
{
------
------
}
void eat( )
{
------
------
}
void walk( )
{
------
------
}
}

In the above example, a person class has 3 variables and 3 methods. This class code stored in JVM’s
method area. When we want to use this class, we should create an object to the class as follows:

Object creation Syntax:


In the real time, memory is not allocated for properties (variables and methods) of class at the time
writing of the program and compilation of the program.
The memory is allocated at run time based on the object creation syntax.
JAVA supports “new” keyword to create a new object for a given class in two ways.

Syntax 1: classname reference = new classname( ); // referenced object

Syntax 2: new classname( ); // unreferenced object

The ‘referenced object’ is available in live state for more time, so that it is recommended to use while
accessing multiple methods of a class or same method multiple times.
The ‘unreferenced object’ is automatically deallocated by “Garbage Collector (GC)” before executing
the next time. So that it is highly recommended to access a single method of the class at a time.
4
In Garbage Collector point of view, referenced object means ‘Useful object’ and unreferenced means
‘un-useful’ object.
‘Referenced’ and ‘unreferenced’ object is created by JVM in main memory based on its syntax.
In the above syntax 2, JVM will create a new object for the properties of the given class.
In the above syntax 1, JVM will create a new object along with class reference name. In this case
reference name acts as a pointer.

Examples of object creation:

1) Person raju = new Person( ); // object creation of syntax 1.

2) new Person( ); // object creation of syntax 2.

Examples of object calling:

1) raju.walk( );
2) raju.talk( );
3) new Person( ).walk( );

In the above figure, multiple users are sending the request to the Banking application and the data will
be stored in the main memory in the form of objects and later it will be stored in the secondary memory
(Database).
Note: Without storing the data in the temporary memory, it will never be stored in the permanent
memory.

5
2)Encapsulation:

Encapsulation is a mechanism of combining the state and behavior in a single unit.


The state represents the data and behavior represents the operation.
In JAVA, encapsulation can be achieved by using “class” keyword.
The variables and methods of a class are known as “members” or “properties” of the class.
Generally, the variables in the class are declared by using a keyword ‘private’. This means the
variables are not directly available to any other classes.
The methods of a class are declared as ‘public’. This means the methods can be called and used from
anywhere outside the other classes.
To use the variables from outside, we should take the help of methods. There is no other way of
interacting with the variables.
This means outsiders do not know what variables declared in the class and what code is written in that
method. Since encapsulation provides a protective mechanism for the members of the class.

Example: Write a java class that the variables of the class are not available to any other program.

class Person
{
//variable declarations
private String name = “Vignan”;
private int age = 2002;
//Method
public void talk( )
{
System.out.println(“ Hello, I am” +name);
System.out.println(“ My year of establishment is:” +age);
}
}

3)Data Abstraction:
A class contains lots of data and the user does not need the entire data.
The user requires only some part of the available data. In this case, data abstraction is used to hide the
un-necessary data from the user and un-hide the necessary data to the user.
This concept called as “Data Abstraction”.
In JAVA, Data Abstraction can be achieved by using ‘class’ keyword.
The advantage of abstraction is that every user will view their data according to own requirements.

Example: Write a java class to describe data abstraction.

class Customer
{
String name;
int accno;
float bal;
int mobno;
String email_id;
String addr;

6
void fundsTransfer( )
{
---------------
---------------
}

void updateContactDetails( )
{
---------------
---------------
}
}

In the above program, the variables ‘accno’ and ‘bal’ are necessary for fundsTransfer( ) method and
the remaining variables are not necessary (hidden).
The variables ‘mobno’, ‘email_id’ and ‘addr’ are necessary for updateContactDetails( ) method and
the remaining variables are not necessary.

4)Inheritance:

Creating or deriving a new class from the existing class is known as “Inheritance”.
So a new class can acquires the properties of the existing class and its own properties also.
In JAVA, Inheritance can be achieved by using “extends” keyword.
The class which is giving the properties is known as “parent/base/super” class.
The class which is acquiring the properties is known as “child/sub/derived” class.

The advantages of using inheritance are Code Re-usability, Re-Implementation and Extensibility.

Example: Write a java class to describe nature of Inheritance.

class A
{
int a;
int b;
void method1( )
{
// method body
}
}

class B extends A
{

7
int c;

8
void method2( )
{
// method body
}
}

5)Polymorphism:
In java point of view, if the same method name is existed multiple times with different implementation
(logic) is known as “polymorphism”.
It can be categorized into two types: Static Polymorphism and Dynamic Polymorphism.
Static Polymorphism:
Whatever the method is verified at compile time and the same method is executed at runtime by
following polymorphism principle is known as “static polymorphism/compile time
polymorphism/static binding”.
In JAVA, static polymorphism can be achieved by using overloading.
Example: A java class on method overloading
class A
{
void f1(int x)
{
---------
---------
}
void f1(float y)
{
---------
---------
}
}
Dynamic Polymorphism:
Verifying super class method at compile time and executing derived class method at runtime by following
polymorphism principle is known as “Dynamic polymorphism or Runtime polymorphism or late
binding”.
In JAVA, Dynamic polymorphism can be achieved by using overriding.
Example: A java class on method overriding
class A
{
void f1(int x)
{
---------
---------
}
}
class B extends A
{
void f1(int x)
{
---------
---------
}
}

9
Introduction to Software:
Def of software:
Software is a collection of programs. A program is a collection of instructions used to perform an
operation.
Either programs or softwares can be designed by using programming languages.
Examples: C, C++, JAVA, VC++, .NET etc.
Types of softwares:
Software is divided in to two categories. 1) System Software 2) Application Software
System Softwares:
These are the softwares can be designed for physical hardware devices (embedded systems).
In real time, these softwares are mostly designed by using C/C++.
Examples: operating system, compilers, system drivers. Etc.
Application Softwares:
These are the softwares can be designed for end users and these are again categorized into two types
named as:
a) Standalone (or) Desktop applications
b) Distributed (or) Internet based applications.
In real time, these softwares are mostly designed by using JAVA.
Standalone (or) Desktop applications:
These applications runs in a single computer and whose results are not sharable in multiple other
computers.
In real time mostly these are designed by using ‘.NET’ language.
Examples: Media player, M.S. office, calculator applications, etc.
Distributed (or) Internet based applications:
This is an application runs in a single computer but whose results can be shared in multiple other
computers.
These distributed applications are again divided in to two: Web applications and Enterprise
applications.
Web Application: This is an internet based application designed commonly for every end user in the
world. Examples: Facebook, YouTube, google, etc.
Enterprise application: This is an internet based application designed for specific organizations,
which means only limited end users can access these applications. Examples: Banking applications,
income tax applications, company mailing applications, etc.

10
So finally java is a universal programming language can be used to design any of above softwares. But
it is very famous to design internet based applications.

Applications of oop:
Oop is used in various fields such as
1.Real time system.
2.Database management.
3.Neural Networks.
4.Artificial Intelligence.
5.Expert system.
6.Good level of code reuse.
7.easy to understand.
8.easy to maintain.

History of JAVA:

➢ Java is a general purpose, object-oriented programming language developed by “Sun Microsystems” of USA in
1991
➢ It took 18 months for to release the first version of java
➢ This language introduced by James Gosling .He is one of the inventor of the language
➢ Actually it was designed for the development of software for electronic consumer devices such as TVs, VCRs
and such other electronic devices
➢ It is a simple, portable and highly reliable.
History
1990 Sun Microsystems decided to develop a new software that could be used to
manipulate consumer electronic devices
1991 After exploring the possibility of using the most popular object oriented language
And initially called ‘OAK’
1994 The same team developed a web-browser called ‘Hot Java’ to locate and run applet
program on internet
1995 OAK was changed to ‘JAVA’ due to legal snags
It is a just name
Many popular companies including ‘NetScapes’ and Microsoft announced their
support to java
1996 Java established itself not only as a leader for internet programming but also a
general purpose , object oriented programming

Page 11
➢ This language is platform independent
➢ Programs developed in java can be executed anywhere on any system

JAVA is a programming language used to design the softwares; the main purpose of software is to
perform business-oriented operations in very less time.
Examples: Operating bank operations through online, searching a job through online, purchasing a
product through online etc.
Java was originally initiated in the year 1991 and it is designed by “Mr. James Gosling” and his team
members ‘Mr. Bill Joy’, ‘Mr. Mike Sheradin’, ‘Mr. Patrick’. N in the year 1995 at “SUN MICRO
SYSTEMS” named as JAVA 1.0.
The initial name was Oak but it was renamed to Java in 1995.
Right now SUN MICRO SYSTEMS was taken over by “ORACLE CORPORATION”.
JAVA 1.0:
In 23rd Jan 1996, Java Development Kit (JDK) 1.0 was released for free by the SUN
MICROSYSTEMS and named as OAK. It includes predefined 8 packages and 212 classes.
MICRSOFT and other companies licensed JAVA.
JAVA 1.1:
In 19th Feb 1997, JDK 1.1 was released with predefined 23 packages and 504 classes. It includes the
features of inner classes, event handling, improved JVM, AWT, JDBC, JAVA Bean Classes etc.
Microsoft developed its own 1.1 compatible JVM for internet explorer.
JAVA 1.2 (J2SE):
In 8th Dec 1998 JDK 1.2 was released with predefined 59 packages and 1520 classes.
It includes the features of Swings for improved graphics, JIT Compiler and Multithread methods like
suspend( ), resume( ) and stop( ) of Thread class.
JAVA API includes collection frameworks such as list, sets and hash map.

JAVA 1.3:
In 8th May 2000 JDK 1.3 was released with predefined 76 packages and 142 classes.
It includes the features of JAVA Sound (input and output of sound media), Java Naming and Directory
Interface (JNDI) and Java Platform Debugger Architecture (JPDA), etc.
JAVA 1.4:
In 6thFeb 2002 JDK 1.4 was released with predefined 135 packages and 2991 classes.
It includes the features of XML support, ‘assert’ keyword, Regular Expressions, Exception Handling,
Reading and writing image files etc.
JAVA SE 5 (Java 1.5):
In 30thSep 2004, JSE5 was released with predefined 165 packages and 3000 classes.
It includes the features of Generics, Annotations, Metadata, Auto boxing, Un-boxing, improved
collection framework, formatted I/O, for-each loop, Concurrency utilities etc.
JAVA SE6:
In 11thDec 2006, Java SE6 was released with features of scripting language support, JDBC 4.0 support,
JVM improvements including Synchronization and compiler performance optimizations, Garbage
collection algorithms, etc.
JAVA SE 7:
In 28thJul 2011, Java SE7 was released with features of JVM support for dynamic language, new library
for parallel computing on multi core, compressed 64 bit pointers, Automatic resource management,
Multi-catch Exception, underscore in numeric literals etc.

Page 12
JAVA SE 8:
In 18thMar 2014, Java SE8 was released with features are lambda expressions, Enhanced security,
JDBC-ODBC bridge has been released etc.

Parts of JAVA:
SUN Micro Systems has divided java into 3 parts named as Java SE, Java EE and Java ME.
Java SE:
It is known as “Java Standard Edition”. It is used to develop basic java classes, standalone
applications, simple network based applications, standard APPLETS.
Java EE:
It is known as “Java Enterprise Edition”. It is used to develop Internet based applications on
providing business solutions.
Java ME:
It is known as “Java Micro Edition”. It is used to develop portable applications such as PDA or
Mobile devices. Code on these devices needs to be small in size and should take less memory.

Key Points:
Up to 8 versions, java EE contains more than 35 modules and these are used to design very efficient
and secured internet based applications.
From Java 2.0 onwards java becomes the “technology” and from java 5.0 onwards it becomes
“Framework”.
The main difference between programming language, technology and framework is all are almost
same but difference can found in its library size.
Programming language supports max 10% of library, Technology supports min 40% of library and
Framework supports min 80% of library sizes.

JAVA Features (or)Java Buzzwords :


Java is very famous in the market even multiple other programming languages are available because of
following features.
1) Simple
2) Object Oriented
3) Platform Independent
4) Architectural Neutral
5) Robust
6) Multi-Threaded
7) High Performance
8) Dynamic
9) Distributed
10) Secured

1.Simple:
Java is easy to learn and its syntax is quite simple, clean and easy to understand.
The ambiguous concept of C++ has been re-implemented in java in a clear way.
Java is simple programming language because of following reasons:-
1) It supports very huge API (Application Program Interface) also known as java library. So that
application development becomes very easy and burden on the developer is reduced.
2) Java is free from pointers. It means java makes the developer free from writing of pointer code.
Page 13
Therefore, the burden on the developer and code complexity is reduced.
Note: Java supports pointers and it will be handled internally / implicitly by the JVM.
Every java program can be written in simple English language. So that it is easy to understand by
developers.

2.Object Oriented:
Java is object oriented language which means java programs uses objects and classes. An object which
contains data and behavior.
Java can be easily extended as it is based on ‘Object’ model.

3.Platform Independent:
Generally platform means “Operating System” (O.S).
Java is a platform independent language, which means java program can be executed in any
operating system even that program was developed and compiled in other O.S.
Java follows “Write Once and Run anywhere” slogan.
After compilation, java program is converted in to ‘byte code’. This bytecode is platform
independent and can be run on any machine with secured manner.
Any machine, which is having “Java Runtime Environment” (JRE), can run java programs.

4.Architectural Neutral:
Java is a processor independent language that means java program can be executed by any processor
even that program was developed and compiled in other processor.

5.Robust:
Java is very strong because of exception handling mechanism.
If any error is generated at that time of compilation of program is known as “Compile time error / Syntax
error”. These errors are raised because of violating the syntax rules given by programming languages.
Example: Semicolon missing, writing keyword in uppercase, etc.
If any error is generated at run time is known as “Run time error / Exception”. Generally these are
raised because of providing invalid inputs by the end user.

Page 14
Whenever exception is raised system defined / generated error message will be given to the end user, it
is unable to understandable. So that this message must be converted into user friendly message.
Exception Handling is a mechanism used to convert system defined error message into user friendly
error message.
In java it can be achieved by using “try-catch”.

6.Multi-Threaded
Java is a multi-threaded programming language. It means if the same program of same application
running simultaneously is known as “Multi-Threading”.
In the end user point of view, thread is a request.
In java point of view, thread is a “flow of execution”.
The main advantage with multi-threading is end users waiting time is reduced while performing
business oriented operations.

7.High Performance
Java is very high performance language because of following reasons:
1) By using Multi-threading, end users waiting time is reduced so that performance will be increased.
2) By using “Garbage Collector”, wastage of memory space is reduced so that performance is
increased.
Garbage Collector: It is a predefined method in Java, runs automatically in the background of every
java program and deallocates un-used memory spaces.

8.Dynamic
Java is dynamic because of supporting “Runtime memory allocations”.
If the memory is allocated for input data at the time of compilation of program is known as “compile
time memory / static memory”.
If the memory is allocated for input data at the time of running of the program is known as “Dynamic
Page 15
memory”.
Java strictly supports only “Dynamic Memory”.

9.Distributed
Java is distributed. It means it supports to design distributed applications / network based applications
and it supports distributed architecture.
Based on the distance between the computer networks are categorized into LAN, MAN, WAN and
Internet.
Java supports to design all network categories based on two architectures.
1) Client-Server architecture
2) Distributed architecture.
Client-server Architecture:
In this architecture, multiple client machines depend on single server machine.
Client always sends the request to the server whereas server always gives the response to the client.

If any problem is occurred at server machine that will reflected on every client machine. This problem
is leads to “server down”.

Distributed Architecture:
In this architecture, multiple client machines depend on multiple server machines.
The main advantage is even if the problem is occurred at one server machine that won’t be reflected on
any client machine.
All client requests are shared to multiple server machines based on its distance.
Java supports to develop internet based applications. This architecture is mostly used in real time.

Page 16
10.Secured:
Java is more secured programming language among all other languages because of following reasons.
It is virus free programming language, which means if any application is designed by using java
language that does not allows virus in to the computer.
Java provides security to the applications in two ways. 1) Internal security 2) External security.
Internal Security: A security is provided by the data within the application is known as Internal
security. It can be achieved by OOPS.
External Security: Whenever security is provided to data by the outside applications is known as
external security. It can be achieved by Encryption and Decryption.
Encryption: Converting plain text into cypher text is known as encryption.
Decryption: Converting cypher text in to plain text is known as decryption.
Java supports all encryption and decryption techniques so that it provides high level external security
for the data.

Java Virtual Machine (JVM) Architecture:

JVM is a software available as a part of JDK software and it is a heart of entire Java program
execution process.
JVM is a platform dependent software mainly used to perform following operations:
1) Allocates sufficient memory space for the properties of class in main memory (RAM).
2) It takes the ‘.class’ file as an input and converting each byte code instruction in to the machine
language instruction that can be executed by the processor.

Page 17
First ‘javac’ converts the source code instructions in to ‘byte code’ and after successful compilation a
new ‘.class’ file will be created.
Now the ‘.class’ file is given to the JVM as an input and it converts in to machine level instructions.
The architecture of JVM is as follows:

Class Loader Sub System:

In JVM, there is a module called “class loader sub system”, which performs the following functions:
1) First, it loads the “.class” file into main memory for all the properties of the class.
2) Then it verifies whether all byte code instructions are proper or not. If it finds any instruction
suspicious, the execution is rejected immediately.
3) If the byte code instructions are proper, then it allocates necessary memory to execute the program.

Method area:
Method area is the method block, in which memory is allocated for the code of the variables and
methods in the java program.

Heap:
This is the area where objects are created. In this area, memory is allocated for the ‘Instance Variables’
in the form of objects.

PC (Program Counter) registers:


These are the registers, which contains memory address of the instructions of the methods.

Page 18
Java Stacks:
Java stacks are memory area where Java methods are executed.
It also allocates the memory for ‘local variables’ and ‘object references’.
JVM uses a separate thread to execute each method.

Native Method area:


In which memory is allocated for the native methods.
These methods contain other than java language code like c, C++, .Net. Etc.
To execute native method, generally native method libraries are required. These header files are
located and connected by the JVM by using ‘Native method interface’.

Execution Engine:
It contains two components named as Just in Time (JIT) Compiler and Interpreter.
These components are responsible for converting the byte instructions into machine code so that the
processor will execute them.
Most of the cases JVM use both JIT compiler and interpreter simultaneously to convert the byte code.
This technique is called “Adaptive Optimizer”.
Interpreter is responsible to convert one by one ‘byte code’ instructions into ‘machine level
instructions’ and it always comes into the picture while sending the first request to java program.
JIT Compiler always appears from the second request onwards; it will collect all the ‘machine level’
instructions that are already converted by the interpreter and gives to processor.
The main advantage with JIT compiler is it will increase the execution speed of the program.

Difference between C++ and JAVA

C++ JAVA
1) C++ is platform dependent. 1) JAVA is platform independent.
2) It is mainly used to develop system 2) It is mainly used to develop application
softwares. softwares.
3) It is not a purely object oriented
3) It is a purely object oriented programming
programming language, since it is possible to
language, since it is not possible to write a
write C++ programs without using class or
java program without using class or object.
object.
4) Pointers are available in C++. 4) Java is free of pointers creation.
5) Allocation and deallocating memory is the 5) Allocation and deallocating memory will
responsibility of the programmer. be taken care of JVM.
6) C++ has goto statement. 6) C++ doesn’t have goto statement.
7) In some cases, implicit casting is available.
7) Automatic casting is available in C++. But it is advisable to the programmer should
use casting wherever required.
8) Multiple Inheritance feature is available in 8) Java doesn’t support Multiple Inheritance
C++. in class level. It can be achieved by interfaces.
9) Operator overloading is available in C++. 9) It is not available in java.
10) #define, typedef and header files are
10) These are not available in java.
available in C++.
11) C++ uses compiler only. 11) Java uses compiler and interpreter both.
12) C++ supports constructors and destructors. 12) Java supports constructors only.

Page 19
Structure of Java Program

Documentation
section
Package section
Import statement
Interface statement
Class definition
Main method class
{
Definition
}
Documentation Section
It comprises a set of comment lines giving the name of the program. The author and other details. Comments
must explain why and what of classes and how of algorithms.
In addition to the two styles of comment discussed earlier. Java support third style of comment that is the
documentation comment that indicate the /* ---- */.
Package Statement
It is directory of classes and interfaces. The first statement allowed in a java file package statement this
statement declare the package name and inform the compiler that the classes defined here belong to the
package.
Import statement

The next thing after package statement maybe a no of import statement . this is similar to #include
statement in ‘C’ and ‘C++’.
Ex: import student. Test;
This statement means the interpreter to load the test class contained in the package student.
Interface statement
An interface like a class but include group of method declaration. It is used to implement the multiple
inheritance features in the program. This is new concept in java.

Class definition
A java program may contain multiple class definition. Classes are the primary and essential elements of real-
world problem.
Main method class
Every java program require a main method as its starting point. This class is essential part of a java program.
A simple java program may contain only this part. The main method creates objects of various
classes and establishes communicatation between them.
Page 20
Example of java program structure

import packagename;
class ClassName1
{
List of variables;
List of methods;
}
class ClassName2
{
List of variables;
List of methods;
}
class MainClass
{
Public static void main(String args[])
{
-------
-------
}

Naming conventions in Java:

“SUN MICRO SYSTEMS” given the following name conventions that must be followed while
writing java programs.

1) Package name must be in ‘LOWER CASE’ letters.


Syntax: a) package packagename; // Used to create a new package
b) import packagename; //Used to import the existing packages.
2) First letter of every word of class name must be in ‘UPPER CASE’ letters.
Example: class StudentDetails
{
----
----
}
3) Constant:
It must be in ‘UPPER CASE’ letters, if it is containing more than one word that must be separated
with UNDERSCORE.
Example: final String COLLEGE_NAME = “VIGNAN”;
-If any variable is preceded with ‘final’ keyword then it becomes ‘constant’. It means whose value
can’t be changed at runtime.
4) Naming of variables is same as that for the method. Except first letter of first word, from the next
word onwards the first letter must be in UPPERCASE for variables, methods and object references.
Example: class StudentDetails
Page 21
{
int rno;
String studentName;
void insertStudentDetails( )
{
----
----
}
}
5) All keywords should be written in LOWERCASE letters. Example: public, void, static. etc.

In the above naming conventions are mandatory while accessing predefined properties of Java API
but it is optional while creating user defined properties.

Compilation of Java program:


Every java program is executed by JVM, but JVM can understand only “Byte Code” instructions.
‘Java compiler’ (javac) is responsible to convert the ‘source code’ instructions into ‘byte code’
instructions and also it will identify the ‘syntactical errors’ in the java program.
‘Byte code’ instructions represented in the form of “.CLASS” file whereas source code instructions
are represented in the form of ‘.java’ file.
Syntax to compile a program:
javac filename.java;
In the above syntax must be written in ‘command prompt’ that will tell O.S. to call the ‘Java compiler’
to compile the program.
Syntax to run a program:
After compilation of java program ‘JVM’ will execute the program and gives the result.
java filename;
In the above syntax must be written in ‘command prompt’ that will tell O.S. to call the ‘JVM’ to
execute the java program.

Example Programs
Program 1: Write a program to display the message

import java.lang.*;
class Sample1
{
public static void main(String args[])
{
System.out.println(“Welcome to Java Programming”);
}
}
OUTPUT:
javac Sample1.java
java Sample1
Welcome to Java Programming

- In the above program 1, it is just to display a string on the monitor.


- ‘System’ is the class name and ‘out’ is a static object in the System class.
Page 22
Program 2: Write a program to find sum of two numbers
import java.lang.*;
class Sum
{
public static void main(String args[ ])
{
int x,y; //variables declaration
x=10, y=20; //store values in to variables
int z = x+y;
System.out.println(z);
}
}
OUTPUT:
javac Sum.java
java Sum
30
- In the above program x+y performs the sum operation and the result is stored into z.
- ‘System’ is a class in ‘java.lang’ package and ‘System.out’ creates the PrintStream object which
represents the standard output device.
- System.out.println(z) is used to displays the value on the monitor.

Program 3: Sum of two numbers with formatting the output


class Sum1
{
public static void main(String args[])
{
int x=10, y=20;
int z=x+y;
System.out.println(“sum of two numbers=” +z);
System.out.println(“sum of two numbers=” +x+y);
System.out.println(“sum of two numbers=” +(x+y));

}
}
OUTPUT:
javac Sum1.java
java Sum1
sum of two numbers=30
sum of two numbers=1020
sum of two numbers=30

- In the first display statement, “+” is used to join the string “sum of two numbers=” and the numeric
variable ‘z’. It is acting like a concatenation operation.
- In the second display statement, we are having sum of two numbers=” +x+y. Since left one is a string
and the next value of x is also converted in to a string; thus the value of x, i.e. 10 will be treated as
separate characters as 1 and 0 and are joined to string and also for the next variable y is 25. Thus we get
result as 1025.

Page 23
- In the third display statement, we are having sum of two numbers=” +(x+y). The execution will start
from the inner braces. At left we got ‘x’ and right we got ‘y’, both are numbers and addition will be done
by the + operator, thus giving a result 35.
Program 4: Examples on System.out.println( ) statements:

Statement Output
1) System.out.println(“Hello”); Hello
2) System.out.println(“ “Hello” ”); Invalid
3) System.out.println(“ ‘Hello’ ”); ‘Hello’
4) System.out.println(“ \”Hello\” ”); “Hello”
5) System.out.println(“ \’Hello\’ ”); ‘Hello’
6) System.out.println(“ Hello \t friends ”); Hello friends
7) int x=10, y=40;
System.out.println(“ x ”); x
System.out.println(x); 10
System.out.println(“ x+y”); x+y
System.out.println(x+y); 50
System.out.println(“10” + “20”); 1020
System.out.println(“x=” +x); x=10
System.out.println(“y=” +y); y=40
System.out.println( x + “ ” +y); 10 20
System.out.println( x +y + “ ”); 30
System.out.println( “ ” +x +y); 1020
8) int rno=1; roll number is: 1
String name = “java”; name of the lab: java
System.out.println(“roll number is:” +rno);
System.out.println(“name of the lab:” +name);
9) System.out.println(“hello”); hello
System.out.println(“friends”); friends
System.out.println(“How are you”); How are you
10) System.out.print(“hello”); hellofriendsHowareyou
System.out.print(“friends”);
System.out.print(“How are you”);

Double quotations with in double quotations and single quotations with in single are not allowed in
java. But single with in double and double within single are allowed in Java.
Java supports escape sequences or backslash code to perform special operations:

Backslash code Meaning


\n Next Line
\t Horizontal tab space
\r Enter key
\b Backspace
\f Form feed
\\ Displays \
\” Displays ”
\’ Displays ’

Page 24
Variables in Java:
Variable is a container which holds the value while the java program is executed.
A variable is assigned with the data type.
A variable is used to identify the data either by the program or developer. So variable is a name of
memory location.
There are three types of variables in Java. They are:
1) Local variable
2) Static variable
3) Instance / Non-static variable
Local Variable:

If a variable defined or declared inside the method is known as “local variable” and also inside the
“formal parameters”.
Example on Local Variable
void method1( )
{
int x = 10; //local variable
}
Local variable must be initialized, why because JVM does not assign any default value for the local
variables.
Example on Formal Parameter
void method1( int x) // formal parameter
{
x = 10;
}
For local variables memory is allocated at that time of calling the method and memory is deallocated
once the control comes outside the method.
Local variables can be accessed only with in the same method.
In real time, it is recommended to define the local variable whenever that variable wants to be used
with in the single method at a time.
Instance / Non-static Variable:
If any variable defined outside the method and inside the class without ‘static’ keyword is known as
“Non-static variable” or “Instance Variable”.
For instance variables memory is allocated whenever a new object is created and memory is
deallocated once object is destroyed.
Instance variable can be accessed in any method of the same class.
Example:
class A
{
int x; //instance variable
void f1( )
{
x=20;
}
void f2( )
{
x=30;
}
}
Page 25
In real time, it is highly recommended to define the non-static variable whenever we want to maintain a
separate memory copy for that variable for every new object.

Static Variable:
If any variable is defined outside the method and inside the class with ‘static’ keyword is known as ‘static
variable’.
For static variable memory is allocated only once at that time of loading of class and memory is
deallocated once class is un-loaded from the main memory. Probably it is possible when we shut down
the server.
Static variable can be accessed in any method of the same class.
Example:
class A
{
static int x; //static variable
void f1( )
{
x=20;
}
Void f2( )
{
x=30;
}
}
In real time, it is highly recommended to define the static variable whenever we want to maintain a
single memory copy for any object of same class.
Note: Separate memory copy is required to handle the dynamic input values and common memory
required to handle common data.

Comparison on life time and scope of variable:

Variable Name Life Scope


1) Local variable Within the same method Within the same method
2) Instance variable Until object is available Anywhere within the same class
Until class is unloaded from
3) Static variable Anywhere within the same class
the main memory

Whenever variable is declared by default JVM keeps following default values.


Syntax: datatype var_name;
Datatype Default Value
1) byte, short, int, long 0
2) float, double 0.0
3) char Blank space
4) Boolean False
5) String NULL

Example Program
class Student
{
int rno;
String name;
float marks;
static clgName= “Vignan”;

Page 26
void insert( )
{
------
------
}
}

Data Types in Java:


Types of inputs:
End user will provide one or more inputs but these are categorized into following 4 types.

If any character (alphabet/numeric/special symbol) is enclosed in ‘single quotation’ is known as


“Single character” constant.
If the set of characters are enclosed in “double quotations” is known as “String type constant”.

Data Types:

Def: It is a keyword in java which is used to represent the type of the data and it will tell to the JVM
how much memory should be allocated for the data.
Data types are categorized in to two types:
1) Primitive data types
2) Reference data types
Note: Every data type is keyword but not every keyword is a datatype.

Page 27
Primitive Data Types:
These are the data types whose variable can handle maximum one value at a time, these are
categorized into following 4 types:
1) Integer datatype
2) Floating point datatype
3) Character datatype
4) Boolean datatype

Integer Data Type: It is used to handle integer type of values without any fraction or decimal parts
and these are categorized into following types:

Data Type Size (in Bytes) Range of the data type


1) byte 1 (8 bits) -27to +27- 1
2) short 2 (16 bits) -215 to +215 - 1
3) int 4 (32 bits) -231 to +231 – 1
4) long 8 (64 bits) -263 to +263 – 1

Example: byte rno=10; in this statement we declared a variable of type ‘byte’ for the variable ‘rno’
with the value 10.
Floating point Data Type: It is used to handle real type of values with fraction or decimal parts
and these are categorized into following types:

Data Type Size (in Bytes) Range of the data type


1) float 4 (32 bits) -231 to +231 – 1
2) double 8 (64 bits) -263 to +263 – 1

Example 1: float pi = 3.142f; in this statement the variable ‘pi’ which contains the value ‘3.142’. If ‘f’
is not written in the end, the JVM would have allocates 8 bytes of memory. The reason which is Java
takes default as ‘double’.
Example 2: Consider double distance = 1.96e8; this deceleration represents the scientific notation. It
means 1.96e8 means 1.96X108.
Character Data Type:
1) This is used to handle single character values at a time.
2) In java language, it can be represented with ‘char’ keyword.
3) In C-language, char data type occupies 1 byte of memory because of ASCII system. It means it
supports only international langua1ge characters English (256 characters).
4) In java language, char data type occupies 2 bytes of memory because of UNICODE system. It
means character data type in java allows 18 international languages. To store these characters 2
bytes of memory is required.
5) Range of char in java language: -215 to +215 – 1.
Boolean Data Type:
1) This is used to handle ‘boolean’ values like TRUE or FALSE.
2) It can be represented by using ‘boolean’ keyword.
3) True value always can be stored in the form of ‘1’and false can be stored in the form of ‘0’.
4) So 1-bit of memory is sufficient for boolean type.
5) Example: boolean response = true;

Page 28
Referenced Data Types:
It is a data type whose variable can handle more than one value in the form of object.

String data Type:


It is used to handle the string type of data in java language and it will be treated as special data type
because of following reasons:
1) There is no fixed size for string data type. Example: “ABC”, “Vignan”… Etc.
2) Based on requirement it may acts a primitive data type or reference data type.
3) String not a keyword in java, it acts as a ‘predefined class’.
4) String is a collection of characters that must be enclosed in “double quotation”.

Note: The main purpose of maintaining sub data types is for handling efficient memory management.
That means based on the size of input values data type should be changed.

Arrays:
collection of homogeneous elements of same type.
Example:int rollno[94]={1,2………94};

Identifiers:

Identifiers are name of the variable, method, classes, packages and interfaces.
For example: main, String, args and println( ) are identifiers in java program.
Identifiers are composed of letters, numbers, underscore, and the dollar ($) sign.
An identifier name must begin with the letter, underscore and dollar sign.
Example: age =20;
_age=20;
25age = 20; // Illegal
After the first character, an identifier can have any combination of characters.
Identifier always should exist in the left hand side of assignment operator.
Example: age = 30;
45 = age; // Illegal
No keyword should be assigned as an identifier.
Example: break = 15; // Illegal
In java, the maximum length of the identifier in java should be 32 characters.
No Spaces are allowed in the identifier declaration;
Example: my age = 20; // Illegal
Except underscore ( _ ) no special symbols are allowed in the middle of the identifier name.
Example: my_age = 20;
my@age = 20; //Illegal
my$age = 20; //Illegal

Program 5: A java program to create referenced and un-referenced objects

class Student
{
int rno;
String name;
float marks;
Page 29
void setData( )
{
rno=1;
name=”james”;
marks=95.6f;
}
void display( )
{
System.out.println(rno);
System.out.println(name);
System.out.println(marks);
}
}
class StudentDemo
{
public static void main(String args[])
{
Student s1 = new Student( );
s1.display( )
s1.setData( );
s1.display( );
System.out.println(“ ............................ ”);
System.out.println(“Hello Java”);
s1.display( );
System.out.println(“ ............................ ”);
new Student( ).display( );
System.out.println(“ ............................ ”);
new Student( ).setData( );
new Student( ).display( );
System.out.println(“ ............................ ”);
s1.display( );
s1=null;
s1.display( );
}
}

OUTPUT: Run this program in your PC for better understanding.

Literals in Java:
A literal represents a value that is stored into a variable in a program.
Example: boolean result = false;
char gender = ‘M’;
int i = 156;
In the above examples, the right hand side (RHS) values are called “Literals” because these values are
being stored into the variables shown in the left hand side (LHS).
As the data type changes then the type of the literal also changes.
Literals are categorized into various types are as follows:
Page 30
1) Integer Literals
2) Float Literals
3) Character Literals
4) String Literals
5) Boolean Literals
1.Integer Literals:
Integer literals represent the fixed integer values like 100, -53, 1235, etc.
All these numbers belonging to the decimal number system, which use (0 - 9) to represent any number.
Examples:
int dec = 26;
2.Float Literals:
Float literals represents fractional numbers. These are the numbers with decimal points like 2.1, -3.4,
etc, which should be used with float and double type variables.
Examples:
float f1 = 12.3f;
double x = 123.4;
3.Character Literals:
Character literals includes general characters like A, b, etc., special characters like @, ?, etc, escape
sequences like \n, \t etc.
These are enclosed in single quotations. But the escaping sequences can also be treated as string
literals.
4.String Literals:
String literals represent objects of “String” class. For example: “Hello”, “Never say die” etc. will
come under string literals, which can be stored directly in the string object.
These are enclosed in double quotations.
Example:
String a = “Hello java world”;
5.Boolean Literals:
It represents only two values namely: TRUE and FALSE. It means we can store either true or false
into boolean type variable.

Operators in Java:

An operator is a symbol that performs basic logical operations like arithmetic, relational, increment
operations etc.
For example: a + b; Here a, b are operands and ‘+’ is an addition operator.
If an operator acts on a single variable is called as unary operator. If it acts on two variables is called
as binary operator. If it acts on three variables is called as Ternary operator.
There are many operators that are supported by Java as follows:
1) Unary operator
2) Arithmetic operator
3) Shift operator
4) Relational operator
5) Bitwise operator
6) Logical operator
7) Ternary operator
8) Assignment operator

Page 31
Unary operator:
The java unary operator acts on only one operand.
These are used to perform increment / decrement a value, negating an expression and inverting the
value of a boolean.

Example 1 on unary + + and - -


class Sample
{
public static void main(String args[])
{
int x=10;
System.out.println(-x);
System.out.println(x++);
System.out.println(++x);
System.out.println(x--);
System.out.println(--x);
}
}
OUTPUT:
-10
10
12
12
10

Example 2 on unary + + and - -


class Sample2
{
public static void main(String args[])
{
int a=10;
int b=10;
System.out.println(a++ + ++a);
System.out.println(b++ + b++);
}
}
OUTPUT:
22
21

Example 3 on !
class Sample3
{
public static void main(String args[])
{
boolean c=true;
boolean d=false;
System.out.println(!c);
Page 32
System.out.println(!d);
}
}
OUTPUT:
false
true

Arithmetic operator:
These are the operators used to perform fundamental arithmetic operations like addition, subtraction,
multiplication, etc.
It acts on the two operands at a time, called as binary operators.
While working with arithmetic operators the result type is depends on the following priorities of
datatypes.
Datatype Priority (High to Low)
1) double 1
2) float 2
3) long 3
4) int 4
5) short 5
6) byte 6
Examples:
- int + float -> float
- float / double -> double
- byte - short -> short
- long * double -> double
- float % int -> int // remainder should be in integer
- int % int -> int
- float % float -> int
- long % int -> long // long has highest priority
Example 1: Program on Arithmetic operators
class AirthmeticOperators
{public static void main(String args[])
{
int a=10;
int b=5;
System.out.println(a+b);
System.out.println(a-b);
System.out.println(a*b);
System.out.println(a/b);
System.out.println(a%b);
}
}
OUTPUT:
15
5
50
2
0

Page 33
Example 2: Program on Arithmetic operators
class SampleArithmetic
{
public static void main(String args[])
{
System.out.println(10*10/5+3-1*4/2);
}
}
OUTPUT:
21

Left Shift operator:


The Java left shift operator << is used to shift all of the bits in a value to the left side of a specified
number of times.
Example Program on Left Shift Operator:
class OperatorExample
{
public static void main(String args[])
{
System.out.println(10<<2);//10*2^2=10*4=40
System.out.println(10<<3);//10*2^3=10*8=80
System.out.println(20<<2);//20*2^2=20*4=80
System.out.println(15<<4);//15*2^4=15*16=240
}
}
OUTPUT:
40
80
80
240
Right Shift operator:
The Java right shift operator >> is used to move left operands value to right by the number of bits
specified by the right operand.
Example Program on Right Shift Operator:
class OperatorExample
{
public static void main(String args[])
{
System.out.println(10>>2);//10/2^2=10/4=2
System.out.println(20>>2);//20/2^2=20/4=5
System.out.println(20>>3);//20/2^3=20/8=2
}
}
OUTPUT:
2
5
2

Page 34
Relational operator:
These are used to check the conditions, it always returns either TRUE or FALSE.
The relational operators are of 6 types:
Operator Meaning
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
== Equal to
!= Not equal to

Example Program on Relational Operator:


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

Logical AND, Bitwise & operator:

The logical && operator doesn't check second condition if first condition is false. It checks second
condition only if first one is true.
The bitwise & operator always checks both conditions whether first condition is true or false.
Java AND Operator Example 1: Logical && and Bitwise &
class OperatorExample
{
public static void main(String args[ ])
{
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a<c);//false && true = false
Page 35
System.out.println(a<b&a<c);//false & true = false
}
}
OUTPUT:
false
false
Java AND Operator Example 2: Logical && vs Bitwise &
class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a++<c);//false && true = false
System.out.println(a);//10 because second condition is not checked
System.out.println(a<b&a++<c);//false && true = false
System.out.println(a);//11 because second condition is checked
}
}
OUTPUT:
false
10
false
11

Logical || and Bitwise | operator:


The logical || operator doesn't check second condition if first condition is true. It checks second
condition only if first one is false.
The bitwise | operator always checks both conditions whether first condition is true or false.
Java OR Operator Example: Logical || and Bitwise |
class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=5;
int c=20;
System.out.println(a>b||a<c);//true || true = true
System.out.println(a>b|a<c);//true | true = true
System.out.println(a>b||a++<c);//true || true = true
System.out.println(a);//10 because second condition is not checked
System.out.println(a>b|a++<c);//true | true = true
System.out.println(a);//11 because second condition is checked
}
}

Page 36
OUTPUT:
true
true
true
10
true
11
Ternary Operator:
This operator is can be used on 3 variables, it is also known as ‘conditional operator’;
Syntax: Expr1? Expr2 : Expr3;
In the above syntax, expr1 should be a condition, if it is TRUE then expr2 will be executed otherwise
expr3 will be executed.
Java Ternary Operator Example:
class OperatorExample
{
public static void main(String args[])
{
int a=2;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}
}
OUTPUT:
2
Assignment Operator:
Java assignment operator is one of the most common operator.
It is used to assign the value on its right to the operand on its left.
Java Assignment Operator Example 1:
class OperatorExample
{
public static void main(String args[])
{
int a=10;
int b=20;
a+=4;//a=a+4 (a=10+4)
b-=4;//b=b-4 (b=20-4)
System.out.println(a);
System.out.println(b);
}
}
OUTPUT:
14
16

Page 37
Java Assignment Operator Example 2:
class OperatorExample
{
public static void main(String[] args)
{
int a=10;
a+=3;//10+3
System.out.println(a);
a-=4;//13-4
System.out.println(a);
a*=2;//9*2
System.out.println(a);
a/=2;//18/2
System.out.println(a);
}
}
OUTPUT:
13
9
18
9

Primitive Type Conversion and Casting


Assigning a value of one type to a variable of another type is known as ‘Type Casting’.
In real time, the main purpose of using type casing is to change the client data in to database
understandable format and database data into client understandable format.
Type casting is categorized in to two: Widening and Narrowing conversion.
Widening Implicit Conversion:
- If the data types are compatible, then Java will perform the conversion automatically known as
automatic Type Conversion (or) Widening.
- Widening conversion takes place when two data types are automatically converted. This happens
when:
1) The two data types are compatible.
2) 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.

Page 38
Example Program on Widening Conversion
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

Narrowing or Explicit Conversion:

- If we want to assign a value of larger data type to a smaller data type we perform explicit type
casting or narrowing.
- This is useful for incompatible data types where automatic conversion cannot be done.
- Here, target-type specifies the desired type to convert the specified value to.

Example Program on Narrowing Conversion


class Test
{
public static void main(String[] args)
{
double d = 100.04;
//explicit type casting
long l = (long)d;
//explicit type casting
int i = (int)l;
System.out.println("Double value "+d);
//fractional part lost
System.out.println("Long value "+l);
//fractional part lost
System.out.println("Int value "+i);
}
}

Page 39
OUTPUT:
Double value 100.04
Long value 100
Int value 100

3. Control Structures in Java


Control Structures are used to control the execution flow of logic, in other words it can be used to
achieve random execution.
These are categorized into following:

Conditional statements:
These are used to execute one or more logical instructions based on the condition, these statements are
executed only once.

If Statement:-
The Java if statement is used to test the condition. It checks boolean condition: true or false. There are
various types of if statement in java.
if statement
if-else statement
else-if ladder
nested if statement
Simple If statement:
It can be used by performing any operation by checking each and every condition. It executes the logic
if the condition is true.
Syntax:
if(condition)
{
//code to be executed
}

Page 40
Example Program:
class IfExample
{
public static void main(String[] args)
{
int age=20;
if(age>18)
{
System.out.print("Age is greater than 18");
}
}
}
OUTPUT:
Age is greater than 18

If else statement:
The Java if-else statement also tests the condition. It executes the code if condition is true otherwise
else block is executed.
In real time it can be used whenever we want to execute one logic among two logics.
Syntax:
if(condition)
{
//code if condition is true
}
else
{
//code if condition is false
}
Example Program:
class IfElseExample
{
public static void main(String[] args)
{
int number=13;
if(number%2==0)
{
System.out.println("even number");
}
else
{
System.out.println("odd number");
}

}
}

OUTPUT:
odd number

Page 40
else-if statement:
In real time it can be used to execute only one logic among multiple logics.

Syntax:
if(condition1)
{
//code to be executed if condition1 is true
}
else if(condition2)
{
//code to be executed if condition2 is true
}
else if(condition3)
{
//code to be executed if condition3 is true
}
...
else
{
//code to be executed if all the conditions are false
}

Example Program:
class IfElseIfExample
{
public static void main(String[] args)
{
int marks=65;
if(marks<50){
System.out.println("fail");
}
else if(marks>=50 && marks<60)
{
System.out.println("D grade");
}
else if(marks>=60 && marks<70)
{
System.out.println("C grade");
}
else if(marks>=70 && marks<80)
{
System.out.println("B grade");
}
else if(marks>=80 && marks<90)
{
System.out.println("A grade");
}
else if(marks>=90 && marks<100)

Page 41
{
System.out.println("A+ grade");
}
else
{
System.out.println("Invalid!");
}
}
}

OUTPUT:
c grade

Nested-if statement:
In real time, if one ‘if-statement’ is existing inside another ‘if-statement’ is known as Nested-if
statement.
It can be used to improve the efficiency of simple if statement, if-else statement and else-if statement.

Syntax:
if(condtion1)
{
// executes when the condtion1 is true
ifcondtion2)
{
// executes when the condtion2 is true
}
}
Example Program:
public class Test
{
public static void main(String args[])
{
int x = 30;
int y = 10;
if( x == 30 ) {
if( y == 10 ) {
System.out.print("X = 30 and Y = 10");
}
}
}
}
OUTPUT:
X = 30 and Y = 10

Page 42
Switch Statement:
It is same as ‘else-if statement’ used to executes only one logic among multiple logics.
The only difference between switch and ‘else-if’ is in performance. Switch is better than else-if
statement.
In ‘else-if’ statement every condition should be verified even to execute last block of statements, it
leads to increase the time consuming process and this problem can overcome using ‘switch’ statement.

Syntax:
switch(expression)
{
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......

default:
//code to be executed if all cases are not matched;
}
‘Java compiler’ will memorize all the case label name values and it will help to JVM to identify the
case blocks at runtime.
If no label name is matching with input choice then default block will be executed, default bloack can
exist anywhere in the switch statement.

Example Program 1:
public class SwitchExample
{
public static void main(String[] args)
{
int number=20;
switch(number){
case 10: System.out.println("10");break;
case 20: System.out.println("20");break;
case 30: System.out.println("30");break;
default:System.out.println("Not in 10, 20 or 30");
}
}
}
OUTPUT:
20

Example Program 2:
public class SwitchExample2
{
public static void main(String[] args)
{
int number=20;
Page 43
switch(number){
case 10: System.out.println("10");
case 20: System.out.println("20");
case 30: System.out.println("30");
default:System.out.println("Not in 10, 20 or 30");
}
}
}
OUTPUT:
20
30
Not in 10, 20 or 30
Note: All conditional statements are executed only once.

Looping statements
In programming languages, loops are used to execute a set of instructions/functions repeatedly when
some conditions become true. There are three types of loops in java.

for loop
while loop
do-while loop

for loop:
These are used to execute repeatedly based on given range, it can be achieved using for loop.
The Java for loop is used to iterate a part of the program several times. If the number of iteration is
fixed then it is recommended to use for loop.
There are three types of for loops in java.
Simple For Loop
Nested For Loop
For-each or Enhanced For Loop
Labeled For Loop
Simple for Loop:
The simple for loop is same as C/C++. We can initialize variable, check condition and
increment/decrement value.
Syntax:
for(initialization; condition; incr/decr)
{
//code to be executed
}
Example Program on for loop:
public class ForExample
{
public static void main(String[] args)
{
for(int i=1;i<=10;i++){
System.out.println(i);
}
}}

Page 44
OUTPUT:
1
2
3
4
5
6
7
8
9
10

Nested loop:
If the ‘for loop’ is existed within another ‘for’ loop are called as Nested for-loops.

Syntax:
for(initialization;condition;incr/decr)
{
for(initialization;condition;incr/decr)
{
//code to be inner for loop
}
//code to be outer for loop
}

Example Program on nested for loop:


class NestedForLoop
{
public static void main(String[] args)
{
for (int i = 1; i <= 5; ++i)
{
System.out.println("Outer loop iteration " + i);
for (int j = 1; j <=2; ++j)
{
System.out.println("i = " + i + "; j = " + j);
}
}
}
}
OUTPUT:
Outer loop iteration 1
i = 1; j = 1
i = 1; j = 2
Outer loop iteration 2
i = 2; j = 1
i = 2; j = 2
Outer loop iteration 3

Page 45
i = 3; j = 1
i = 3; j = 2
Outer loop iteration 4
i = 4; j = 1
i = 4; j = 2
Outer loop iteration 5
i = 5; j = 1
i = 5; j = 2

for-each loop:
The for-each loop is used to traverse array or group of elements in java.
It is easier to use than simple for loop because we don't need to increment value and use subscript
notation.
It works on elements basis not index. It returns element one by one in the defined variable.

Syntax:
for(Datatype var:array)
{
//code to be executed
}

Example Program on ‘for-each’ loop:


public class ForEachExample
{
public static void main(String[] args) {
int arr[]={12,23,44,56,78};
for(int i:arr){
System.out.println(i);
}
}
}
OUTPUT:
12
23
44
56
78

Java Labeled For Loop:


We can have name of each for loop. To do, we use label before the for-loop.
It is useful if we have nested for loop so that we can break/continue specific for loop.
Normally, break and continue keywords breaks/continues the inner most for loop only.
Syntax:
labelname:
for(initialization;condition;incr/decr)
{
//code to be executed
}
Page 46
Example Program 1 on labeled for loop:
public class LabeledForExample
{
public static void main(String[] args)
{
aa:
for(int i=1;i<=3;i++){
bb:
for(int j=1;j<=3;j++){
if(i==2&&j==2){
break aa;
}
System.out.println(i+" "+j);
}
}
}
}
OUTPUT:
11
12
13
21

Example Program 2 on labeled for loop:


public class LabeledForExample2
{
public static void main(String[] args) {
aa:
for(int i=1;i<=3;i++){
bb:
for(int j=1;j<=3;j++){
if(i==2&&j==2){
break bb;
}
System.out.println(i+" "+j);
}
}
}
}
OUTPUT:
11
12
13
21
31
32
33
Page 47
Example Program 3 on infinite for loop:
If you use two semicolons “;;” in the for loop, it will be infinitive for loop.
Syntax:
for(;;)
{
//code to be executed
}
Program:
public class ForExample
{
public static void main(String[] args)
{
for(;;)
{
System.out.println("infinitive loop");
}
}
}
OUTPUT:
infinitive loop
infinitive loop
infinitive loop
infinitive loop
infinitive loop
ctrl+c (To exit out of the program)

While loop:
These are used to execute one or more logical instructions based on the condition if the range is not
known, these can be achieved by while and do-while loop.
While loop is an entry controlled loop that means condition is verified before performing operation
only.
Syntax:
while(condition)
{
//code to be executed
}
Example Program 1 on while loop:
public class WhileExample
{
public static void main(String[] args)
{
int i=1;
while(i<=5){
System.out.println(i);
i++;
}
}
}

Page 48
OUTPUT:
1
2
3
4
5
Example Program 2 on infinite while loop:
If you pass true in the while loop, it will be infinitive while loop.
Syntax:
while(true)
{
//code to be executed
}
Program:
public class WhileExample2
{
public static void main(String[] args)
{
while(true){
System.out.println("infinitive while loop");
}
}
}
OUTPUT:
infinitive while loop
infinitive while loop
infinitive while loop
infinitive while loop
infinitive while loop
ctrl+c (To exit out of the program)

do-while loop:
The Java do-while loop is used to iterate a part of the program several times.
If the number of iteration is not fixed and you must have to execute the loop at least once, it is
recommended to use do-while loop.
The Java do-while loop is executed at least once because condition is checked after loop body.
Syntax:
do
{
//code to be executed
}while(condition);

Example Program 1 on do-while loop:


public class DoWhileExample
{
public static void main(String[ ] args)
{
int i=1;

Page 49
do{
System.out.println(i);
i++;
}while(i<=5);
}
}
OUTPUT:
1
2
3
4
5

Example Program 2 on infinite do-while loop:


If you pass true in the do-while loop, it will be infinitive do-while loop.
Syntax:
do{
//code to be executed
}while(true);
Program:
public class DoWhileExample2
{
public static void main(String[] args)
{
do{
System.out.println("infinitive do while loop");
}while(true);
}
}
OUTPUT:
infinitive do while loop
infinitive do while loop
infinitive do while loop
ctrl+c (to exit out of the program)

Un-Conditional statements

Break Statement:
When a break statement is encountered inside a loop, the loop is immediately terminated and the
program control resumes at the next statement following the loop.
The Java break is used to break loop or switch statement.
It breaks the current flow of the program at specified condition. In case of inner loop, it breaks only
inner loop.

Syntax:
jump-statement;
break;

Page 50
Example program 1 on break statement:
public class BreakExample
{
public static void main(String[] args)
{
for(int i=1;i<=10;i++){
if(i==5){
break;
}
System.out.println(i);
}
}
}
OUTPUT:
1
2
3
4

Example program 2 on break statement:


It breaks inner loop only if you use break statement inside the inner loop.
Program:
public class BreakExample2
{
public static void main(String[] args)
{
for(int i=1;i<=3;i++)
{
for(int j=1;j<=3;j++)
{
if(i==2&&j==2)
{
break;
}
System.out.println(i+" "+j);
}
}
}
}
OUTPUT:
11
12
13
21
31
32
33

Page 51
Continue Statement:
The continue statement is used in loop control structure when you need to immediately jump to the
next iteration of the loop. It can be used with for loop or while loop.
The Java continue statement is used to continue loop. It continues the current flow of the program and
skips the remaining code at specified condition. In case of inner loop, it continues only inner loop.
Syntax:
jump-statement;
continue;
Example program on continue statement:
public class ContinueExample
{
public static void main(String[] args)
{
for(int i=1;i<=10;i++)
{
if(i==5)
{
continue;
}
System.out.println(i);
}
}
}
OUTPUT:
1
2
3
4
6
7
8
9
10

Page 52
JAVA Expressions:
Expressions are made up of variables, operators, literals and method calls that evaluates to a single
value according to the syntax of the language.
Operators may be used in building expressions, which compute values; expressions are the core
components of statements; statements may be grouped into blocks.
Example 1:
int abc;
abc = 100;
Here, abc = 100, is an expression that returns an int because the assignment operator returns a value of
the same data type as its LHS operand.
Example 2:
int a=10, b=30;
int c;
c = a + b;
Here, c = a + b, is an expression that returns an int.
Example 3:
If (number1 = = number2)
{
Sytem.out.println(“Hello java world”);
}
Here, number1 = = number2 is an expression that returns Boolean value and “Hello java world” is an
string expression.

Compound expressions:
The Java programming language allows you to construct compound expressions from various smaller
expressions as long as the data type required by one part of the expression matches the data type of the
other.
Example of a compound expression is: 1 * 2 * 3;
Here the above example, the order in which the expression is evaluated is unimportant because the
result of multiplication is independent of order; the outcome is always the same, no matter in which
order you apply the multiplications.
However, this is not true of all expressions. For example, the following example 1 expression gives
different results, depending on whether you perform the addition or the division operation first:
Example 1:
x + y / 100; // ambiguous
To overcome this, an expression will be evaluated using balanced parenthesis: ( and ). For example, to
make the previous expression unambiguous, you could write the following example 2:
Example 2:
(x + y) / 100; // unambiguous, recommended

Java Blocks:
A block is a group of statements (zero or more) that is enclosed in curly braces { }.
Example:
class AssignmentOperator
{
public static void main(String[] args)
{

Page 53
String band = "Beatles";
if (band == "Beatles")
{ // start of block
System.out.print("Hey ");
System.out.print("Jude!");
} // end of block
}
}
There are two statements System.out.print("Hey "); and System.out.print("Jude!"); inside the
mentioned block above.

Java operator precedence and associativity rules


In Java, when an expression is evaluated, there may be more than one operators involved in an
expression.
When more than one operator has to be evaluated in an expression, Java interpreter has to decide
which operator should be evaluated first.
Java has well-defined rules for specifying the order in which the operators in an expression are
evaluated when the expression has several operators.
For example: multiplication and division have a higher precedence than addition and subtraction.
Java makes this decision on the basis of the precedence and the associativity of the operators.

Precedence order:
Precedence is the priority order of an operator, if there are two or more operators in an expression
then the operator of highest priority will be executed first.
For example: In expression 1 + 2 * 5, multiplication (*) operator will be processed first and then
addition. It's because multiplication has higher priority or precedence than addition.

Associativity:
When an expression has two operators with the same precedence, the expression is evaluated
according to its associativity.
Associativity tells the direction of execution of operators that can be either left to right or right to left.
For example, in expression a = b = c = 8 the assignment operator is executed from right to left that
means c will be assigned by 8, then b will be assigned by c, and finally a will be assigned by b. You
can parenthesize this expression as (a = (b = (c = 8))).
Note that, you can change the priority of a Java operator by enclosing the lower order priority operator
in parentheses but not the associativity.
For example, in expression (1 + 2) * 3 addition will be done first because parentheses has higher
priority than multiplication operator.

Page 54
Precedence and associativity of Java operators:
The table below shows all Java operators from highest to lowest precedence, along with their
associativity.

Precedence Operator Description Associativity


[] array index
1 () method call Left -> Right
. member access
++ pre or postfix increment
-- pre or postfix decrement
2 +- unary plus, minus Right -> Left
~ bitwise NOT
! logical NOT
3 new Object creation Right -> Left
* multiplication
4 / division Left -> Right
% modulus (remainder)
+,- Addition, Subtraction
5 Left -> Right
+ Concatenation
< less than
<= less than or equal to
6 Left -> Right
> greater than
>= greater than or equal to
== Equal to
7 Left -> Right
!= Not equal to
& bitwise AND
^ bitwise XOR
8 | bitwise OR Left -> Right
&& Logical AND
|| Logical OR
9 ?: Ternary (conditional) Right -> Left
=
+=
-=
10 Assignment operators Right -> Left
*=
/=
%=

Page 55
Page 56

You might also like

pFad - Phonifier reborn

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

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


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy