0% found this document useful (0 votes)
42 views99 pages

Introduction to Java Programming Basics

Uploaded by

Dheer Desai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views99 pages

Introduction to Java Programming Basics

Uploaded by

Dheer Desai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd

Chapter 1

INTRODUCTION TO JAVA

Contents
1.1 Introduction
1.1.1 Features of Java
1.1.2 Java Programming Environment
1.1.3 Java Program Structure
1.2 Java Tokens and Data Types
1.2.1 Java Token
1.2.2 Data Types
1.2.3 Constants
1.2.4 Symbolic Constants
1.2.5 Variables
1.2.6 Dynamic Initialization
1.2.7 Array and String
1.2.8 Scope of Variables
1.2.9 Type Casting
1.3 Java Tokens and Data Types
1.3.1 Arithmetic Operators
1.3.2 Relational Operators
1.3.3 Logical Operators
1.3.4 Increment and Decrement Operators
1.3.5 Bitwise Operators
1.3.6 Conditional Operator (?:)
1.3.7 Instance of Operator
1.3.8 Data Operator
1.3.9 Operator Precedence and Associativity
1.4 Expressions
1.4.1 Evaluation of Expressions
1.4.2 Type Conversions in Expressions
1.4.3 Mathematical Functions
[Link] min()
[Link] max()
[Link] sqrt()
[Link] pow()
[Link] exp()
(1.1)
Java Programming 1-2 Introduction to Java

[Link] round()
[Link] abs()
1.5 Expressions
1.5.1 Evaluation of Expressions
[Link] if statement
[Link] if-else statement
[Link] Nested if-statement
[Link] if-else Ladder
[Link] switch statement
[Link] nested switch statement
[Link] ?: operator
1.5.2 Looping
[Link] while loop
[Link] do while loop
[Link] for loop
[Link] for each loop
[Link] Nested loops
[Link] Labelled loops
1.5.3 Looping
[Link] break statement
[Link] continue statement
[Link] return statement
 Important Points
 Practice Questions
 MSBTE Questions and Answers
Objectives
 To understand the Features of Java
 To understand Data Types Expression etc.
 To understand Decision making and Looping
 To understand Operators and Tokens in Java

1.1 INTRODUCTION
 Java is a very powerful general-purpose, platform independent programming
language.
 Java is an object oriented programming language developed by Sun Microsystems
which was initiated by James Gosling and released in 1995.
 Java is intended to let application developers "write once, run anywhere" (WORA),
meaning that code that runs on one platform does not need to be recompiled to
run on another.
 Java is a programming language expressly designed for use in the distributed
environment of the Internet.
Java Programming 1-3 Introduction to Java

 Java is, as of 2014, one of the most popular programming languages in use. Some
common applications of Java includes, enterprise applications (banking
applications), mobile applications, embedded system, smart card, robotics,
games and so on.
 There were five primary goals in the creation of the Java language:
