Introduction to Java Programming Basics
Introduction to Java Programming Basics
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.
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).
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.”
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.
(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
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.
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.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.
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.
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
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".
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!'.
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
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;
}
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
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
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
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
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
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
[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 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.
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.
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
------- * ---------
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
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
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.
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
Fig. 1.23
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...
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
(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
(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
}
}
}
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:
*
* *
* * *
* * * *
* * * * *
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");
[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
}
}
}
Output:
..........
.........
........
.......
......
.....
....
...
..
.
}
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
}
}
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
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
{
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
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
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. 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. 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