1. It should use the object-oriented programming methodology.
2. It should allow the same program to be executed on multiple operating
systems.
3. It should contain built-in support for using computer networks (as Sun was
especially working on Networking.
4. It should be designed to execute code from remote sources securely.
5. It should be easy to use by selecting what was considered the good parts of
other object-oriented languages.
 There are mainly 4 types of applications that can be created using java:
1. 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.
2. Web Application: An application that runs on the server side and creates
dynamic page, is called web application. Currently, servlet, jsp, struts, jsf etc.
technologies are used for creating web applications in java.
3. 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.
4. Mobile Application: An application that is created for mobile devices.
Currently Android and Java ME are used for creating mobile applications.
 The Java programming language is popular on internet due to the following
reasons:
1. Java is meant to be used in distributed environments such as internet. Since
both web and Java share the same philosophy, Java could be easily in-
corporate into the web system.
2. Java is a platform independent language. It’s all applications can run as it on
various operating systems.
3. Before Java World Wide Web was limited to display of still images only.
However, incorporation of Java into web pages has made it capable of
supporting animation graphics, games and wide ranges of special effects.
4. With the support of Java, web has become more interactive and dynamic. On
the other hand, with the support of the web we can run Java programs
Java Programming 1-4 Introduction to Java

someone else’s computer across the internet. Internet users can use Java to
create applet programs and run them locally using a Java enabled browser
such as Hot Java or Java enabled browser to download an applet located on a
computer anywhere on the internet and run it on his local computer.
5. We can create the Servlets in Java. Servlets are small programs that execute
on the server side of a Web connection. Just as applets dynamically extend
the functionality of a Web browser, servlets dynamically extend the
functionality of a Web server.
Programming Approaches:
1. Procedure oriented programming (POP):
o In procedure oriented programming everything is organized in functions by
functions.
o Flow of execution of the program is taken through the linear steps.
o The emphasis is given on the procedures rather then data.
o The data can be accessed anywhere in the functions. So there is no security
for this data.
o C is the best example of such procedure oriented programming. C language
employed this programming approach successfully.

Fig. 1.1: Procedure Oriented Methodology


2. Object oriented programming (OOP):
o Object oriented programming is a programming paradigm that uses "objects"
to design applications and computer programs.
o Basically, it is introduced to eliminate the flaws in the procedure oriented
programming. It is the best way to manage the increasing complexity in
procedure orientation.
o Object oriented programming organizes the program around the objects i.e. it
treats the data as a critical element in the program development and does not
allow it to flow freely around the system.
Java Programming 1-5 Introduction to Java

o OOP ties this data more closely to the functions that operate on it and
protects it from unintentional modification by other functions.
o Simula is considered as the first object-oriented programming language.
Smalltalk is considered as the first truly object-oriented programming
language.
o As shown in the Fig. 1.2, the data is centered element in the object, which can
be only be accessed by all the functions defined in it. (In Java’s terminology,
function is called as method).

Fig. 1.2: Procedure Oriented Methodology

1.2 BASIC CONCEPTS IN OBJECT ORIENTED PROGRAMMING


1. Classes:
o The basic element of object oriented programming is a class.
o A class is a collection of objects of similar type.
o The entire set of data and code of an object can be made using a user defined
data type called as class.
o In short, we can call the class is data type of object. A class can be defined as
“a blueprint or prototype that defines the variables
o and methods common to all objects of a certain kind.” or “a class is a
template/blue print for defining the behavior and states of the objects.”
o Classes are user defined data types. Once class has defined, we can create
any number of objects of that.
o For example, you could create a bicycle class that declares several instance
variables to contain the current gear, the current cadence, and so on, for each
bicycle object.
2. Objects:
o Object is called as the instance of the class.
o Object is the run time entity in an object oriented system.
o In short, we can call object as a variable of type class.
Java Programming 1-6 Introduction to Java

o Each object is associated with data of type class with which they are created.
A class is thus collection of objects of similar types. For example, Maharashtra,
Gujarat, Bengal, Goa, Tamilnadu are the members of class India.
o We can define object as “an object is a software bundle of variables and
related methods.”
o Objects have states and behaviors. State is represented by instance variable
and static variable and behaviors are implemented as methods.
3. Data Abstraction:
o Hiding internal details and showing functionality is known as abstraction.
o For example: phone call, we don't know the internal processing. In java, we
use abstract class and interface to achieve abstraction.
o Abstraction is process of hiding the implementation details and showing only
the functionality.
o Abstraction refers to the act of representing essential features without
including the background details or explanation.
o Classes use the concept of abstraction and are defined as a list of abstract
attributes such as size, weight, cost and methods that operate on these
attributes. Since classes use the concept of data abstraction, they are known
as ‘Abstract Data Type ADD’.
4. Encapsulation:
o Encapsulation refers to wrapping up of data and methods into the single unit
(i.e. class).
o Encapsulation is:
 Binding the data with the code that manipulates it.
 It keeps the data and the code safe from external interference
o The data contained in the object is not accessible outside of the class.
o The methods which are wrapped around the object can access the data.
These methods provide interface between object’s data and program. This
insulation of the data from direct access by the program is called ‘data
hiding’.
o A java class is the example of encapsulation.
o Looking at the example of a power steering mechanism of a car. Power
steering of a car is a complex system, which internally have lots of
components tightly coupled together, they work synchronously to turn the car
in the desired direction. It even controls the power delivered by the engine to
the steering wheel. But to the external world there is only one interface is
available and rest of the complexity is hidden. Moreover, the steering unit in
itself is complete and independent. It does not affect the functioning of any
other mechanism.
Java Programming 1-7 Introduction to Java

5. Inheritance:
o It is the process by which one class acquires the properties of objects of
another class.
o It increases code reusability by grouping common logics and data’s in a class
and allows other classes to inherit it without rewriting it.
o We can define inheritance as “the process by which objects of one class can
get the properties of objects of another class.”

Fig. 1.4: Example of an inheritance


o See the example given in Fig. 1.4. ‘Vehicles’ is the main class we can call it a
root class, base class or super class. It is having its own attributes and
methods. Theses properties are inherited to two different classes i.e. Two-
wheeler and Four-wheeler. So, Two-wheeler and Four wheeler both have
wheels and can be manually driven. Furthermore, Two-wheeler and Four-
wheeler classes can have their own uncommon properties. These can also be
inherited in their sub-classes i.e. Bicycle and Scooter for Two-Wheeler and
Tata – nano and Lenovafor Four wheeler. Thus, there is no need to have the
similar properties again in sub-classes.
6. Polymorphism:
o Polymorphism is the Greek term in which 'Poly' means ― "many" and "morph"
means "form". Polymorphism means the ability to take more than one form. In
short polymorphism means "one name many form".
o Polymorphism plays a main role in allocate objects having different internal
structures to share the same external interface
Java Programming 1-8 Introduction to Java

o Take an example of one method called area( ). When we pass one argument
to this method, it will consider it as side of a square and according to that
area of the square will be calculated. When we pass two arguments to
area( ), it will consider them as length and breadth of a rectangle and
calculate area accordingly. And after passing three arguments to
area( ), these can be three sides of the triangle to calculate the area of it. So,
here method area( ) is having property of polymorphism i.e. ability to take
more than one forms. Our method name is same but its data i.e. parameters
decides its function.
o There are two types of polymorphism:
(i) Compile-time polymorphism: In compile time polymorphism, method
to be invoked is determined at the compile time. Compile time
polymorphism is nothing but the method overloading in java.
Method overloading means having multiple methods with same name
but with different signature (number, type and order of parameters).
Compile time Polymorphism also called as Static polymorphism.
(ii) Runtime Polymorphism: In rum time polymorphism, the method to be
invoked is determined at the run time. The example of run time
polymorphism is method overriding. When a subclass contains a method
with the same name and signature as in the super class then it is called
as method overriding. Runtime polymorphism also called as dynamic
polymorphism.
7. Dynamic Binding:
o The term binding refers to assigning one thing to another.
o In programming languages, there are two types of bindings i.e. static and
dynamic.
o Static binding means at the time of compilation and execution, compiler
knows what to do and with which values? But, in case of dynamic binding
compiler decides the function at run time i.e. at execution time. Thus, at the
time of compilation, compiler does not know which method to call? This
decision is made after execution of program.
Comparison of Dynamic and Static Binding
Sr. Dynamic Binding Static Binding
No.
1. When compiler is not able to resolve The binding which can be resolved
the call/binding at compile time, at compile time by compiler is
such binding is known as dynamic known as static or early binding.
or late binding.
2. Dynamic binding happens at Static binding happens at compile-
Java Programming 1-9 Introduction to Java

runtime. time.
3. Dynamic binding for overridden Java uses static binding for
methods. overloaded methods.
4. Binding of overridden methods Binding of private, static and final
happen at runtime. methods always happen at compile
time since these methods cannot be
overridden.
Object-Oriented Programming vs. Procedural Programming:
Terms Object Oriented Procedure Oriented
Programming Programming
Divided into In OOP, program is divided into In POP, program is divided into
parts called objects. small parts called functions.
Importance In OOP, Importance is given to In POP, Importance is not given
the data rather than procedures to data but to functions as well
or functions because it works as as sequence of actions to be
a real world. done.
Approach OOP follows Bottom Up POP follows Top Down approach.
approach.
Access OOP has access modifier named POP does not have any access
modifier Public, Private, Protected, etc. modifier.
Data Moving In OOP, objects can move and In POP, Data can move freely
communicate with each other from function to function in the
through member functions. system.
Expansion OOP provides an easy way to To add new data and function in
add new data and function. POP is not so easy.
Data Access In OOP, data cannot move easily In POP, Most function uses
from function to function, it can Global data for sharing that can
be kept public or private so we be accessed freely from function
can control the access of data. to function in the system.
Data Hiding OOP provides Data Hiding so POP does not have any proper
provides more security. way for hiding data so it is less
secure.
Overloading In OOP, overloading is possible in In POP, Overloading is not
the form of Function Overloading possible.
and Operator Overloading.
Examples C++, JAVA, [Link], C#. NET. C, VB, FORTRAN, Pascal.
Java Programming 1 - 10 Introduction to Java

History of Java:
 Java is developed by group of Sun Microsystems engineers, led by an all-around
computer wizard James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and
Mike Sheridan. James Gosling with his team started developing a new language,
which was completely system independent. This language was initially called
OAK. Since this name was registered by some other company, later it was
changed to Java. Sun formally announced Java at Sun World conference in 1995.
On January 23rd 1996, JDK1.0 version was released.
Java version releases:
o JDK 1.0 was released on January 23, 1996. The code was named as oak.
o JDK 1.1 released on February 19, 1997. The new features included in jdk 1.1
are,
JDBC, inner classes, java beans, RMI, Reflection.
o J2SE 1.2 released on December 8, 1998. The code was named as playground.
o J2SE 1.3 released on May 8, 2000. The code was named as kestrel.
o J2SE 1.4 released on February 6, 2002. The code was named as merlin.
o J2SE 5.0 released on September 30, 2004. The code was named as tiger.
o Java SE 6 released on December 11, 2006. The code was named as mustang.
o Java SE 7 released on July 28, 2011. The code was named as Dolphin.

 Features of Java are listed below:


1. Simplicity: Java was designed to be easy for the professional programmer to
learn and use effectively. If you already understand the basic concepts of
object-oriented programming, learning Java will be even easier because Java
is strictly object-oriented language than C++. If you are an experienced C++
programmer, moving to the Java will require very little effort. Because Java
has the C/C++ syntax and many of the object-oriented features of C++.
2. Object Oriented: The object oriented language must support the
characteristics of the OOPs, and Java is a fully object oriented language. Java
is strictly or truly object-oriented language due to the following reasons:
(i) Everything in Java is considered as the object including the source
program because it is written in a class itself.
(ii) Java implements all of the features of Object oriented programming
including inheritance, polymorphism, dynamic binding etc.
(iii) Most of the methods and constructors of the Java classes are overloaded.
That is, Java itself implements the property of polymorphism in large
extent.
Java Programming 1 - 11 Introduction to Java

(iv) Java does not support the multiple inheritances to avoid the duplication
of data. But multiple inheritance in supported by the way of ‘interface’.
3. Platform Independence: Java has implemented ‘Write Once Run
Everywhere’ (Known as platform independent) strategy. Program written on
one platform (operating system) can be run on any other operating system.
Changes and up gradation in the operating system does not affect Java
programs to run. This is the reason why Java has become popular language for
programming on internet all over the world. We can download Java application
or Applet from internet and execute it locally. Size of the data types used in
Java programs is also machine-independent.
4. Portable: Unlike C and C++, there are no “implementation-dependent
”aspects of the specification in Java. The sizes of the primitive data types are
specified, as is the behavior of arithmetic on them. For example, an int in Java
is always a 32-bit integer. In C/C++, int can mean a 16-bitinteger, a
32-bit integer, or any other size that the compiler vendor likes. The feature of
java "write once-run any-where" make java portable. Many type of computers
and operating systems are used for programs by porting an interpreter for the
Java Virtual Machine to any computer hardware/operating system, one is
assured that all code compiled for it will run on that system. This forms the
basis for Java's portability.
5. Compiled and Interpreted: Java is the only language, which has compiler
and interpreter both. This has been designed to ensure platform
independence nature for the language. Due to this Java has been made a two-
stage system. First, Java complier translates the source code into bytecode
instructions and thereafter in the second stage, Java interpreter generates
machine code that can be directly executed by machine that is running Java
program.
6. Java is Robust: Java makes an effort to eliminate error prone situations by
emphasizing mainly on compile time error checking and runtime checking.
7. Security: Security becomes an important issue for a language that is used for
programming on Internet. So, Java enables the construction of virus-free,
tamper-free systems. Java systems not only verify all memory access but also
ensure that no viruses are communicated with an application or an applet. It
also contains security manager class that determines what resources a class
can access such as reading and writing to the local disk. With Java's secure
feature it enables to develop virus-free, tamper-free systems. Authentication
techniques are based on public-key encryption.
8. Dynamic: Java is considered to be more dynamic than C or C++ since it is
designed to adapt to an evolving environment. Java programs can carry
Java Programming 1 - 12 Introduction to Java

extensive amount of run-time information that can be used to verify and


resolve accesses to objects on run-time.
(i) High Performance: With the use of Just-In-Time compilers, Java enables
high performance.
(ii) Distributed: Java is designed for the distributed environment of the
internet.
9. Architectural-neutral: Java compiler generates an architecture-neutral
object file format which makes the compiled code to be executable on many
processors, with the presence of Java runtime system.

 Java environment includes a number of development tools, classes and methods.


 The development tools are part of the system known as Java Development Kit
(JDK) and the classes and methods are part of the Java Standard Library (JSL),
also known as the Application Programming Interface (API).
1. Java Development kit (JDK):
 The JDK comes with a set of tools that are used for developing and running Java
program.
 Java Development Kit has a collection of tools for Java Development.
Table 1.1: Java Development Tools
Tool Description
javac The java compiler that translates javacode to bytecode file which java
interpreter can understand.
java Java interpreter that runs applets and applications interpreting
bytecode files. It launches a java application by starting Java Runtime
Environment, loading a specified class and invoking that class’s main
method to run the program.
appletviewer Enables us to run java applets. Normally applets are the programs
those can be embedded in a web page and run in web browser. This
is very useful tool which gives the same effect but on console.
javadoc Creates HTML formatted documentation from java source code files.
jdb Java debugger that helps us in finding errors in java programs.
 A Java technology runtime environment runs code compiled for a JVM and
performs three main tasks:
(i) Loads code: Performed by the class loader.
(ii) Verifies code: Performed by the bytecode verifier.
(iii) Executes code: Performed by the runtime interpreter.
 Fig. 1.5 depicts a typical Java programming environment.
Java Programming 1 - 13 Introduction to Java

Fig. 1.5
 The Java source file is stored as a ‘.java’ file and is compiled to get an executable
‘.class’ file. A ClassLoader is use to download the executable file, the bytecode of
which is then interpreted, a process which makes the file understood by the
underlying processor which executes the file instructions.
 The operating system called ‘native code’ that the processor understands is never
stored, and has to be generated from the .class file each time. This naturally
extends the processing time over the shorter time had the process be written in
C, but Java overcomes this to an extent by including a ‘Just-In-Time’ compiler
with the interpreter.
 The JIT compiler enables all the frequently used class files to be compiled into
native code just the once, rather than each time they are used. This improves the
speed of execution of the commands to an acceptable level. The stored native
code last only for the lifetime of the application.
 The API provided by the language is constantly available to the JVM, and the
entire package, excepting the compiler that generates the .class file from
the .java file, is referred to as the Java Runtime Environment (JRE):
(i) Bytecode:
 The Java language is used bytecode. The bytecode is a special type of
code that runs only on the JVM.
 The bytecode is generated after the compilation of the program by the
Java compiler.
 A byte code is the machine independent code so; it can be executed on
any machine. That is if you have created this byte code on Windows
operating system then it can be executed on Linux operating system.
Java Programming 1 - 14 Introduction to Java

Fig. 1.6
(ii) Java Virtual Machine:
 All the programming language compilers translate the source code into
machine code. Java compiler also performs the same function. However,
the difference between Java and the other compilers is that Java compiler
produces the intermediate code known as byte code for the machine that
does not exist.
 This machine is called as Java Virtual Machine. It exists only inside the
computer memory. It is a simulated computer within the computer and
does all the functions of the computer.
 The Java virtual machine is called "virtual" because it is an abstract
computer (that runs compiled programs) defined by a specification.
 The Java Virtual Machine's (JVM) function is to load the appropriate class
files for executing a Java Program, and then to execute it.
 JVM forms the Java Runtime Environment (JRE) for the program execution.
Each operating system and CPU architecture requires a different JRE. The
JRE comprises a set of base classes, which are an implementation of the
base Java API, as well as a JVM.
 Fig. 1.7 shows the process of compilation of a Java program into byte
code. This is also referred to as virtual machine code.

Fig. 1.7: Process of compilation of Java Program


Java Programming 1 - 15 Introduction to Java

 The virtual machine code is not machine specific. Java interpreter


generates this code by acting as an intermediary between the virtual
machine and real machine as shown in the Fig. 1.8.

Fig. 1.8: Process of converting bytecode into machine code


 Fig. 1.9 below illustrates how Java works on a typical computer. The Java
object framework (Java API) acts as the intermediary between the user
program and the virtual machine, which in turn acts as intermediary
between the operating system and the Java object framework.

Fig. 1.9: Layers of interaction of a Java Program


2. API (Application Programming Interface)
 Java API includes hundreds of classes and functions grouped into several
functional packages. Most commonly used packages are given in following table.
Language A collection of classes and methods required for [Link]
Support Package implementing basic features of Java.
Utility Package A collection of classes to provide utility functions [Link]
such as date and time.
Input/Output A collection of classes for input and output [Link]
Package manipulation.
Networking A collection of classes for communicating with [Link]
Package other computers.
AWT Package An Abstract Window Toolkit which contains classes [Link]
and methods for implementing Graphical User
Interface.
Java Programming 1 - 16 Introduction to Java

Applet Package Set of classes to create Java Applets. [Link]

 A Java program may contain many classes of which only one class defines main
method.
 Classes contain data members and methods that operate on the data members of
the class.
 Methods may contain data type declaration and executable statements. To write
a Java program, we first define classes and then put them together.
 Fig. 1.10 shows structure of a java program.

Fig. 1.10: General structure of a Java Program


Class Definitions: A Java program may contain multiple class definitions.
Classes are the primary and essential elements of a Java program. All methods and
variables that we declare in program must be the part of a class. By creating objects
of it, we can call method with particular object.
Main method class: Programs in all programming languages are having the
starting point. Since, every Java program requires a main method as the starting
point. This class is the essential part of a Java program. A simple Java application
program may contain only this part. The main method creates objects of various
classes and establishes communication between them. Program execution starts in
main and also ends in main.
 The steps in writing a Java program are illustrated in Fig. 1.11.
Java Programming 1 - 17 Introduction to Java

Fig. 1.11
Step 1: Write the source codes (.java) using a programming text editor or an
IDE.
Step 2: Compile the source codes (.java) into Java portable bytecodes (.class)
using the JDK compiler ("javac"). IDE compiles the source codes
automatically while they are entered.
Step 3: Run the compiled bytecodes (.class) with the input to produce the
desired output, using the Java Runtime ("java").
1st java program:
public class HelloWorld
{
public static void main(String[] args)
{
[Link]("Hello world!");
}
}
Explanation of above proram:
o class keyword is used to declare a class in java. In the above program
HelloWorld defines the class name in Java. Every class definition in java begins
with an opening brace ‘{‘ and ends with closing brace ‘}’.
o public: It is the access specifier that makes it accessible from all classes.
o static keyword indicates that this method can be invoked simply by using
the name of the class without creating any class-object.
Java Programming 1 - 18 Introduction to Java

o void keyword specifies that this method will not return any type of data.
main() method is the main entry point of the program, to start execution. First
of all JVM calls the main method of a class and start execution. JVM (Java
Virtual Machine) is responsible for running java programs.
o args is a string array that takes values from java command line. It's index
starts from '0'. We can access values by writing args[0], args[1] etc.
o println() function prints the output to the standard output stream (monitor).
o out word represents the standard output stream (monitor).
Compiling the program:
 To compile the Sample program, execute the compiler, javac specifying the name
of the source file on the command line. This is shown below:
C:\> javac [Link]
 Javac compiler creates a file named [Link] which contains the byte
code version of the program. It is an intermediate representation of the program.
Executing the program:
 To actually run the program you must use the Java application launcher called
‘java’. This is shown below:
C:\> java HelloWorld
 We can write comments in java in two ways.
(a) Line comments: It start with two forward slashes (//) and continue to the end
of the current line. Line comments do not require an ending symbol.
(b) Block comments: It is start with a forward slash and an asterisk (/*) and end
with an asterisk and a forward slash (*/).Block comments can also extend
across as many lines as needed.

1.2 JAVA TOKENS AND IDENTIFIERS

 Tokens are the smallest unit of a program.


 In other words “a token is the smallest element of a program that is meaningful
to the compiler.”
 Tokens supported in Java include keywords, variables, constants, special
characters, operations etc., (See Fig. 1.12).
Java Programming 1 - 19 Introduction to Java

Fig. 1.12: Tokens in java


 When you compile a program, the compiler scans the text in your source code
and extracts individual tokens. While tokenizing the source file, the compiler
recognizes and subsequently removes whitespaces (spaces, tabs, newline and
form feeds) and the text enclosed within comments.
 There are five types of token as follows:
1. Literals:
o Literals in Java are a sequence of characters (digits, letters and other
characters) that characterize constant values to be stored in variables.
o Java language specifies five major types of literals are: 1. Integer literals,
2. Floating point literals, 3. Character literals, 4. String literals, 5. Boolean
literals.
2. Identifiers:
o Identifiers are programmer-created tokens.
o They are used for naming classes, methods, variables, objects, labels,
packages and interfaces in a program.
o Java identifiers follow the following rules:
(i) They can have alphabets, digits, and the underscore and dollar sign
characters.
(ii) They must not start with a digit.
(iii) Uppercase and lowercase letters are individual.
(iv) They can be of any length.
o Identifier must be meaningful, easily understandable and descriptive.
For example:
Private and local variables like ―length‖.
Name of public methods and instance variables begin with lowercase letter
like ―addition‖
3. Keywords:
Java Programming 1 - 20 Introduction to Java

o Keywords are important part of Java. Java language has reserved 50 words as
keywords.
o Keywords have specific meaning in Java. We cannot use them as variable,
classes and method.
o Following used by Java are the
abstract char catch boolean
default finally do implements
if long throw private
package static break double
this volatile import protected
class throws byte else
float final public transient
native instanceof case extends
int null const new
return try for switch
interface void while synchronized
short continue goto super
assert const
4. Operator:
o Java carries a broad range of operators. Operators are used in programs to
operate data and variables. They frequently form a part of mathematical or
logical expressions.
o Categories of operators are: 1. Arithmetic operators, 2. Logical operators,
3. Relational operators, 4. Assignment operators, 5. Conditional operators,
6. Increment and decrement operators and 7. Bit wise operators.
5. Separator:
o Separators are symbols. It shows the separated code, they describe function
of our code.
o Following table shows various type of separators used in Java.
Name Use
() Parameter in method definition, containing statements for
conditions, etc.
{} It is used for define a code for method and classes.
[] It is used for declaration of array.
; It is used to show they separate statement.
, It is used to show the separation in identifier in variable
Java Programming 1 - 21 Introduction to Java

declaration.
. It is used to show the separate package name from sub-
packages and classes, separate variable and method from
reference variable.

1.2 DATA TYPES


 The type of value that a variable can hold is called data type.
 Every variable declared in a Java program is having the data type. Data type
specifies the size and type of values that a variable can have.
 When we declare a variable we need to specify the type of value it will hold along
with the name of the variable.
 Java has a rich set of data types. The data types in the Java programming
language are divided into two categories as shown in Fig. 1.13.
 Primitive types are also called as built in data types or predefined data types and
derived data types are called as reference types.
 Primitive data types are non grouped pieces of data which can have only one
value at a time. They are the simplest built in forms of data in Java. Java initializes
all primitive data types to default values if an initial value is not explicitly
specified by the programmer. Primitive data types are used to store the actual
value
 Reference data types are made by the logical grouping of primitive data types.
These are called reference data types because they contain the address of a
value rather than the value itself. Reference data type are used to stored the
reference’s (address) of another object.

Fig. 1.13
Java Programming 1 - 22 Introduction to Java

 Java's built-in data types called primitive data types. There are eight primitive
data types supported by Java.
 Primitive data types are predefined by the language and named by a keyword.
 Let us now look into detail about the eight primitive data types:
(i) byte:
 Byte data type is an 8-bit signed two's complement integer.
 Minimum value is –128 (–2^7).
 Maximum value is 127 (inclusive)(2^7 – 1).
 Default value is 0.
 Byte data type is used to save space in large arrays, mainly in place of
integers, since a byte is four times smaller than an int.
 Example: byte a = 100 , byte b = -50
(ii) short:
 Short data type is a 16-bit signed two's complement integer.
 Minimum value is -32,768 (-2^15)
 Maximum value is 32,767 (inclusive) (2^15 -1)
 Short data type can also be used to save memory as byte data type. A
short is 2 times smaller than an int
 Default value is 0.
 Example: short s = 10000, short r = – 20000.
(iii) int:
 Int data type is a 32-bit signed two's complement integer.
 Minimum value is - 2,147,483,648.(-2^31)
 Maximum value is 2,147,483,647(inclusive).(2^31 -1)
 Int is generally used as the default data type for integral values unless
there is a concern about memory.
 The default value is 0.
 Example: int a = 100000, int b = -200000
(iv) long:
 Long data type is a 64-bit signed two's complement integer.
 Minimum value is -9,223,372,036,854,775,808.(-2^63)
 Maximum value is 9,223,372,036,854,775,807 (inclusive). (2^63 -1)
 This type is used when a wider range than int is needed.
 Default value is 0L.
 Example: long a = 100000L, int b = -200000L.
Java Programming 1 - 23 Introduction to Java

(v) float:
 Float data type is a single-precision 32-bit IEEE 754 floating point.
 Float is mainly used to save memory in large arrays of floating point
numbers.
 Default value is 0.0f.
 Float data type is never used for precise values such as currency.
 Example: float f1 = 234.5f.
(vi) double:
 double data type is a double-precision 64-bit IEEE 754 floating point.
 This data type is generally used as the default data type for decimal
values, generally the default choice.
 Double data type should never be used for precise values such as
currency.
 Default value is 0.0d.
 Example: double d1 = 123.4.
(vii) boolean:
 boolean data type represents one bit of information.
 There are only two possible values: true and false.
 This data type is used for simple flags that track true/false conditions.
 Default value is false.
 Example: boolean one = true.
(viii) char:
 char data type is a single 16-bit Unicode character.
 Minimum value is '\u0000' (or 0).
 Maximum value is '\uffff' (or 65,535 inclusive).
 Char data type is used to store any character.
 Example: char letterA ='A'.

 Reference data types or objects are created using class constructors. It's type
can't be changed after declaration.
 Default value of any reference variable is null.
 A reference variable can be used to refer to any object of the declared type or
any compatible type.
 Example: Mainclass mc = new Mainclass("Ankit") .
Java Programming 1 - 24 Introduction to Java

 Constant in Java refer to fixed values that do not change during the execution of
the program.
 A constant in Java is used to map an exact and unchanging value to a variable
name.
 Constants are used in programming to make code a bit more robust and human
readable.
 Constants in java are fixed values those are not changed during the Execution of
program.
 Constant in Java can be declared by using the keyword final. The value of a
constant cannot change throughout the program.
 The keyword final indicates that once you assign some value to a variable, the
value does not change throughout the program.
 In Java, by convention, constants are variables generally declared in uppercase
only. For example:
final int MAX=100;
 In the above example, MAX is an integer constant and its fixed value is 100.
 Java supports several types of constants. They are
1. Integer constant
Integer constant refers to sequence of numbers without decimal point. There are
three types of integer constants
(i) Decimal integers: They consist of combination digits 0 through 9 with or
without negative sign.
Example: 105 -245 0
(ii) Octal integer: They consist of combination of digits 0 through 7 with
leading zero.
Example: 074 0 034
(iii) Hexadecimal integer: They consist of combination of digits 0 through 9
and letter a through f or A through F with leading 0x or 0X.
Example: 0X7A4 0Xa 0xA4
2. Real constants
Real constant refers to sequence of numbers with decimal point. They can be
represented in two forms decimal notation and exponential notation
(i) Decimal notation: The deciaml notation has three parts the integer part,
the decimal point and the fractional part and can be used to represent sinle
precision numbers.
Example: 2.15 -7.8 0.78
(ii) Exponential notation: The exponential notation is used to represent
double precision numbers and has the following syntax
Java Programming 1 - 25 Introduction to Java

mantissa e/E Exponent


The mantissa is either a real number expressed in decimal notaion or an
integer. The exponent is an integer withan optinal + or - sign. e2 means
102.
Example: 0.97e4 12e-2 -1.2E-4
3. Character constant
A single character enclosed within single quotes is called character constant.
Example: ‘5’ ‘E’ ‘$’
4. String Constants:
A sequence of characters enclosed within double quotes is called string constant.
Example: “Hai” “Java programming” “2014”
5. Back slash character constant
They are special character constants that are used in output methods.
Example:
\b’ - Back spac
‘\t’ -Horizontal
‘\n’ -New line
‘\r’ -Carriage return
These constants are also known as escape sequences.

 Symbolic constants are named constants like:final, double PI = 3.14 ;


 In Java program, there are many things which is requires repeatedly and if we
want to make changes then we have to make these changes in whole program
where this variable is used. For this purpose, Java provides ‗final‘ keyword.
Syntax: final type Symbolic_name=value;
 We can declare a variable in any scope to be final. The value of final variable
cannot change after it has been initialised. Such variables are similiar to
constants.
 To declare a final variable, we can use keyword final in the variable declaration.
final int K = 2;
 The previous statement declares a final variable and initialises it, all at once. If we
try to assign a new value to a variable, it will give us compiler error.
Program 1.1: Program for final variable declaration and initialization.
class finInt
{
public static void main(String [] args)
{
Java Programming 1 - 26 Introduction to Java

final int K = 25;


[Link](K);
K = 100;
[Link](K);
}
}
 This will give compiler error at line no. 6. It says "cannot assign a value to final
variable k".
k = 100;
If we remove statement k = 100. It will give us proper output i.e. 25 and 25.

 Variables are nothing but reserved memory locations to store values. This means
that when we create a variable we reserve some space in memory.
 A variable refers to the memory location that holds values like numbers, texts etc.
in the computer memory.
 A variable is a name of location where the data is stored when a program
executes (See Fig. 1.14)

Fig. 1.14
int data=50;//Here data is variable and 50 is value.
 While naming Java variables we have to adhere to 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 "_".
Java Programming 1 - 27 Introduction to Java

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.
7. Do not begin with a digit.
8. A name can be of any realistic length.
9. A name cannot be a reserved word (keyword).
Declaration of variable:
 In Java, all variables must be declared before they can be used.
 The basic form (syntax) of a variable declaration is shown here:
dataType variableName;
 See the following example for variables declaration:
int num; //represents that num is a variable that can
store value of int type.
String name; //represents that name is a variable that can
store string value.
boolean bol; //represents that bol is a variable that can
take boolean value (true/false);
 You can assign a value to a variable at the declaration time by using an
assignment operator ( = ).
int num = 1000; // This line declares num as an int variable
which holds value "1000".
boolean bol = true; // This line declares bol as boolean variable
which is set to the value "true".

 Initialization is the process of providing value to a variable at declaration time.


 A variable is initialized once in its life time. Any attempt of setting a variable's
value after its declaration is called assignment.
 To use a local variable you have to either initialize or assign it before the variable
is first used. But for class members, the compulsion is not so strict. If you don't
initialize them then compiler takes care of the initialization process and set class
members to default values.
 Java allows its programmers to initialize a variable at run time also. Initializing a
variable at run time is called dynamic initialization.
Program 1.2: Program for dynamic initialization.
public class DynamicInitializationDemo
{
Java Programming 1 - 28 Introduction to Java

public static void main(String[] args)


{
//dynSqrt will be initialized when [Link]
//will be executed at run time
double dynSqrt = [Link] (16);
[Link]("sqrt of 16 is: " + dynSqrt);
}
}
Output
======
sqrt of 16 is: 4.0

1. Array:
 Java provides a data structure, the array, which stores a fixed-size sequential
collection of elements of the same type.
 An array is used to store a collection of data, but it is often more useful to think of
an array as a collection of variables of the same type.
 Array are called object in Java and array names are called reference variable.
Both primitive type and reference type or user defined type can be arrays in Java.
 Array is index based, first element of the array is stored at 0 index.

Fig. 1.15
Syntax: type_name var_name/ref_name[]=new type_name[size];
Example:
 Following statement declares an array variable, myList, creates an array of 10
elements of double type and assigns its reference to myList:
double[] myList = new double[10];
Fig. 1.16 represents array myList. Here, myList holds ten double values and the
indices are from 0 to 9.
Java Programming 1 - 29 Introduction to Java

Fig. 1.16
2. Strings:
 In general, strings are sequence of characters but in java strings are objects.
Strings, which are widely used in Java programming, are a sequence of
characters.
 The most direct way to create a string is to write:
String greeting = "Hello world!";
 Whenever, it encounters a string literal in your code, the compiler creates a String
object with its value in this case, "Hello world!'.

 Scope refers to the lifetime and accessibility of a variable.


 How large the scope is depends on where a variable is declared. For example, if a
variable is declared at the top of a class then it will accessible to all of the class
methods. If it’s declared in a method then it can only be used in that method.
 The scope of a variable is the part of the program over which the variable name
can be referenced.
 The scope of a variable defines the section of the code in which the variable is
accessible or visible.
 The lifetime of a variable refers to how long the variable exists before it is
destroyed.
 For example, the scope of the variable NUMBER_OF_HOURS_IN_A_DAY is the
whole class. Whereas the scope of NUMBER_OF_DAYS_IN_A_WEEK is just
the calculateHoursInWeeks method:
public class AllAboutHours{
private final int NUMBER_OF_HOURS_IN_A_DAY = 24;
Java Programming 1 - 30 Introduction to Java

public int calculateHoursInDays(int days)


{
return days * NUMBER_OF_HOURS_IN_A_DAY;
}
public int calculateHoursInWeeks(int weeks)
{
final int NUMBER_OF_DAYS_IN_A_WEEK = 7;
return weeks * NUMBER_OF_DAYS_IN_A_WEEK *
NUMBER_OF_HOURS_IN_A_DAY;
}
}
Types of variables:

Fig. 1.17
1. Local variables:
o Local variables are declared in methods, constructors, or blocks.
o Local variables are created when the method, constructor or block is entered
and the variable will be destroyed once it exits the method, constructor or
block.
o Access modifiers cannot be used for local variables.
o Local variables are visible only within the declared method, constructor or
block.
o Local variables are implemented at stack level internally.
o There is no default value for local variables so local variables should be
declared and an initial value should be assigned before the first use.
Example:
public class Test{
public void pupAge(){
int age = 0;
age = age + 7;
[Link]("Puppy age is: " + age);
}
Java Programming 1 - 31 Introduction to Java

public static void main(String args[]){


Test test = new Test();
[Link]();
}
}
Output:
Puppy age is: 7
2. Class/static variables:
o Variables declared inside the class with static keyword are called as static
variables.
o Class variables also known as static variables are declared with the static
keyword in a class, but outside a method, constructor or a block.
o Static variables belongs to class that is memory for static variables will be
allocated when class is loaded into main memory.
o Static variables can be accessed with following 3 ways:
(a) with class name.
(b) with reference variable which contains null.
(c) with reference variable which contains object.
o Static variables can also be primitive type or reference type or final variables.
o Memory will be allocated only once for the static variables for multiple object
creation.
o Static variables can be accessed by calling with the class name.
[Link].
Example:
import [Link].*;
public class Employee{
// salary variable is a private static variable
private static double salary;
// DEPARTMENT is a constant
public static final String DEPARTMENT = "Development ";
public static void main(String args[]){
salary = 1000;
[Link](DEPARTMENT+"average salary:"+salary);
}
}
Output: Development average salary:1000
3. Instance Variables:
Java Programming 1 - 32 Introduction to Java

o Variables declared inside the class without static keyword is called as instance
variables.
o Instance variables belongs to instance or objects that is memory will be
allocated for the instance variables when object of class is created.
o Instance variables can access with the reference variable which contains
object.
o Instance variable can be primitive type or reference type or final variables.
o Instance variables can also be called as non-static variables.
o For multiple object creation, multiple times memory will be allocated for the
instance variables.
Example:
import [Link].*;
public class Employee{
// this instance variable is visible for any child class.
public String name;

// salary variable is visible in Employee class only.


private double salary;

// The name variable is assigned in the constructor.


public Employee (String empName){
name = empName;
}
// The salary variable is assigned a value.
public void setSalary(double empSal){
salary = empSal;
}
// This method prints the employee details.
public void printEmp(){
[Link]("name: " + name );
[Link]("salary:" + salary);
}
public static void main(String args[]){
Employee empOne = new Employee("Amar");
[Link](1000);
[Link]();
}
Java Programming 1 - 33 Introduction to Java

}
Output:
name: Amar
salary:1000.0

 It is the process of converting from one data type to another data type. Casting of
data types in Java is also known as type casting in java.
 There are two types of casting:
1. Implicit Casting:
o Implicit casting is also called as a “widening”. An implicit cast means you
don’t have to write code for the cast.
o In case of implicit casting source is smaller than destination and you no need
to do any casting, JVM will do required casting.
Example:
int a;
byte b1;
a=b1;
//b1=a;//error
o In this example “int” is a datatype which has greater memory allocation than
a “byte” datatype, hence byte can be stored in an int. JVM understands this
type of casting and hence does this type of casting by itself. Another
important point to keep in mind is that byte and int are similar data type
items (They both are numeric type of datatype).
o It looks like
a = b1; //For user
o But inside the JVM it is like
a = (int)b1; //For JVM
2. Explicit casting:
o Explicit casting is also called as “Narrowing”.
o In case of explicit casting destination is smaller than source, you need to do
the casting explicitly JVM will not do any casting.
o In this type of casting the JVM cannot make a decision by itself because a
bigger data type value is being stored in a smaller data type (byte has smaller
memory allocation than int and hence storing int in byte creates a problem).
Thus the user needs to make the decision for the JVM.
Example:
int a;
Java Programming 1 - 34 Introduction to Java

byte b;
a=b;
//b=a;//error
b=(byte)a;

1.3 OPERATORS
 Operator is a symbol that represents some operation that can be performed on
data.
 An operator is the symbol that takes one or more arguments and operates on
them to produce a result. The constants, variables or expression on which
operator operates are called as operands.
Like, 2 +3
In this + is the Operator and 2 and 3 Operands.
 Java supports a rich set of operators which are used in a program, to manipulate
the data and variables. They are usually the part of mathematical or logical
expression.
 Operators in Java are classified into number of categories:
1. Arithmetic operators,
2. Bitwise operators,
3. Increment / Decrement operators,
4. Relational operators,
5. Logical operators, and
6. Conditional operators.

 Arithmetic operators are used in mathematical expressions in the same way that
they are used in algebra.
 Arithmetic operators are used to perform some mathematical operations like
addition, subtraction, multiplication, division, and modulo (or remainder). These
are generally performed on an expression or operands.
 According to number of operands required for an operator, they are classified as
Unary (one operand), binary (two operands) and ternary (three operands)
operators. First five operators are binary operators as they require two operands.
Last two operators are unary operators i.e. they require only one operand to
operate.
 The following table lists the arithmetic operators. Assume integer variable A holds
10 and variable B holds 20, then:
Operator Description Example
+ (Addition) Adds values on either side of the operator A + B = 30
Java Programming 1 - 35 Introduction to Java

- (Subtraction) Subtracts right hand operand from left hand A - B = -10


operand
* (Multiplication) Multiplies values on either side of the operator A * B = 200
/ (Division) Divides left hand operand by right hand B/A=2
operand
% (Modulus) Divides left hand operand by right hand B%A=0
operand and returns remainder

 When we want to compare values of two variables for various means, relational
operators are used. After comparing these values we may take several decisions
in The program.
 Relational operators can be called as comparison operators.
 Java supports six different relational operators.
Operator Meaning Explanation Example Result
== Equal to operator This operator is 10==10 true
used for check
equality
!= Not equal to operator This operator is 10!=10 false
used for check
Inequality
> Greater than operator This operator is 10>10 false
used for check
greater value
< Less than operator This operator is 10<10 false
used for check
lesser value

>= Greater than or equal This operator is 10>=10 true


to operator used for check
greater as well
as equality
<= Less than or equal to This operator is 10<=10 true
operator used for check
lesser as well as
equality
 Observe the following relational expressions which returns boolean values
36 > 42 true
Java Programming 1 - 36 Introduction to Java

52.14 < 45 false


10 < 8+9 false
-74 != 0 false
 When the arithmetic expressions are used on either side of a relational operator,
the arithmetic expression will be evaluated first and then the results are
compared. In short, the arithmetic operators are having highest priority over
relational operators.

 When we want to form compound conditions by combining two or more relations,


then we can use logical operators.
 Logical operators, compare or evaluate logical and relational expressions.
 There are only three logical operators which are related with the logical decisions.
Assume Boolean variables A holds true and variable B holds false, then:
Operator Description Example
&& (Logical AND operator) If both the operands are non- (A && B) is false.
zero, then the condition becomes
true.
|| (Logical OR Operator) If any of the two operands are (A || B) is true.
non-zero, then the condition
becomes true.
! (Logical NOT Operator) Use to reverses the logical state !(A && B) is true.
of its operand. If a condition is
true then Logical NOT operator
will make false.
 First two operators are used to combine the conditions i.e. to form a compound
conditional expression. Literally, they have same meaning as in the digital
techniques. Third operator is used to inverse the condition.
For example, x > y &&k !=12
 This is termed as the logical expression or a compound relational expression.
Whole expression also returns the boolean value. That is, the above expression
will return true when the both the conditions (x > y) and (k != 12) are true. If any
one of these conditions is false the expression will return false.
 Consider another example, m == 99 || j <= 10
 This logical expression involves the logical OR operator. The expression will return
true only when any one of the conditions (m==99 and j<=10) is true. If both
conditions are false, the whole expression will also return false. That is, in order to
evaluate the expression to true, any one of the condition must be true.
Java Programming 1 - 37 Introduction to Java

 The third operator is known as logical NOT operator. This is the only unary logical
operator and generally used to negate the condition. If we write this operator in
front of any other relational or logical expression, the result of the expression will
be inverted. That is, true will become false and false will become true.
For example,
x = 36 then
!(x>40) will return true
!(x==36) will return false

 Java is also having the increment and decrement operators’ i.e., ++ and – –.
 Both of these are unary operators. The operator ++ adds 1 to the operand and – –
subtracts 1 from the operand. They are only associated with the variable name,
not with the constant or the expression.
 They can be written in following from:
x++ or x—-
++x or --x
 Both forms of the ++ increment the value of variable by one i.e. x++ or ++x will
be equivalent to x = x + 1. As well as, x – – is equivalent to x = x – 1.
 When the increment or decrement operator is used before variable, it is called as
pre-increment or pre-decrement operator. And when it is used after variable, it is
called as post-increment or post-decrement operator.
 The difference is simple. That is, when these pre-increment or pre-decrement
operators are involved in the arithmetic expression, the values of respective
variables will get affected before evaluation of expression. In case of post-
increment and post-decrement operators, the value of variable will be affected
after the evaluation of expression.
For example
z = 14;
y = z++;
 Here, the value of variable y will be 14 and z will be 15, because in the second
expression, post increment operator is used. Value of variable z is assigned to y
first and then it is incremented. If we change the second expression to,
y = ++z;
 Now, both the values of y and z will be 15. Pre-increment operator does its job
first the then uses the value in the expression.
 Following table shows the use of operators.
Expression Process Example End result
Java Programming 1 - 38 Introduction to Java

A++ Add 1 to a variable after use int A = 10,B; A=11


B=A++; B=10
++
A Add 1 to a variable before use int A=10,B; A=11
B=++A; B=11
A-- Subtract 1 from a variable after use int A=10,B; A=9
B=A-- B=10
--A Subtract 1 from a variable before int A=10,B; A=9
use B=--A; B=9

 In order to manipulate the data at the bit level, the bitwise operators are provided
in Java. These operators are used for testing the bits as well as shifting them to
left or right etc. These can be applied to integer types only.
 Bitwise operator works on bits (0 or 1) and perform bit by bit operation. Assume if
x = 60; and y = 13; Now in binary format they will be as follows:
x = 0011 1100
y = 0000 1101
-------------------
x&y = 0000 1100
x|y = 0011 1101
x^y = 0011 0001
~x = 1100 0011
 The following table lists the bitwise operators: Assume integer variable A holds 60
and variable B holds 13 then:
Operator Description Example
& (Binary AND Operator) It copies a bit to the result (A & B) will give 12 which
if it exists in both is 0000 1100
operands.
| (Binary OR Operator) It copies a bit if it exists in (A | B) will give 61 which
either operand. is 0011 1101
^ (Binary XOR Operator) It copies the bit if it is set (A ^ B) will give 49 which
in one operand but not is 0011 0001
both.
~ (Binary Ones This is unary and has the (~A ) will give -61 which is
Complement Operator) effect of 'flipping' bits. 1100 0011 in 2's
complement form due to
Java Programming 1 - 39 Introduction to Java

a signed binary number.


<< (Binary Left Shift The left operands value is A << 2 will give 240
Operator) moved left by the number which is 1111 0000
of bits specified by the
right operand.
>> (Binary Right Shift The left operands value is A >> 2 will give 15 which
Operator) moved right by the is 1111
number of bits specified
by the right operand.
>>> (Shift right zero fill The left operands value is A >>>2 will give 15
operator) moved right by the which is 0000 1111
number of bits specified
by the right operand and
shifted values are filled up
with zeros.
 All these operators except one’s complement operator are binary operators.
These perform the given bitwise operation on the operands. Accordingly, the
result is obtained. Shift operators shift the binary equivalent bits of the operand
to respective left or right position. >>> operator is one of the special type of
bitwise operator which is generally used for the negative values which will be
shifted to right by filling the zeroes to leftmost positions.

 Conditional operator is also known as the ternary 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
 Example:
public class TernaryDemo
{
public static void main(String[] args)
{
int a, b;
a = 50;
b = a < 0 ? -a: a; // get absolute value of a
Java Programming 1 - 40 Introduction to Java

[Link]("The Absolute value of "+ a + " is " + b);


a = -10;
b = a < 0 ? -a: a; // get absolute value of a
[Link]("The Absolute value of "+ a + " is " + b);
}
}
Output:
The Absolute value of 50 is 50
The Absolute value of -10 is 10

 The instanceof operator compares an object to a specified type.


 The instanceof operator is used to test whether the object is an instance of the
specified type (class or subclass or interface).
 The instanceof operator is also known as type comparison operator because it
compares the instance with type. It returns either true or false. If we apply the
instanceof operator with any variable that have null value, it returns false.
 instanceof operator is wriiten as:
(Object reference variable) instanceof (class/interface type)
 If the object referred by the variable on the left side of the operator passes the IS-
A check for the class/interface type on the right side, then the result will be true.
 Example:
public class Test {
public static void main(String args[]){
String name = "James";
// following will return true since name is type of String
boolean result = name instanceof String;
[Link]( result );
}
}
Output:
true
 This operator will still return true if the object being compared is the assignment
compatible with the type on the right.

 Use the dot operator to access class members:


1. Methods: Name is followed by parentheses containing arguments
Java Programming 1 - 41 Introduction to Java

2. Fields: Not followed by parentheses


 We can now analyse the following statement (See Fig. 1.18).

Fig. 1.18
Operator precedence and associativity
 Two operator characteristics determine how operands group with operators:
precedence and associativity.
 Precedence is the priority for grouping different types of operators with their
operands. Operator Precedence is an evaluation order in which the operators
within an expression are evaluated on the priority bases.
 Associativity is the left-to-right or right-to-left order for grouping operands to
operators that have the same precedence.
 Operator precedence determines the grouping of terms in an expression. This
affects how an expression is evaluated. Certain operators have higher precedence
than others; for example, the multiplication operator has higher precedence than
the addition operator.
 For example, x = 7 + 3 * 2; here x is assigned 13, not 20 because operator
* has higher precedence than +, so it first gets multiplied with 3*2 and then adds
into 7.
 Here, operators with the highest precedence appear at the top of the table, those
with the lowest appear at the bottom. Within an expression, higher precedence
operators will be evaluated first.
Category Operator Associativity
Postfix () [] . (dot operator) Left to right
Unary ++ - - ! ~ Right to left
Multiplicative */% Left to right
Additive +- Left to right
Shift >> >>> << Left to right
Java Programming 1 - 42 Introduction to Java

Relational > >= < <= Left to right


Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %= >>= <<= &= ^= |= Right to left
Comma , Left to right

 Expressions are evaluated using the assignment statement


Syntax: variable=expression
 In java the expressions are evaluated based on some rules known as operator
precedence and associativity. Normally the expressions to the right of the
assignment operator are evaluated from left to right based on the operator
precendence and the result is assigned to the variable on the left hand side.
 The following are the rules that are to be followed when evaluating an arithmetic
expression:
o () Any thing within the parenthesis is evaluated first irrespective of the
precedence.
o ++, -- The pre_increment and decrement calculations are performed next
o *, /, % Do all multiplications, divisions and remainders from left to right.
o +, - Do additions and subtractions from left to right.
o = Assign the right-hand side to the left-hand side
 Example:
for(int i=0;i&lt;7;i++)
{
[Link]("i="+i);
}

 When two data types are compatible and destination type is larger than the
source data type, Java performs automatic conversion for us. This is called
‘Widening conversion’. For example, int data type can always store byte value as
it is large enough to occupy byte values.
Java Programming 1 - 43 Introduction to Java

 Every expression written in the Java programming language has a type that can
be deduced from the structure of the expression and the types of the literals,
variables, and methods mentioned in the expression.
 It is possible, however, to write an expression in a context where the type of the
expression is not appropriate. In some cases, this leads to an error at compile
time. In other cases, the context may be able to accept a type that is related to
the type of the expression; as a convenience, rather than requiring the
programmer to indicate a type conversion explicitly, the Java programming
language performs an implicit conversion from the type of the expression to a
type acceptable for its surrounding context.
 Java’s automatic type conversion also occurs in the case of expressions.
Expression is a statement which consists of operands and operators, used to
compute a result.
Example: d = a + b * c;
 In the above expression, a,b,c and d are operands and +, *, = are operators.
 Java allows mixing of constants and variables of different types in an expression,
but during assessment it hold to very strict rules of type conversion.
 When computer consider operand and operator and if operands are different
types then type is automatically convert in higher type.
 Following table shows the automatic type conversion.
char byte short int long float double
Char int int int int long float double
Byte int int int int long float double
Short int int int int long float double
Int int int int int long float double
Long long long long long long float double
Float float float float float float float double
double double double double double double double double
 If we want to convert two types which are incompatible or if the size of
destination type is less than the size of source type, then we must do the
conversion explicitly. This process is also called as “type casting”.
 For example if we want to convert a int value to byte, java cannot do this
automatically as the size of int is 32 and size of byte is only 8. So, we must
explicitly cast an int to byte. This is also known as “narrowing conversion”
 Syntax for type casting is:
(destination type) value;
Java Programming 1 - 44 Introduction to Java

Program 1.3: Program for type conversion.


class Conversion {
public static void main(String args[]) {
byte b;
int i = 257;
double d = 323.142;
[Link]("\nConversion of int to byte.");
b = (byte) i;
[Link]("i and b " + i + " " + b);
[Link]("\nConversion of double to int.");
i = (int) d;
[Link]("d and i " + d + " " + i);
[Link]("\nConversion of double to byte.");
b = (byte) d;
[Link]("d and b " + d + " " + b);
}
}
Output:
Conversion of int to byte.
i and b 257 1
Conversion of double to int.

[Link] min()
 The method gives the smaller of the two arguments. The argument can be int,
float, long, double.
Syntax:
double min(double arg1, double arg2)
float min(float arg1, float arg2)
int min(int arg1, int arg2)
long min(long arg1, long arg2)
Example:
public class Test{
public static void main(String args[]){
[Link]([Link](12.123, 12.456));
[Link]([Link](23.12, 23.0));
}
Java Programming 1 - 45 Introduction to Java

}
Output:
12.123
23.0
[Link] max()
 The method gives the maximum of the two arguments. The argument can be int,
float, long, double.
Syntax:
double max(double arg1, double arg2)
float max(float arg1, float arg2)
int max(int arg1, int arg2)
long max(long arg1, long arg2)
Example:
public class Test{
public static void main(String args[]){
[Link]([Link](12.123, 12.456));
[Link]([Link](23.12, 23.0));
}
}
Output:
12.456
23.12
[Link] sqrt()
 The method returns the square root of the argument.
Syntax:
double sqrt(double d)
Example:
public class Test{
public static void main(String args[]){
double x = 11.635;
double y = 2.76;
[Link]("The value of e is %.4f%n", Math.E);
[Link]("sqrt(%.3f) is %.3f%n", x, [Link](x));
}
}
Output:
Java Programming 1 - 46 Introduction to Java

The value of e is 2.7183


sqrt(11.635) is 3.411
[Link] pow()
 The method returns the value of the first argument raised to the power of the
second argument.
Syntax:
double pow(double base, double exponent)
Example:
public class Test{
public static void main(String args[]){
double x = 11.635;
double y = 2.76;
[Link]("The value of e is %.4f%n", Math.E);
[Link]("pow(%.3f, %.3f) is %.3f%n",
x, y, [Link](x, y));
}
}
Output:
The value of e is 2.7183
pow(11.635, 2.760) is 874.008
[Link] exp()
 The method returns the base of the natural logarithms, e, to the power of the
argument.
Syntax:
double exp(double d)
Here, is a primitive data types
Example:
public class Test{
public static void main(String args[]){
double x = 11.635;
double y = 2.76;
[Link]("The value of e is %.4f%n", Math.E);
[Link]("exp(%.3f) is %.3f%n", x, [Link](x));
}
}
[Link] round()
Java Programming 1 - 47 Introduction to Java

 The method round returns the closest long or int, as given by the methods return
type.
Syntax: This method has following variants:
long round(double d)
int round(float f)
Here, d is a double or float primitive data type and f is a float primitive data type
Example:
public class Test{
public static void main(String args[]){
double d = 100.675;
double e = 100.500;
float f = 100;
float g = 90f;
[Link]([Link](d));
[Link]([Link](e));
[Link]([Link](f));
[Link]([Link](g));
}
}
Output:
101
101
100
90
[Link] abs()
 The method gives the absolute value of the argument. The argument can be int,
float, long, double, short, byte.
Syntax: All the variant of this method are given below:
double abs(double d)
float abs(float f)
int abs(int i)
long abs(long lng)
Example:
public class Test{
public static void main(String args[]){
Integer a = -8;
Java Programming 1 - 48 Introduction to Java

double d = -100;
float f = -90;
[Link]([Link](a));
[Link]([Link](d));
[Link]([Link](f));
}
}
Output:
8
100.0
90.0

1.4 EXPRESSIONS
 Expressions in Java are used to fetch, compute, and store values.
 An expression is a syntactic construction that has a value. Expressions are formed
by combining variables, constants, and method returned values using operators.
 An expression is a construct made up of variables, operators, and method
invocations, which are constructed according to the syntax of the language, that
evaluates to a single value.
 There are three purposes for defining an expression:
1. To compute values.
2. To assign values to variables.
3. To control the flow of execution.
 Example:
int sum = 0; mark[0] = 100;
[Link]("Element 1 at index 0: " + mark[0]);
int result = 1 + 2; // result is now 3
if(value1 == value2) [Link]("value1 == value2");
 The data type of the value returned by an expression depends on the elements
used in the expression. The expression sum=0 returns an int because the
assignment operator returns a value of the same data type as its left-hand
operand; in this case, cadence is an int. As you can see from the other
expressions, an expression can return other types of values as well, such as
boolean or String.

1.5 DECISION MAKING AND LOOPING


 In programming, a statement is an instruction to do something. It controls the
sequence of execution of a program.
Java Programming 1 - 49 Introduction to Java

 It is the ability to adjust (or to control) the way that program progresses. By
adjusting the direction of flow programs can become dynamic. Java support
following types of statements:
1. Selection Statement: Selection statement is also called as Decision making
statements because it provides the decision making capabilities to the
statements. These statements allow you to control the flow of your program’s
execution based upon conditions known only during run time. Java supports
two selection statements: if and switch.
2. Iteration Statement: The process of repeatedly executing a statements and
is called as looping. The statements may be executed multiple times (from
zero to infinite number). A loop repeatedly executes the same set of
instructions until a termination condition is met. Looping is also called as
iterations. In Iteration statement, there are three types of operation: for loop,
while loop and do-while loop
3. Jumps in statement: These statements transfer control to another part of
your program. Statements or loops perform a set of operations continually
until the control variable will not satisfy the condition. But if we want to break
the loop when condition will satisfy then Java give a permission to jump from
one statement to end of loop or beginning of loop as well as jump out of a
loop. “break” keyword use for exiting from loop and “continue” keyword use
for continuing the loop.

 A selection statement is a control statement that allows choosing between two or


more execution paths in a program.
 Java supports different control flow and branching statements given below.
1. if statement
2. if-else statement
3. switch-case statement
4. Conditional operator statement
[Link] 'if' Statement
 The if statement is Java’s conditional branch statement.
 The “if statement” is the simplest one in decision statements.
 It can be used to route program execution through two different paths. If
condition causes "one thing" to occur when a specified condition is met.
 The one thing may be a single statement or a block of statements in curly braces.
The remainder of the code (following the if and the statement or block it owns) is
then executed regardless of the result of the condition.
 The “if statement” is used to manage the flow of execution of statements.
Java Programming 1 - 50 Introduction to Java

Syntax:
if (condition)
{
statement;
}
OR
if (condition)
{
statement1;
statement2;
statement3;
}
 This allows the compiler to evaluate the condition first, which is the boolean
expression. Then depending upon the value of the condition (true or false), the
related statements are executed.
 Fig. 1.19 shows flow diagram of if statement.

Fig. 1.19
 The condition generally involves relational and logical operators which return
boolean value.
 Some examples of an ‘if’ statements are:
1. if(number < 0)
[Link](“The number is negative”);
2. if(ch> ‘A’ &&ch< ‘Z’)
[Link](“It is upper case letter”);
Java Programming 1 - 51 Introduction to Java

3. if(sell_price>cost_price)
[Link](“You made profit”);
Program 1.4: Program for simple if statement.
public class Test {
public static void main(String args[]){
int x = 10;
if( x < 20 ){
[Link]("This is if statement");
}
}
}
Output:
This is if statement

Program 1.5: Program to check whether the number is positive or negative.


import [Link].*;
class NumTest
{
public static void main (String[] args) throws IOException
{
int Result=11;
[Link]("Number is"+Result);
if ( Result < 0 )
{
[Link]("The number "+ Result +" is negative");
}
else
{
[Link]("The number "+ Result +" is positive");
}
[Link]("------- * ---------");
}
}
Output:
Number is 11
The number 11 is positive
Java Programming 1 - 52 Introduction to Java

------- * ---------
Nested ‘if’ statement:
 Nesting of the statements is one of the useful features of the all the programming
languages.
 Nesting means we can write one ‘if’ statement in another ‘if’ statement.
 It takes the following forms or syntax:
if(condition1)
if(condition2)
statement;
OR
if(condition1)
if(condition2)
{
statement1;
statement2;
statement3;
}
OR
if(condition1)
{
if(condition2)
{
statement1;
statement2;
statement3;
}
statement4;
}
 In all the above cases, if both the conditions (condition1 and condition2) are true
then only the respective statements are executed.
Program 1.6: Program for nested if statement.
classNestedIf
{
public static void main(String args[])
{
int number = -52;
Java Programming 1 - 53 Introduction to Java

[Link]("Number is: "+number);


if(number > 0) //1
if(number%2 == 0)
[Link]("It is positive & even");
if(number < 0) //2
if(number%2 == 0)
[Link]("It is negative & even");
if(number > 0) //3
if(number%2 != 0)
[Link]("It is positive & odd");
if(number < 0) //4
if(number%2 != 0)
[Link]("It is negative & odd");
}
}

Program 1.7: Program to find greater number.


public class Main{
public static void main(String args[]){
int a = 10;
int b = 20;
if(a>b){
[Link]("a is greater than b");
}
if(b<a){
[Link]("b is less than a");
}
}
}
Output:
a is greater than b
b is less than a
[Link] if-else Statements
 It is basically extension of if statement.
 The if ... else Statement does "one thing" if a condition is true, and a different
thing if it is false.
Java Programming 1 - 54 Introduction to Java

 It is never the case that both things are done. The "one thing" may be a single
statement or a block of statements in curly braces.
 A statement executed in a branch may be any statement, including another if or
if ... else statement.
Syntax:
if(boolean-expression)
{
if-code;
}
else
{
else-code;
}
rest-of-code;
 Fig. 1.20 shows flowchart for if-else statement.

Fig. 1.20
 If the boolean-expression is true if-code gets executed. If boolean-expression is
false else-code gets executed.
 In this decision making statements generally either of the block gets executed
whether its if-code or else-code, after either execution rest-code gets executed.
Java Programming 1 - 55 Introduction to Java

Program 1.8: Program for if-else statement.


public class Test {
public static void main(String args[]){
int x = 30;
if( x < 20 ){
[Link]("This is if statement");
}else{
[Link]("This is else statement");
}
}
}
Output:
This is else statement.

[Link] Nested if-else Statements


 The nested if-else statements are used where we want to make series of decision
making. Thus one if-else is nested within another if-else. Therefore nested if-else
give us to make a decision within a decision already taken.
Syntax:
if(boolean-expression 1)
{
if(boolean-expression 2)
{
statement 1;
}
else
{
statement 2;
}
}
else
{
statement 3;
}
rest-of-code;
 Fig. 1.21 flowchart for nested if-else statement.
Java Programming 1 - 56 Introduction to Java

Fig. 1.21: Nested if-else statement flowchart


 Lets analyze about syntax and flowchart. Nested if-else syntax is very much.
Generally if you look at the flowchart you will find that there are two if-else
statements. You can nest them to n number. For the sake of simplicity we have
taken only two if-else. Logic implemented in above syntax is like if boolean-
expression 1 is false, statement - 3 gets executed and then program flows to rest
of code.
 But if the boolean-expression 1 is true the controls flow to another expression
called as boolean-expression 2. Then the same code follows if boolean-expression
2 is evaluated as false statement - 2 gets executed and then to rest of the code.
But if boolean-expression 2 is true, statement - 1 is executed and then follows to
rest of code.
[Link] if-else Ladder
 The if-else ladder is another way of putting the ‘if’s together when multi-path
decisions are involved.
 A multi-path decision is a chain of ‘if’s in which statements are associated with
each ‘else’ is an ‘if’.
 This construct is known as if-else ladder.
if(condition1)
statement1;
else
Java Programming 1 - 57 Introduction to Java

if(condition2)
statement2;
else
if(condition3)
statement3;
else
statement4;
-
-
-
 The conditions are evaluated from top of the ladder to the bottom. The very
familiar example of this construct is to find the grade of the student according to
marks.
 Fig. 1.22 shows else-if ladder statements. Else-if ladder is generally used when we
want to take multiple decision. These multiple decision are in chains of if followed
by else-if statements till n number.

Fig. 1.22: Else-if ladder statement flow chart


Java Programming 1 - 58 Introduction to Java

 Lets analyze the syntax and flowchart of Else-if ladder. The multiple decision
making starts from top and flows towards bottom. The ladder works very simple
and straight way. Whenever true condition is evaluated the statement below if
gets executed and rest-of-code execution follows and whenever false condition is
evaluated control flows towards next condition till default statement gets
executed followed by rest-of-code.
 For example examination board is giving grade according to marks as below:
Marks Grade
Above 75 Distinction
60 to 74 First class
50 to 59 Second class
40 to 49 Pass class
Below 40 Fail
 This can be done by applying the if-else ladder as,
classIfElseLadder
{
public static void main(String args[])
{
float marks = 62.12f;
[Link]("Marks: "+marks);
[Link]("Your grade is: ");
if(marks >= 75)
[Link]("Distinction");
else
if(marks >= 60)
[Link]("First class");
else
if(marks >= 50)
[Link]("Second class");
else
if(marks >= 40)
[Link]("Pass class");
else
[Link]("Fail");
}
}
Java Programming 1 - 59 Introduction to Java

[Link] The switch Statement


 Sometimes it becomes cumbersome to write lengthy programs using if and if-else
statements. To avoid this we can use switch statements in Java.
 switch is the multi-way selection statement.
 It tests the value of the variable (or expression) against the list of case values and
when match is found, a block of statements associated with that case are
executed.
Syntax:
switch(variable)
{
case value-1:
statements-1;
break;
case value-2:
statements-2;
break;
- - - - - - - - -
- - - - - - - - -
default:
default block;
}
statement-out;
 The variable written in switch brackets is either an integer or character variable
or an expression which is evaluated to an integer value. value-1, value-2… are
constants, which are also known as case labels. Each of this value is unique within
switch statement. A colon (:) is given after each case label.
 When the switch is executed, the value of the variable is successively compared
with the values value-1, value-2…. If the case is found whose value matches with
the variable then the statements in front of respective case are executed.
 The ‘break’ statement is written at the end of each case statement to signal the
end of particular case. It causes the exit from the switch statement.
 Fig. 1.23 shows flowchart for switch statement.
Java Programming 1 - 60 Introduction to Java

Fig. 1.23

Program 1.9: Program for switch statement


classNumDisplay
{
public static void main(String args[])
{
int x = 6;
[Link]("x = "+x);
[Link]("It is ");
switch(x)
{
case 1: [Link]("One");
break;
case 2: [Link]("Two");
break;
case 3: [Link]("Three");
break;
case 4: [Link]("Four");
break;
case 5: [Link]("Five");
break;
case 6: [Link]("Six");
break;
case 7: [Link]("Seven");
Java Programming 1 - 61 Introduction to Java

break;
case 8: [Link]("Eight");
break;
case 9: [Link]("Nine");
break;
case 0: [Link]("Zero");
break;
default: [Link]("No. not correct");
}
}
}

Program 1.10: Program to find odd, even, positive and negative numbers.
import [Link].*;
class Menu
{
public static void main(String args[]) throws Exception
{
int choice, num;
BufferedReaderbr = new BufferedReader(new
InputStreamReader([Link]));
[Link]("Menu....");
[Link]("1. Find positive");
[Link]("2. Odd/Even");
[Link]("Enter the choice: ");
choice = [Link]([Link]();
switch(choice)
{
case 1:
[Link]("Enter number: ");
num = [Link]([Link]();
if(num > 0)
[Link]("Positive...");
else
[Link]("Negative...");
break;
Java Programming 1 - 62 Introduction to Java

case 2:
[Link]("Enter number: ");
num = [Link]([Link]();
if(num%2 == 0)
[Link]("Even...");
else
[Link]("Odd...");
break;
default:
[Link]("Wrong choice..");
}
}
}
Output1:
Menu....
1. Find positive
2. Odd/Even
Enter the choice: 1
Enter number: -20
Negative...
Output2:
Menu....
1. Find positive
2. Odd/Even
Enter the choice: 2
Enter number: 63
Odd...

Program 1.11: Program to find day in switch statement.


public class Main{
public static void main(String args[]){
int day = 1;
switch(day){
case 0:
[Link]("Sunday");
break;
Java Programming 1 - 63 Introduction to Java

case 1:
[Link]("Monday");
break;
case 3:
[Link]("Tuesday");
break;
case 4:
[Link]("Wednesday");
break;
case 5:
[Link]("Thursday");
break;
case 6:
[Link]("Friday");
break;
case 7:
[Link]("Saturday");
break;
default:
[Link]("Invalid Day");
break;
}
}
}
Output:
Monday
[Link] Nested switch Statements
 We can use a switch as part of the statement sequence of an outer switch. This is
called nested switch. We know that each switch defines its own block of code but
case constants of outer switch have no conflicts with the inner switch's case
constants.
Syntax:
switch (value)
{
case 1:
switch (value)
Java Programming 1 - 64 Introduction to Java

{
case 1:
statement(s)
break;
.
.
case n:
statement (n)
break;
default:
statement
}
case 2:
statement(s)
break;
.
.
case n:
statement (n)
break;
default:
statement
}
 Here, value can be a variable or any constant value. Remember case 1 of outer
switch have no conflicts with case 1 of inner switch. If the value matches with
case 1 (outer switch's) then inner switch will be executed otherwise it will be
bypassed.
Program 1.12: Program for nested switch statement.
public class Main {
public static void main(String[] args) {
int i = 0;
switch (i) {
case 0:
int j = 1;
switch (j) {
case 0:
Java Programming 1 - 65 Introduction to Java

[Link]("i is 0, j is 0");
break;
case 1:
[Link]("i is 0, j is 1");
break;
default:
[Link]("nested default case!!");
}
break;
default:
[Link]("No matching case found!!");
}
}
}
[Link] Operator
 It also called as ternary operator.
 The character pair?: is a conditional operator of Java.
 The ternary operator, is a shorthand if else statement.
 It can be used to evaluate an expression and return one of two operands
depending on the result of the expression.
Syntax: Expression1 ? Expression3: Expression3
 The operator ?: works as follows:
Expression1 is evaluated if it is true then Expression3 is evaluated and becomes
the value of the conditional expression. If Expression1 is false then Expression3 is
evaluated and its value becomes the conditional expression.
Program 1.13: Program for ternary operator.
class Coptr
{
public static void main (String args[])
{
int a = 10;
int b = 30;
int c;
c=(a>b)?a:b;
[Link]("c = " +c);
c=(a<b)?a:b;
Java Programming 1 - 66 Introduction to Java

[Link]("c = " +c);


}
}
Output:
c = 30
c = 10

Program 1.14: Program to check whether number is positive or negative.


class PosNeg
{
public static void main(String args[])
{
int a=10;
int flag=(a<0)?0:1;
if(flag==1)
[Link](―Number is positive‖);
else
[Link](―Number is negative‖);
}
Write a program to check whether number is positive or negative.
class PosNeg
{
public static void main(String args[])
{
int a=10;
int flag=(a<0)?0:1;
if(flag==1)
[Link](―Number is positive‖);
else
[Link](―Number is negative‖);
}
}
Output:
Number is positive
looping
Java Programming 1 - 67 Introduction to Java

 There may be a situation when we need to execute a block of code several


number of times, and is often referred to as a loop.
 A Loop is the cycle of execution. It is what we can call repeatedly executing the
same block of code until the termination condition is met.
 These statements are used to repeat same set of instructions specified number of
times called loops.
 Java is having three different loop statements, i.e., 1. while loop, 2. do-while loop,
3. for loop
[Link] while Loop
 The while loop is entry controlled loop statement.
 While loop repeats a group of statements as long as condition is true. Once the
condition is false, the loop is terminated.
Syntax:
while (condition) statement
OR
initialization;
while (condition)
{
//body of the loop;
}
 Body of the loop may contain any number of statements. If the loop contains only
one statement then the curly braces are not required. Condition given may
contain combination of relational and logical operators as well as boolean variable
variables too.

(a) (b)
Fig. 1.23
Java Programming 1 - 68 Introduction to Java

 In Fig. 1.23 the loop continues as long as the expression evaluates to true, the
condition is evaluated before the start of each pass and it is possible that the
body of the loop never executes at all (if the condition is false the first time).
 For example, if we want to print “I Love Java” for 10 times. It can be written in
following form.
int i = 0;
while(i<10)
{
[Link](“I Love Java”);
i++;
}
Program 1.15: Program to find addition of 10 natural numbers.
classWhileAdd
{
public static void main(String args[])
{
int a = 0, sum = 0;
while(a<=10)
{
sum = sum + a;
a++; // or a = a+1;
}
[Link]("Addition is "+sum);
}
}
Output:
Addition is 55
[Link] do-while Loop
 Sometimes in the program it is desirable to execute your loop at least once. The
do-while loop can be applied in this case.
 It is post-test loop. That is, the loop is executed first and then the loop condition is
checked. The condition is written at the end of the loop.
 This is also called as exit-controlled loop.
 The syntax of do-while loop statement is,
do
{
Java Programming 1 - 69 Introduction to Java

//body of the loop;


}while(condition);
 On reaching the do statement, the body of the loop is executed first. Then the
loop condition written in ‘while’ is checked. If it is true then program control will
proceed to execute next iteration of the loop else next statements are executed.

(a) (b)
Fig. 1.24
 In above Fig. 1.24 the condition is evaluated after the end of each pass and the
body of the loop will always execute at least once, even if the condition is false
the first time
Program 1.16: Program squares of numbers.
classDoWhileSquare
{
public static void main(String args[ ])
{
intnum = 1;
do
{
[Link]("Square of ");
[Link](num+": ");
[Link](num*num);
num++;
}while(num<=10);
}
}
[Link] for Loop
Java Programming 1 - 70 Introduction to Java

 The ‘for’ loop is another entry-controlled loop, that provides a more concise loop
control structure.
 That is, initialization, condition and increment/decrement can be done in the
single loop statement as given below.
Syntax:
for(initialization; condition; increment/decrement)
{
Body of the loop;
}
 This loop control structure works as below:
1. Initialization part is executed first. Here, we can do the initialization of the
loop control variables. This statement is executed only once i.e. before the
start of execution of the loop.
2. In the second stage, the condition given is tested. If it is evaluated to true,
then body of the loop is executed. Generally, the condition is related with the
loop counter. But it is not necessary to give condition related to loop counter
only. The condition is tested for each iteration of the loop. When it becomes
false the loop gets terminated.
3. After completion of execution of the body of the loop, increment /
decrement statement is executed. Any action we can write in this
statement. Then again control gets transferred to the condition to execute the
next iteration.
 For example, consider the following segment.
for(a = 0; a < 10; a++ )
{
[Link](a);
}
 Here the loop counter ‘a’ is initialized to 0 when loop execution started. The loop
is executed for 10 numbers of times by incrementing the value of counter by 1.
Each time the value of variable ‘a’ gets printed onto the screen. When the body of
the loop contains only one statement then it is not necessary to give the curly
braces.
Java Programming 1 - 71 Introduction to Java

(a) (b)
Fig. 1.25
Control Flow of for loop in Java (See Fig. 1.25 (b):
1. The initialization statement is executed [Link] declares and initializes the
value of the "loop control variable" which acts as the counter of the for loop. It
executes only once at the beginning of the for loop.
2. The condition statement is executed next and tests the value of the loop
control variable and decides whether the body of the for loop can be
executed. It can only be a boolean expression. If the condition evaluates to
true , the body is executed otherwise the loop terminates and the statement
after the for loop is executed.
3. The body of the for loop is executed next.
4. Once the control finishes executing the last statement of the body, the control
goes to the iteration statement. It updates/modifies the value of the loop
control variable/ counter and prepares for the next iteration.
5. Then the control again enters the condition statement and checks whether the
updated control variable still satisfies the condition.
Program 1.17: Find factorial of number using for loop
import [Link].*
{
public static void main(String args[])
{
int fact = 1, num;
Java Programming 1 - 72 Introduction to Java

BufferedReaderbr = new BufferedReader(new


InputStreamReader([Link]));
[Link]("Enter number: ");
num = [Link]([Link]();
for(int i = num ;i>0; i--)
fact = fact * i;
[Link]("Factorial: "+ fact);
}
}
[Link] for each Loop
 This loop is supported from Java 5.0. Java's enhanced for loop facilitate array and
collection traversing.
 It is also referred as the loop. By providing enhanced for statement Java folks
simplified the code structure.
 For each loop is mainly used for iterate the Array, List etc.
Syntax:
for(declaration: expression)
{
//Code Here
}
Program 1.18: Program for each loop.
public class Example {
public static void main(String args[]){
List list = new ArrayList();
[Link](10);
[Link](20);
[Link](30);
[Link]("List Value = ");
for(int x: list){
[Link]( x );
[Link](",");
}
String [] names ={"abc", "xyz", "test", "example"};
[Link]("String Array value = ");
for( String name: names ) {
[Link]( name );
[Link](",");
Java Programming 1 - 73 Introduction to Java

}
}
}
Output:
List Value = 10,20,30
String Array value = abc,xyz,test,example
[Link] Nested loop
 Like all other programming languages, Java allows loops to be nested. That is, one
loop may be inside another.
 The placing of one loop inside the body of another loop is called nesting. When
you "nest" two loops, the outer loop takes control of the number of complete
repetitions of the inner loop. A nested loop is a loop that lies inside another loop.
 It can help you to scan and print multi dimensional array as well as in so many
other application or program.
1. Nested for loop:
 The nested for loop is the type of looping construct when we use for loop inside
for loop. All the statements which has to be executed written in the for block.
 We can use for loop inside another for loop is called nested for loop.
Syntax:
for(initialization; test; increment)
{
statements;
for(initialization; test; increment)
{
statements;
|
|
|
for(initialization; test; increment)
{
statements;
}
}
}
Program 1.19: Program to display triangle of * using nested for loop
class NestedForLoopDemo
Java Programming 1 - 74 Introduction to Java

{
public static void main(String args[])
{
for(int i = 1; i <=5 ; i++)
{
for(int j = 1; j <= i; j++)
{
[Link]("* ");
}
[Link]("");
}
}
}
Output:
*
* *
* * *
* * * *
* * * * *

Program 1.20: Program for nested for loop.


public class ForLoop
{
public static void main(String[] args)
{
for(int i = 1;i <= 5;i++)
{
for(int j = 1;j <= i;j++)
{
[Link](i);
}
[Link]();
}
}
}
Output:
Java Programming 1 - 75 Introduction to Java

1
22
333
4444
55555
2. Nested while Loop:
 One while loop can be nested with other while loop. We can use while loop inside
another for loop is called nested while loop.
Syntax:
While(expression)
{
statements;
|
|
|
While(expression)
{
statements;
}
}
Program 1.21: Program to print tables.
class NestedWhileLoop
{
public static void main(String args[])
{
int i=1, j=1;
[Link]("Tables");

while(i <= 2) // change to 2 to 10 or 20 as many tables user want


{
while(j <= 10)
{
[Link](i + " * " + j + " = " + (i*j));
j++;
}
i++;
Java Programming 1 - 76 Introduction to Java

[Link]("");
[Link]("");
}
}
}
Output:
Tables
1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
1 * 4 = 4
1 * 5 = 5
1 * 6 = 6
1 * 7 = 7
1 * 8 = 8
1 * 9 = 9
1 * 10 = 10
3. Nested do while loop:
 We can use do while loop inside another for loop is called nested do while loop.
 The syntax for a nested do...while loop as follows:
do
{
statement(s); // you can put more statements.
do
{
statement(s);
}
while( condition );
}while( condition );
Program 1.22: Program to print triangle of numbers
class NestedDOWhileLoop
{
public static void main(String args[])
{
int i=1, j=1;
do
Java Programming 1 - 77 Introduction to Java

{
k = 3;
do
{
[Link](" ");
k--;
}while(k>=i);
j = 1;
do
{
[Link](i + " ");
j++:
}while(j<=i);
[Link]("");
i++;
}while(i<=5);
}
}
Output:
1
2 2
3 3 3

Program 1.23: Program to print * pattern.


class Nested
{
public static void main(String args[])
{
int i, j;
for(i=0; i<10; i++)
{
for(j=i; j<10; j++)
{
[Link](".");
}
[Link]();
Java Programming 1 - 78 Introduction to Java

}
}
}
Output:
..........
.........
........
.......
......
.....
....
...
..
.

[Link] Labeled Loops


 Both break and continue can have an optional label that tells Java where to
resume execution of the program. Without a label, break jumps outside the
nearest loop to an enclosing loop or to the next statement outside the loop. The
continue keyword restarts the loop it is enclosed within.
 Using break and continue with a label enables you to use break to go to a point
outside a nested loop or to use continue to go to a loop outside the current loop.
 To use a labeled loop, add the label before the initial part of the loop, with a colon
between the label and the loop. Then, when you use break or continue, add the
name of the label after the keyword itself.
Program 1.24: Program for labeled for loop.
public class LabeledFor {
public static void main(String[] args) {
int i = 0;
outer: // Can't have statements here
for(; true ;) { // infinite loop
inner: // Can't have statements here
for(; i < 10; i++) {
[Link]("i = " + i);
if(i == 2) {
[Link]("continue");
continue;
Java Programming 1 - 79 Introduction to Java

}
if(i == 3) {
[Link]("break");
i++; // Otherwise i never
// gets incremented.
break;
}
if(i == 7) {
[Link]("continue outer");
i++; // Otherwise i never
// gets incremented.
continue outer;
}
if(i == 8) {
[Link]("break outer");
break outer;
}
for(int k = 0; k < 5; k++) {
if(k == 3) {
[Link]("continue inner");
continue inner;
}
}
}
}
// Can't break or continue to labels here
}
}

 Sometimes we use jumping statements in Java. Using jumping statements like


break and continue it is easier to jump out of loops to control other areas of
program flow.
 Java supports three jump statements: break, continue, and return.
[Link] Break Statements
 This statement is used to jump out of a loop. break statement is used to
terminate the execution of looping statement.
Java Programming 1 - 80 Introduction to Java

 break statement transfer the control unconditionally to the end/out of the looping
statement.
 break statement should be used with looping statement and switch statement.
 The break statement is a branching statement that contains two forms: labeled
and unlabeled.
Syntax:
break; // breaks the innermost loop or switch statement.
break label; // breaks the outermost loop in a series of nested
loops.
Program 1.25: Program for break to a label.
class break3
{
public static void main (String args[])
{
boolean t=true;
a:
{
b:
{
c:
{
[Link]("Before the break");
if(t)
break b;
[Link]("This will not execute");
}
[Link]("This will not execute");
}
[Link]("This is after b");
}
}
}
Output:
Before the break
This is after b
[Link] Continue statements
Java Programming 1 - 81 Introduction to Java

 This is a branching statement that are used in the looping statements (while, do-
while and for) to skip the current iteration of the loop and resume the next
iteration.
 This statement is used only within looping statements. When the continue
statement is encountered, the next iteration starts. The remaining statements in
the loop are skipped. The execution starts from the top of loop again.
 Continue statement is used to skip the execution of looping statement and
continue with the execution of looping statement. Continue statement can be
used with looping statement only.
 Continue statement transfers control unconditionally to the beginning of the
looping statement.
Syntax: continue;
Program 1.26: Program for continue statement.
lass continue1
{
public static void main(String args[])
{
for (int i=1; i<1=0; i++)
{
if (i%2 == 0)
continue;
[Link]("\n" + i);
}
}
}
Output:
1
3
5
7
9
[Link] return Statements:
 It is a special branching statement that transfers the control to the caller of the
method.
 This statement is used to return a value to the caller method and terminates
execution of method.
 This has two forms: one that returns a value and the other that can not return.
Java Programming 1 - 82 Introduction to Java

 The returned value type must match the return type of method.
Syntax:
return;
OR
return values;
OR
return; //This returns nothing. So this can be used when
method is declared with void return type.
OR
return expression; //It returns the value evaluated from the
expression.
Program 1.26: Program for return statement.
class Return1
{
public static void main(String args[])
{
boolean t = true;
[Link]("Before the return.");
if(t)
return; // return to caller
[Link]("This won't execute.");
}
}
Output:
Before the return.
Programs:
1. Program of factorial number.
class Operation{
static int fact(int number){
int f=1;
for(int i=1;i<=number;i++){
f=f*i;
}
return f;
}
public static void main(String args[]){
Java Programming 1 - 83 Introduction to Java

int result=fact(5);
[Link]("Factorial of 5="+result);
}
}
2. Program to find armstrong number or not.
class ArmStrong{
public static void main(String...args)
{
int n=153,c=0,a,d;
d=n;
while(n>0)
{
a=n%10;
n=n/10;
c=c+(a*a*a);
}
if(d==c)
[Link]("armstrong number");
else
[Link]("it is not an armstrong number");
}
}
3. Floyd's triangle
class FloydTriangle
{
public static void main(String args[])
{
int n, num = 1, c, d;
Scanner in = new Scanner([Link]);
[Link]("Enter the number of rows of floyd's triangle
you want");
n = [Link]();
[Link]("Floyd's triangle:-");
for ( c = 1 ; c <= n ; c++ )
{
for ( d = 1 ; d <= c ; d++ )
Java Programming 1 - 84 Introduction to Java

{
[Link](num+" ");
num++;
}
[Link]();
}
}
}
Output:
Enter the number of rows of floyd's triangle you want
5
Floyd's triangle:
1
2 3
4 5 6
7 8 9 10
11 12 13 14 15
4. Program of swapping two numbers without using third variable.
class SwapTwoNumbers{
public static void main(String args[]){
int a=40,b=5;
a=a*b;
b=a/b;
a=a/b;
[Link]("a= "+a);
[Link]("b= "+b);
}
}
5. Program to find odd or even
class OddOrEven
{
public static void main(String args[])
{
int x;
[Link]("Enter an integer to check if it is odd or
even ");
Java Programming 1 - 85 Introduction to Java

Scanner in = new Scanner([Link]);


x = [Link]();

if ( x % 2 == 0 )
[Link]("You entered an even number.");
else
[Link]("You entered an odd number.");
}
}
6. Program to convert Fahrenheit to Celsius.
import [Link].*;
class FahrenheitToCelsius {
public static void main(String[] args) {
float temperatue;
Scanner in = new Scanner([Link]);
[Link]("Enter temperatue in Fahrenheit");
temperatue = [Link]();
temperatue = (temperatue - 32)*5/9;
[Link]("Temperatue in Celsius = " + temperatue);
}
}
7. Program print prime numbers
import [Link].*;
class PrimeNumbers
{
public static void main(String args[])
{
int n, status = 1, num = 3;
Scanner in = new Scanner([Link]);
[Link]("Enter the number of prime numbers you
want");
n = [Link]();
if (n >= 1)
{
[Link]("First "+n+" prime numbers are:-");
[Link](2);
Java Programming 1 - 86 Introduction to Java

}
for ( int count = 2 ; count <=n ; )
{
for ( int j = 2 ; j <= [Link](num) ; j++ )
{
if ( num%j == 0 )
{
status = 0;
break;
}
}
if ( status != 0 )
{
[Link](num);
count++;
}
status = 1;
num++;
}
}
}
Output:
Enter the number of prime numbers you want
10
First 10 prime numbers are:
2
3
5
7
11
13
17
19
23
29
8. Program to reverse number
Java Programming 1 - 87 Introduction to Java

class ReverseNumber
{
public static void main(String args[])
{
int n, reverse = 0;
[Link]("Enter the number to reverse");
Scanner in = new Scanner([Link]);
n = [Link]();
while( n != 0 )
{
reverse = reverse * 10;
reverse = reverse + n%10;
n = n/10;
}
[Link]("Reverse of entered number is "+reverse);
}
}
Output:
Enter the number to reverse
12345
Reverse of entered number is 54321
9. Program to find area of circle.
public class CircArea {
//void main
public static void main (String[] args)
{
//declare float
float area,r;
//print message
[Link]("Enter Radius:");
//Take input
Scanner input = new Scanner([Link]);
r = [Link]();
//calculate
area = 3.142f*r*r;
//print the area
Java Programming 1 - 88 Introduction to Java

[Link]("Area = "+area);
}
}
Output
Enter Radius:
2
Area = 12.568
[Link] to find Area of Rectangle.
public class RectArea {
//void main
public static void main (String[] args)
{
//declare int
int area,a,b;
//print message
[Link]("Enter length and breadth of Rectangle:");
//Take input
Scanner input = new Scanner([Link]);
a = [Link]();
b = [Link]();
//calculate
area = a*b;
//print the area
[Link]("Area = "+area);
}
}
Output:
Enter length and breadth of Rectangle:
4
8
Area = 32
[Link] to find average of n numbers.
public class Average
{
public static void main(String[] args)
{
Java Programming 1 - 89 Introduction to Java

int n,num,sum=0, i;
Scanner input =new Scanner([Link]);
[Link]("Enter How Many Numbers: ");//input
n =[Link](); //read total numbers
[Link]("Enter the Numbers:");
for(i=1;i<=n; i++)
{
num=[Link](); //input number
sum += num;
}
double average=(double)sum/n;
[Link]("Average of " + n + " Numbers =
" +average);
}
}
Output:
Enter How Many Numbers : 5
Enter the Numbers : 5 10 15 20 30
Average of 5 Numbers = 16.0
[Link] vowel or not example.
public class VowelorNot
{
public static void main(String[] args)
{
char ch='z';
switch(ch)
{
case 'a': case 'A':
case 'e': case 'E':
case 'i': case 'I':
case 'o': case 'O':
case 'u': case 'U':
[Link]( ch + " is Vowel");
break;
default:
[Link]( ch + " is not Vowel");
Java Programming 1 - 90 Introduction to Java

}
}
}
Output:
z is not Vowel
13. Perfect Number Program in Java
class PerfectNumber
{
public static void main(String args[])
{
Scanner sl=new Scanner([Link]);
[Link]("Enter A Number");
int num=[Link]();
int b=1, s=0;
while(b<num )
{
if(num%b == 0)
{
s += b;
}
b++;
}
if(s == num)
{
[Link](num+" is a perfect number");
}
else
{
[Link](num+" is not a perfect number");
}
}
}
Output:
Enter A number
6
6 is a perfect number
Java Programming 1 - 91 Introduction to Java

[Link] nested for loop examples


public class pyramid
{
public static void main(String [] args)
{
int n,i,j;
//create scanner object to obtain input from keyboard
Scanner input =new Scanner([Link]);
[Link]("Enter How Many Lines:"); // input
n =[Link](); //Read number
for(i=1 ; i<=n ; i++ )
{
for( j=1; j<=i ; j++)
{
[Link](i + " ");
}
[Link]("\n");
}
}
}
Output:
Enter How Many Lines :10
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
6 6 6 6 6 6
7 7 7 7 7 7 7
8 8 8 8 8 8 8 8
9 9 9 9 9 9 9 9 9
10 10 10 10 10 10 10 10 10 10
15. Program to sum of first n natural numbers in java.
public class SumNatural
{
public static void main(String[] args)
Java Programming 1 - 92 Introduction to Java

{
int n,i=1,sum=0;
Scanner input=new Scanner([Link]);
[Link]("Enter Number:");
n=[Link]();
do
{
sum=sum+i;
i +=1;
} while(i<=n);
[Link]("Sum of First " + n + " Numbers = "+sum);
}
}
Output:
Enter Number :10
Sun of First 10 Numbers = 55
16. Program to calculate the sum of only the positive numbers
public class SumPositiveNumbers
{
public static void main(String[] ars)
{
int num,sum=0;
Scanner input = new Scanner([Link]);
[Link]("Enter Numbers(Negative Number to Quit):");
while(true)
{
num=[Link](); //Read number
if(num<0)
break;
sum +=num;
}
[Link]( "Sum is: " +sum);
}
}
Output:
Enter Numbers (Negative Number to Quit) :15 20 25 30 – 1
Java Programming 1 - 93 Introduction to Java

17. Program to print all the prime numbers up to 100


class PrimeNumbers100
{
public static void main(String args[] )
{
int i,j,x,m;
[Link]("Prime Numbers upto 100 are\n");
[Link]("2"+ " ");
[Link]("3"+ " ");
for(i=4;i<=100;i++)
{
x=0;
for(j=2;j<=i-1;j++)
{
m=i%j;
if(m==0)
{
x=1;
break;
}
}
if(x==0)
{
[Link](i + " ");
}
}
}
}
Output:
Prime Numbers upto 100 are:
2 3 5 6 11 13 17 19 23 29 31 37 41 43 53 59 61 71 73 79 83 89 97

Important Points
 Java was developed by James Gosling, Patrick Naughton, Chris Warth, Ed Frank and Mike
Sheridan at Sun Microsystems in 1991.
 The Java programming language is usually mentioned in the context of the World Wide Web
(WWW) and browsers that are capable of running programs called applets.
Java Programming 1 - 94 Introduction to Java

 Java applications are standalone programs that do not require a Web browser to execute.
 The Java Development Kit (JDK) from Sun Microsystems consists of an extensive library of
java classes called packages.
 JAR is used to create archives of .class file by compression.
 The javap command disassembles a class file.
 AppletViewer tool is used to run the applet on the console.
 The Java Virtual Machine Specification provides the hardware platform specifications to
which all Java technology code is compiled.
 The output of the Java program is not executable code like C and C++, rather it is a
ByteCode.
 One obvious advantage is a runtime environment that provides platform independence.
 An object is a software bundle of related state and behavior. Software objects are often used
to model the real-world objects that you find in everyday life.
 A software blueprint for objects is called a class.
 Abstraction is a “mental process”, it means we visualize the things according to our use
without going in complexities associated with it.
 Encapsulation is the mechanism that binds together code and the data it manipulates and
keeps both safe from outside interference and misuse.
 Inheritance is the process by which one object acquires the properties of another object.
 Polymorphism means more than one form.
 Dynamic binding also known as Late binding.
 Keywords are reserved words of the language.
 An identifier is a word used by a programmer to name a variable, method (function), class or
label.
 Constant in Java can be declared by using the keyword final.
 A variable represents a memory location that can store a value.
 The scope of a variable is the part of the program over which the variable name can be
referenced.
 Variable scope refers to the accessibility of a variable.
 Instance and class variables are declared inside a class.
 The process of converting one data type to another is called casting.
 Java does the conversion of the assigned value automatically. This approach is known as
automatic type conversion.
 Operators are special symbols used for mathematical functions, some type of assignment
statements, logical comparisons and bitwise programming.
 Unary operators are the operators which operates on only one operand.
Java Programming 1 - 95 Introduction to Java

 The relational operators are also known as Comparison operator.


 The Logical operators are also known as Short-Circuit Logical Operators.
 The bitwise operators &, ^ and | provide bitwise AND, Exclusive-OR (XOR) and OR
operations respectively. They are applicable to integral types.
 Java provide three shift operators <<, >>, >>>. Shifting of bits is used in control system.
 An array is a group of similar type of variables that are referred to by a common name.
 The length attribute will give the length of array.
 An expression is a series of variables, operators and method calls that evaluates to a single
value.
 It is used to control the flow of the execution of statements.
 The if inside it is called as nested if statement.
 The switch statement causes a particular group of statement to be chosen from several
available groups.
 In for loop, execution of a group of statements is repeated a designated number of times.
 The while loop has a loop condition which controls the execution of the loop statement.
 A break statement skips the remaining part and the remaining iterations of the loop.
Practice Questions
1. What do you understand by bytecode ?
2. Why java is more popular for internet programming ?
3. Java is platform independent language ? Comment.
4. Explain any four features of java.
5. Explain public static void main (String args[]).
6. Explain working of java.
7. Explain working of jvm.
8. Explain two kind of program that can be developed in java.
9. Explain variables ? Explain rules of variable.
10. What do you mean by type casting. Give any Example Also write hierarchy for primitive
casting of data type ?
11. Describe any two bit wise operator in java ?
12. Describe switch case statement with Example ?
13. In the expression involving the operator and (bitwise AND), | (bitwise OR),
&&(Logical AND) and || (Logical or), which operators are evaluated and the value of
expression with suitable example ?
14. Explain the term:
(a) Variable (b) Constants (c) Keywords (d) Data Types.
15. Give primitive data types in java and its storage ?
Java Programming 1 - 96 Introduction to Java

16. Describe logical operator in java ?


17. Give different scope of variable in java ?
18. What are signed and unsigned shift operators ?
19. Write program to find largest of three number using logical operator ?
20. Write program to find smallest of three number using logical operator ?
21. Write a program to find smallest of Three number using nested if ?
22. Write a program to display:
(a) * * * * * (b) 1 1 1 1 1 (c) 1 2 3 4 5 (d) a b c d e (e) a a a a a (f) a b c d e
**** 2222 1234 abcd bbbb fghi
*** 333 123 abc ccc jkl
** 44 12 ab d d mn
* 5 1 a e o
23. Write a program to print Fibonacci series.
24. Write a program to find factorial of a number.
25. Write a program to find following sum of series
(a) 1 + x + x2 + x3 + … xn
(b) 1 + x – x2 + x 3 – … xn
26. A person will be insured if
(a) is male and having age more than 30 and married.
(b) is male and having age more than 25 and unmarried.
(c) is female and having age more than 22 and married.
(d) is female and having age more than 20 and unmarried.
Write a program for above
27. Write a program which will display following menu.
(a) Add
(b) Sub
(c) Mul
(d) Div
Take the choice from the user and perform the operation on two values.
28. Write a program which will take today’s date as input and calculate tomorrows date.
29. Write a program which will take today’s date as input and calculate yesterdays date.
30. Write a program which will search a number entered by user from array.
31. Write a program to arrange numbers stored in array in ascending order.
32. Write a program which will find first n even numbers.
33. Write a program which will find first n odd numbers, (use if else).
Java Programming 1 - 97 Introduction to Java

34. Write a program which will print n natural numbers, (take input as command line
argument).
35. Write a program which will perform addition of first n even and odd number, (take input as
command line argument).
36. Write a program which will find the addition of first n numbers, (take input as command
line argument)
37. Write a program which will add two matrix
38. Write a program which will multiply two matrix.
39. Write a program which will find binary number of a given number
40. Write a program which will find the sum of total digits of a number entered by user
41. Write a program which will reverse a number given as command line argument
42. Write a program to find xy.
MSBTE Questions & Answers

1. State any four features of Java. [4 M]

Ans. Please refer to Section 1.3.


2. Describe arithmetic operators with examples. [4 M]

Ans. Please refer to Section [Link].


3. Write a program to convert a decimal number to binary form and display the value. [4 M]
Ans. Please refer to Programs of Section 1.7.
4. Describe various bitwise operators with example. [4 M]
Ans. Please refer to Section [Link].

1. Why java is popular for internet ? Explain. [4 M]

Ans. Please refer to Page 1.18.


2. State any four decision making statement along with their syntax. [4 M]
Ans. Please refer to Section 1.6.
3. Why java is called truly object oriented ? Explain. [4 M]
Ans. Please refer to Section 1.1.
4. Write a program to generate Fibonacci series for any number using loop. [4 M]

Ans. Please refer to Section 1.7.


5. What is ByteCode ? Explain any tools available in JDK. [8 M]

Ans. Please refer to Section 1.1.5.


Java Programming 1 - 98 Introduction to Java

6. Differentiate between break and continue statement. [4 M]


Ans. Please refer to Section 1.7.4.

1. Write all primitive datatypes available in java with their storage sizes in bytes. [4 M]
Ans. Please refer to Section 1.4.4.
2. Explain why java is called as true object oriented language. [4 M]
Ans. Please refer to Section 1.1.
3. Write a program to accept a number and print its factorial. [4 M]
Ans. Please refer to Programs of Section 1.7.
4. Explain the concept of JVM with respect to portability feature of java. [4 M]
Ans. Please refer to Section 1.3.

1. List different data types in java. [4 M]


Ans. Please refer to Section 1.4.4.
2. State different features of java. Those make it different from 'C' language. [4 M]
Ans. Please refer to Section 1.3.
3. Write a program to calculate percentage of 4 subjects and print in suitable format. [4 M]
Ans. Please refer to Sections 1.6 and 1.7.
4. Write a program to check whether the entered number is prime or not. [4 M]
Ans. Please refer to Sections 1.6 and 1.7.
5. Explain relational and logical operators in java. [4 M]
Ans. Please refer to Sections [Link] and [Link].
6. Write a program to generate Fibonacci series 1 1 2 3 5 8 1 3 for any number
using loop. [4 M]
Ans. Please refer to Sections 1.6 and 1.7.

1. Describe any two features of java. [4 M]


Ans. Please refer to Section 1.3.
2. Explain typecasting with suitable example. [4 M]
Ans. Please refer to Section 1.4.5.
3. Write a program to print sum of the number. [4 M]
Ans. Please refer to Sections 1.6 and 1.7.

1. Explain: [4 M]
(i) Platform independence.
(ii) Data encapsulation features of java.
Ans. Please refer to Section 1.3.
2. Explain type casting with suitable example. [4 M]
Java Programming 1 - 99 Introduction to Java

Ans. Please refer to Section 4.5.


3. Write program to input a number and find sum of all prime numbers from 1 to that
number. [4 M]
Ans. Please refer to Sections 1.6 and 1.7.


You might also like