0% found this document useful (0 votes)
3 views45 pages

Java Unit-1 Material

Uploaded by

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

Java Unit-1 Material

Uploaded by

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

ST.

ANN’S COLLEGE OF ENGINEERING &TECHNOLOGY :: CHIRALA


DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
JAVA PROGRAMMING (UNIT-1)

SYLLABUS(UNIT-1):
Program Structure in Java: Introduction, Writing Simple Java Programs, Elements or
Tokens in Java Programs, Java Statements, Command Line Arguments, User Input to
Programs, Escape Sequences, Comments, Programming Style.
Data Types, Variables, and Operators: Introduction, Data Types in Java, Declaration of
Variables, Data Types, Type Casting, Scope of Variable Identifier, Literal Constants,
Symbolic Constants, Formatted Output with printf() Method, Static Variables and Methods,
Attribute Final, Introduction to Operators, Precedence and Associativity of Operators,
Assignment Operator ( = ), Basic Arithmetic Operators, Increment (++) and Decrement (- -)
Operators, Ternary Operator, Relational Operators, Boolean Logical Operators, Bitwise
Logical Operators.
Control Statements: Introduction, if Expression, Nested if Expressions, if–else Expressions,
Ternary Operator?:, Switch Statement, Iteration Statements, while Expression, do–while
Loop, for Loop, Nested for Loop, For–Each for Loop, Break Statement, Continue Statement.

1. History of JAVA:
The history of java starts from Green Team. Java team members (also known
as Green Team), initiated a revolutionary task to develop a language for digital devices such
as set-top boxes, televisions etc. Later, Java technology as incorporated by Netscape.
Currently, Java is used in internet programming, mobile devices, games, e-business solutions
etc. There are given the major points that describes the history of java.
i) James Gosling, Mike Sheridan, and Patrick Naughton initiated the Java language
project in June 1991. The small team of sun engineers called Green Team.
ii) Firstly, it was called "Greentalk" by James Gosling and file extension was .gt.
iii) After that, it was called Oak and was developed as a part of the Green project.
Why Oak name for java language?
iv) Oak is a symbol of strength and chosen as a national tree of many countries like U.S.A.,
France, Germany, Romania etc. During 1991 to 1995 many people around the world
contributed to the growth of the Oak, by adding the new features. Bill Joy, Arthur van
Hoff,Jonathan Payne, Frank Yellin, and Tim Lindholm were key contributors to the
Original prototype.
v) In 1995, Oak was renamed as "Java" because it was already a trademark by Oak
technologies.
Why they chose java name for java language?
vi) The team gathered to choose a new name. The suggested words were "dynamic",
"revolutionary", "Silk", "jolt", "DNA" etc. According to James Gosling "Java was one of the
top choices along with Silk". Since java was so unique, most of the team members preferred
java.
vii) Java is an island of Indonesia where first coffee was produced (called java coffee).
viii) Originally developed by James Gosling at Sun Microsystems (which is now a subsidiary
of Oracle Corporation) and released in 1995.
ix) In 1995, Time magazine called Java one of the Ten Best Products of 1995 and JDK 1.0
released in(January 23, 1996).

2. Features of Java ( Buzzwords of Java)


Java is the most popular object-oriented programming language. Java has many advanced
features, a list of key features is known as Java Buzz Words. The most important features of
the Java language is given below.
 Simple
 Platform Independent
 Secure
 Portable
 Object-oriented
 Robust
 Multithreaded
 Architecture-neutral
 Interpreted
 High performance
 Distributed
 Dynamic
Simple
Java was designed to be easy for the professional programmer to learn and use effectively.
According to Sun, Java language is simple because: syntax is based on C++ (so easier for
programmers to learn it after C++). removed many confusing and/or rarely-used features e.g.,
explicit pointers, operator overloading etc.
Platform Independent
Java is platform independent because it is different from other languages like C, C++, etc.
which are compiled into platform specific machines while Java is a write once, run anywhere
language. Java code can be executed on multiple platforms, for example, Windows, Linux,
Sun Solaris, Mac/OS, etc. Java code is compiled by the compiler and converted into
bytecode. This bytecode is a platform-independent code because it can be run on multiple
platforms.
Secure
Java is best known for its security. With Java, we can develop virus-free systems. Once the
byte code generated, the code can be transmitted to other computer in the world with
knowing the internal details of the source code.
Portable
Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't
require any implementation. The byte code can be easily carried from one machine to other
machine.
Object Oriented
Java is an object-oriented programming language. Everything in Java is an object. Object-
oriented means we organize our software as a combination of different types of objects that
incorporate both data and behavior. The object model in Java is simple and easy to extend,
while primitive types, such as integers, are kept as high-performance non-objects.
Robust
The multi-plat-formed environment of the web places extraordinary demands on a program,
because the program must execute reliably in a variety of systems. Thus, the ability to create
robust programs was given a high priority in the design of Java. Java also frees from having
worry about many errors. Java is Robust in terms of memory management and mishandled
exceptions. Java provides automatic memory management and also provides well defined
exception handling mechanism.
Multithreaded
A thread is like a separate program, executing concurrently. We can write Java programs that
deal with many tasks at once by defining multiple threads. The main advantage of multi-
threading is that it doesn't occupy memory for each thread. It shares a common memory area.
Threads are important for multi-media, web applications, etc.
Architecture-neutral
The Java designers made several hard decisions in the Java language and the Java Virtual
Machine in an attempt to alter this situation. Their goal was “write once; run anywhere, any
time, forever.” To a great extent, this goal was accomplished.
Interpreted and High Performance
Java enables the creation of cross-platform programs by compiling into an intermediate
representation called Java byte code. This code can be executed on any system that
implements the Java Virtual Machine. Most previous attempts at cross-platform solutions
have done so at the expense of performance. As explained earlier, the Java byte code was
carefully designed so that it would be easy to translate directly into native machine code for
very high performance by using a just-in-time compiler.
Distributed
Java is designed for the distributed environment of the Internet because it handles TCP/IP
protocols. In fact, accessing a resource using a URL is not much different from accessing a
file. Java also supports Remote Method Invocation (RMI). This feature enables a program to
invoke methods across a network.
Dynamic
Java programs carry with them substantial amounts of run-time type information that is used
to verify and resolve accesses to objects at run time. This makes it possible to dynamically
link code in a safe and expedient manner.

3. Java Virtual Machine

The key that allows Java to solve both the security and
the portability problems is the byte code. The output of Java
Compiler is not directly executable file. Rather, it contains
highly optimized set of instructions. This set of instructions is
called, "byte code". This byte code is designed to be executed
by Java Virtual Machine (JVM). The JVM also called as the
interpreter for byte code. JVM also helps to solve many
problems associated with web-based programs.
Translating a Java program into byte code makes it much
easier to run a program in a wide variety of environments
because only the JVM needs to be implemented for each
platform. Figure: Java Virtual Machine (JVM)
Once the run-time package exists for a given system, any Java program can run on it.
Remember, although the details of the JVM will differ from platform to platform, all
understand the same Java byte code. Thus, the execution of byte code by the JVM is the
easiest way to create truly portable programs.

The fact that a Java program is executed by the JVM also helps to make it secure.
Because the JVM is in control, it can contain the program and prevent it from generating side
effects outside of the system.

In general, when a program is compiled to an intermediate form and then interpreted by a


virtual machine, it runs slower than it would run if compiled to executable code. However,
with Java, the differential between the two is not so great. Because byte code has been highly
optimized, the use of byte code enables the JVM to execute programs much faster than you
might expect
4. Comparison between C , C++ and JAVA Languages
The following table describes the major differences between C, C++, and Java.

S
N C C++ JAVA
o

1 It is a procedural language. It is an object-oriented It is a pure object-oriented programming


programming language. language.

2 It is a static programming It is also a static It is a dynamic programming language.


language. programming language.

3 The code is executed directly. The code is executed The code is executed by the JVM.
directly.

4 It is platform dependent. It is platform It is platform-independent because of byte code.


dependent.

5 It uses a compiler only to It also uses a compiler Java uses both compiler and interpreter and
translate the code into only to translate the it is also known as an interpreted language.
machine language. code into machine
language.

6 It generates the .exe, and .bak, It generates .exe file. It generates .class file.
files.

7 The source file has a .c The source file has a The source file has a .java extension.
extension. .cpp extension.

8 It supports pointers. It also supports Java does not support the pointers concept
pointers. because of security.

9 It supports union and structure It also supports union It does not support union and structure data
data types. and structure data types. types.

10 It uses pre-processor It uses pre-processor It does not use directives but uses packages.
directives such as #include, directives such as
#define, etc. #include,#define,
#header, etc.

11 It does not support constructor It supports both It supports constructors only.


and destructor. constructors and
destructors.

12 It does not support exception It supports exception It also supports exception handling.
handling. handling.

13 It uses the calloc(), malloc(), It uses new and delete It uses a garbage collector to manage the
free(), and realloc() methods operator to manage the memory.
to manage the memory. memory.
5. Object-Oriented Programming(OOP) Principles
All object-oriented programming languages provide mechanisms that help you implement the
object-oriented model. They are as follows:
i. Abstraction
ii. Encapsulation
iii. Inheritance
iv. Polymorphism
 Compile-time polymorphism
 Runtime polymorphism
i) Abstraction
Data Abstraction is the property by virtue of which only the essential details are
displayed to the user. The trivial or non-essential units are not displayed to the user.
Data Abstraction may also be defined as the process of identifying only the required
characteristics of an object, ignoring the irrelevant details. The properties and behaviors of
an object differentiate it from other objects of similar type and also help in
classifying/grouping the object. In Java, abstraction is achieved by interfaces and abstract
classes. We can achieve 100% abstraction using interfaces.
Consider a real-life example of a man driving a car. The man only knows that
pressing the accelerators will increase the car speed or applying brakes will stop the car, but
he does not know how on pressing the accelerator, the speed is actually increasing. He does
not know about the inner mechanism of the car or the implementation of the accelerators,
brakes etc. in the car.

ii) Encapsulation
Encapsulation is the mechanism that binds together code and the data it manipulates,
and keeps both safe from outside interference and misuse. One way to think about
encapsulation is as a protective wrapper that prevents the code and data from being arbitrarily
accessed by other code defined outside the wrapper. Access to the code and data inside the
wrapper is tightly controlled through a well-defined interface.
Technically, in encapsulation, the variables or the data in a class is hidden from any
other class and can be accessed only through any member function of the class in which
they are declared. In encapsulation, the data in a class is hidden from other classes, which is
similar to what data-hiding does. So, the terms “encapsulation” and “data-hiding” are used
interchangeably.

iii) Inheritance
Inheritance is an important pillar of OOP (Object Oriented Programming). It is the
mechanism in Java by which one class is allowed to inherit the features of another class.
 Superclass: The class whose features are inherited is known as superclass (also known
as base or parent class).
 Subclass: The class that inherits the other class is known as subclass (also known as
derived or extended or child class). The subclass can add its own fields and methods in
addition to the superclass fields and methods.
 Reusability: Inheritance supports the concept of “reusability”, i.e. when we want to
create a new class and there is already a class that includes some of the code that we
want, we can derive our new class from the existing class. By doing this, we are reusing
the fields and methods of the existing class.

iv) Polymorphism
It refers to the ability of object-oriented programming languages to differentiate
between entities with the same name efficiently. This is done by Java with the help of the
signature and declaration of these entities. Polymorphism in Java is mainly of two types:
 Compile-time polymorphism
Method overloading is also known as Compile-time Polymorphism, Static
Polymorphism, or Early binding in Java. Method Overloading allows different methods to
have the same name, but different signatures where the signature can differ by the number
of input parameters or type of input parameters, or a mixture of both.
 Runtime polymorphism
Method overriding is also known as Run Time Polymorphism or Dynamic
Polymorphism or Late binding in Java. Overriding is a feature that allows a subclass or
child class to provide a specific implementation of a method that is already provided by one
of its super-classes or parent classes. When a method in a subclass has the same name,
same parameters or signature, and same return type(or sub-type) as a method in its super-
class, then the method in the subclass is said to override the method in the super-class.

6. Writing Simple Java Programs


File Name: [Link]
class Helloworld
{
public static void main(String args[])
{
[Link]("Hello World");
}
}

Creating and Running the Java Program:


We can use any text editor such as "notepad' or "dos text editor". The source code is typed
and is saved with ".java" as extension. The source code contains one or more class
definitions. The program name will be same as class name in which main function is written.
This in not compulsory, but by convention this is used. The source file is officially called as
compilation unit. We can even uses our choice of interest name for the program. If we use a
different name than the class name, then compilation is done with program name, and
running is done with class file name. To avoid this confusion and organize the programs well,
it is suggested to put the same name for the program and class name, but not compulsory.
Compiling the Program
To compile the program, first execute the compiler, "javac", specifying the name of the
source file on the command line, as shown bellow:
c:\>javac [Link]
The javac compiler creates the file called "[Link]", that contains the byte code
version of the source code. This byte code is the intermediate representation of the source
code that contains the instructions that the Java Virtual Machine (JVM) will execute. Thus
the output of the javac is not the directly executable code.
Running the Program
To actually run the program, we must use Java interpreter, called "java". This is
interpreter the "[Link]" file given as input.
c:/> java Helloworld
When the program is run with java interpreter, the following output is produced: Helloworld

Description of the every line of the program


The first line contains the keyword class and class name, which actually the basic unit for
encapsulation, in which data and methods are declared.
Second line contains "{" which indicates the beginning of the class.
Third line contains the public static void main(String args[])
where “public” is access specifier, when a member of a class is made public it can be
accessed by the outside code also. The “static” is the keyword which is used to call the main
function without instantiation. The “void” is also a keyword which is used to describe the the
return type of the function. The main function is the beginning of from where execution
starts. Java is case-sensitive. "Main" is different from the "main". In main there is one
parameter, String args, which is used to read the command line arguments.
Fourth line contains the "{", which is the beginning of the main method.
Fifth line contains the statement [Link]("Hello World");
Here "System" is the predefined class, that provides access to the system, and out is the
output stream that is used to connect to the console. The println(), is used to display string
passed to it. This can even display other information to.
7. Elements or Tokens in Java Programs
A Token is a smallest element in java program which is recognized by the compiler and
which treats them as defined for compiler. Therefore a program is set of tokens.
The token comprise the following:
i. Identifiers or Variables
ii. Keywords
iii. Literals
iv. Separators
v. Operators

i. Identifiers
Identifiers are used for class names, method names, and variable names. An
identifier may be any descriptive sequence of uppercase and lowercase letters, numbers, or
the underscore and dollar-sign characters. They must not begin with a number, lest they be
confused with a numeric literal. In Java, identifiers are also called variables since they
identify the memory locations. Java is case-sensitive, so VALUE is a different identifier than
Value.
Rules for Naming Identifier:
 The first character of an identifier must be a letter, or dollar($) sign.
 The subsequent characters can be letters, an underscore, dollar sign or digit.
 White spaces are not allowed within identifiers.
 Identifiers are case sensitive so VALUE is a different identifier than Value
Some examples of valid identifiers are:
Average Height A1 Area_Circle
Invalid Identifiers are as follow:
2types Area-circle Not/ok

Naming Convention for Identifiers:


 Class or Interface- These begin with a capital letter. The first alphabet of every
internal word is capitalized. Ex: class Myclass;
 Variable or Method –These start with lower case letters. The first alphabet of every
internal word is capitalized. Ex:- int totalPay;
 Constants- These are in upper case. Underscore is used to separate the internal word.
Ex:-final double PI=3.14;
 Package – These consist of all lower-case letters. Ex:- import [Link].*;

ii. Java Keywords or Reserved words


Java keywords are also known as reserved words. Java has a number of keywords.
These are the words that you cannot use as identifiers. Key words have a specific meaning to
the Java language and these meanings does not change during execution of the program.
There are 50 keywords currently defined in the Java language (see Table bellow). These
keywords, combined with the syntax of the operators and separators, form the foundation of
the Java language.

iii. Literals
A literal is a value that can be passed to a variable or constant in a program. Literals can
be numeric, boolean, character, string notation or null. A constant value in Java is created by
using a literal representation of it. It can be assigned directly to a variable. Java has various
types of literals. There are the majorly six types of literals in Java as follows:
1. Integer Literal
2. Floating point Literals
3. Boolean Literal
4. Character Literal
5. String Literal
6. Null Literal
1. Integer Literal
Integer literals are sequences of digits. There are three types of integer literals:
• Decimal Integer: These are the set of numbers that consist of digits from 0 to 9. It
may have a positive (+) or negative (-) . For example, int decVal = 9 ;
• Octal Integer: It is a combination of number have digits from 0 to 7 with a leading 0.
For example, int octVal = 065;
• Hexa-Decimal: The sequence of digits preceded by 0x or 0X is considered as
hexadecimal integers. It may also include a character from a to f or A to F that
represents numbers from 10 to 15, respectively. For example, int hexVal = Ox6AF32
• Binary Integer: Base 2, whose digits consists of the numbers 0 and 1 . Prefix 0b
represents the Binary system. You can create binary literals in Java SE 7 and later.
int binVal = 0b1001;
2. Floating point Literals
• The vales that contain decimal are floating literals. In Java, float and double primitive
types fall into floating-point literals.
• For Floating-point data types, we can specify literals in only decimal form, and we
cant specify in octal and Hexadecimal forms. Floating-point literals for float type end
with F or f. Example: float length = 15.42f;
3. Boolean Literal
• Boolean literals are the value that is either true or false. It may also have values 0 and
1. For example, boolean x=true; boolean y=false;
4. Character Literal
• A character literal is expressed as a character or an escape sequence, enclosed in
a single quote ('') mark. It is always a type of char. For example, char ch=’A’;
char ch=’9’;.
5. String Literal
• String literal is a sequence of characters that is enclosed between double quotes ("")
marks. It may be alphabet, numbers, special characters, blank space, etc. For example,
String str1=”java is a Object Oriented Programming”;
6. Null Literal
• Null literal is often used in programs as a marker to indicate that reference type object
is unavailable. The value null may be assigned to any variable, except variables of
primitive types.
• Example, String Name = null; [Link](Name); //it will not give any output
iv) Separators
In Java, there are a few characters that are used as separators. The most commonly used
separator in Java is the semicolon and it is used to terminate statements. The separators are
shown in the following table:

v) Operators
Operators are used to perform operations on variables and values. Java provides
many types of operators which can be used according to the need. They are classified
based on the functionality they provide. Some of the types are: Unary Operators ,
Arithmetic Operators,Assignment Operators ,Logical Operators ,Shift Operators ,Bitwise Ope
rators ,Ternary Operators and Relational Operators.

8. Command Line Arguments


The arguments that are passed at command prompt, are called Command Line
Arguments. These are passed at the time of program execution. The Java application can
accept any number of arguments. They are captured into the String args of your main method.
JVM stores the first command-line argument at args[0], the second at args[1], the third at
args[2], and so on.
To run this java program, you must pass at least one command line argument from the
command prompt. There is no restriction on the number of java command line arguments.
You can specify any number of arguments and Information is passed as Strings.

For example: File Name: [Link]


class Colors
{
public static void main(String args[] )
{
for( int i=0; i<[Link]; i++) // returns array lengths
{
[Link](“ Commandline arguments are:”+args[i]);
}
}
}

c:/> javac [Link]


c:/> java Colors green orange blue
Output:
Commandline arguments are:
green // args[0]
orange // args[1]
blue // args[2]

9. User Input to Programs


• Java provides various ways to read input data from the keyboard, the Scanner class is one
of them. Scanner class is found in the [Link] package in Java.
• The Java Scanner class breaks the input into tokens using a delimiter which is whitespace
by default.
• By the help of Scanner, we can get input from the user in primitive types such as int,
long, double, byte, float, short, etc. First we create an object from Scanner class and we
will access the public methods of it.
• There are different methods such as nextInt() , nextFloat(), nextDouble(), nextLine() ,
nextLong() , nextShort() , close() etc., nextInt() method of a Scanner object reads in a
string of digits (characters) and converts them into an int type.
Example for Scanner class: [Link]
import [Link].*;
public class AddTwoNumbers
{
public static void main(String a[])
{
int a , b , c ;
Scanner in = new Scanner([Link]);
[Link]("Enter a valiue");
a = [Link]();
[Link]("Enter b valiue");
b = [Link]();
c = a + b;
[Link](“Sum is:”+” “+c);
}
}

10. Comments in Java


Comments in Java are non-executable statements, used to understand the code better and to
make it more readable. A program can be documented by inserting comments at relevant
places. These comments are for documentation purposes and are ignored by the compile
while compiling a code.
Java provides three types of comments to document a program:
 A single-line comment: // ... to the end of the line
 A multiple-line comment: /* ... */
 A documentation (Javadoc) comment: /** ... */
Single-line Comment
 All characters after the comment-start sequence // through to the end of the line
constitute a single-line comment. Example: // Welcome to CSE
Multiple-line Comment
 A multiple-line comment, as the name suggests, can span several lines. Such a
comment starts with /* and ends with */.
Example: /* Welcome to CSE
JAVA is a Object Oriented Programming */
Documentation Comment
A documentation comment is a special-purpose comment that when placed before class or
class member declarations can be extracted and used by the javadoc tool to generate HTML
documentation for the program. Documentation comments are usually placed in front of
classes, interfaces, methods and field definitions. Such a comment starts with /** and ends
with */:
Example:
import [Link].*;
class CommentsDemo {
public static void main (String[] args) {
/**
comment line 1
comment line 2
*/
}}

11. Escape Sequences


In Java, if a character is preceded by a backslash (\) is known as Java escape
sequence or escape characters and has a special meaning to the compiler. The following table
shows the Java escape sequences.

Escape Sequence Description


\t Inserts a tab in the text at this point.

\b Inserts a backspace in the text at this point.

\n Inserts a newline in the text at this point.


\r Inserts a carriage return in the text at this point.

\f Inserts a form feed in the text at this point.


\' Inserts a single quote character in the text at this point.

\" Inserts a double quote character in the text at this point.


\\ Inserts a backslash character in the text at this point.
Example:
public class EscapeSequenceExample
{
public static void main(String args[])
{
String str = “Welcome\tto CSE"; //it inserts a Tab Space
[Link](str);
String str1 = “Stann’s\nEngineering \nCollege“; //it inserts a New Line
[Link](str1);
String str2 = “CSE\\IT"; //it insert a backslash
[Link](str2);
String str3 = "Carriage\rReturn"; //it insert a Carriage
[Link](str3);
String str4 = “[Link]\'s"; //it prints a single quote
[Link](str4);
String str5 = “\”SACET\”"; //it prints double quote
[Link](str5);
String str6 = “Form\fFeed"; //it prints form feed
[Link](str6);
}
}

12. Java Statements


In Java, a statement is an executable instruction that tells the compiler what to
perform. It forms a complete command to be executed and can include one or more
expressions. A sentence forms a complete idea that can include one or more clauses.
Types of Statements:
Java statements can be broadly classified into the following categories:
• Declaration Statement
• Expression Statement
• Control Statement
• Synchronized Statement
• Guarding statement

Declaration Statement
In declaration statements, we declare variables and constants by specifying their data
type and name. A variable holds a value that is going to use in the Java program.
For example: int quantity;
String name;
Expression Statement
Expression is an essential building block of any Java program. Generally, it is used to
generate a new value. Sometimes, we can also assign a value to a variable. In Java,
expression is the combination of values, variables, operators, and method calls.
For example: num =2; sum = a + b;
Control Statement
Control statements decide the flow of sequence of execution of statements in a
program. They include selection, iteration and jump statements.
For example:
int number;
number=20;
if (number > 10 )
{
[Link](number + " is greater than 10");
}
Synchronized Statement
There are used in multi-threading. Synchronized block can be used to perform
synchronization on any specific resource of the method.
Example: synchronized(this){//synchronized block
for(int i=1;i<=5;i++){
[Link](n*i);
try{
[Link](400);
}catch(Exception e){[Link](e);}
}
}
Guarding statement
Guarding statements are used for safe handling of code that may cause exceptions .
These statements use the keywords. Example: try, catch, throw, throws and finally.

13. Programming Style


Computer programs should be written so that they can be read, understand, and
modified by human readers. Programming style is important and most programs are
evaluated for style as well as for correctness. If the program is small, it is almost one-man
show. If the program is large, then it is not one-man show. The team will be writing and
hence the team members could able to understand it in easier manner. The following points
are helpful for good programming style.
 The program should present clean and orderly look.
 The program should be easy to understand.
 The debugging process should be easy.
 The program should be easy to use.
 The program should be easy to maintain.
 The program should be fail-safe. The failure of program should not cause to great
damage to system.

14. Data Types in Java


Java is strongly typed language. First, every variable has a type, every expression has a type,
and every type is strictly defined. Second, all assignments, whether explicit or via parameter
passing in method calls, are checked for type compatibility. Data types specify the different
sizes and values that can be stored in the variable. There are two types of data types in Java:
1. Primitive data types
2. Non-primitive data types
1. Primitive data types
Primitive data type specifies the size and type of variable values, and it has no
additional methods. There are 8 primitive data types include boolean, char, byte, short, int,
long, float and double. These are again grouped into 4 groups.
i. Integers
ii. Floating-Point Types
iii. Characters
iv. Booleans

i. Integers
• The integer group contains byte, short, int, long. These data types will need different
sizes of the memory. These are assigned positive and negative values. The width and
ranges of these values are as follow:

byte:
• The smallest integer type is byte. This is a signed 8-bit type that has a range from –
128 to [Link] of type byte are especially useful when you’re working with a
stream of data from a network or file.
• For example, byte b, c; // where b and c are identifiers
short:
• short is a signed 16-bit type. It has a range from –32,768 to 32,767. It is probably the
least-used Java type. Examples of short variable declarations: short s; short t;
int:
• The most commonly used integer type is int. It is a signed 32-bit type that has a range
from –2,147,483,648 to 2,147,483,647. Example: int x=12;
long:
• long is a signed 64-bit type and is useful for those occasions where an int type is not
large enough to hold the desired value. The range of a long is quite large.
• Example: long x=123456;

Example for Integers Data Types:


class IntegerDataTypes
{
public static void main(String args[]) {
int a = 10;
short s = 2;
byte b = 6;
long l = 123456;
[Link]("The integer variable is: " + a );
[Link]("The short variable is: " + s);
[Link]("The byte variable is: " + b);
[Link]("The long variable is: " + l);
}}
Output: The integer variable is: 10
The short variable is: 2
The byte variable is: 6
The long variable is: 123456
ii. Floating-Point Types
• Floating-point numbers, also known as real numbers, are used when evaluating
expressions that require fractional precision. These are used with operations such as
square root, cosine, and sine etc.
• There are two types of Floating-Point numbers: float and double.

float:
• The float type represents single precision and double represents double precision. For
single precision, 32 bits are used to represents the floating point number. For double
precision, 64 bits are used to represents the floating point number.
• A float can have a 7-digit decimal precision and ends with an ‘f’ or ‘F’
Example for Floating-Point Data Type(float):
class FloatDataTypes
{
public static void main(String args[]) {
float f = 65.20298f;
[Link]("The float variable is: " + f);
}
}
double:
• Double precision, as denoted by the double keyword, uses 64 bits to store a value.
Double precision is actually faster than single precision on some modern processors.
Example program to calculate the area of a circle
import [Link].*;
class Circle
{
public static void main(String args[])
{
double r, area, pi;
r=12.3; // radius of circle
pi=3.14;
area=pi * r * r; // compute area
[Link]("The Area of the Circle is:"+area);
}
}
Output: The Area of the Circle is:475.0506000000001
iii. Characters
• In Java, the data type used to store characters is char. Java char is a 16-bit type. The
range of a char is 0 to 65,536. There are no negative chars.
• The char data type stores a single character. It stores both lower case and upper case
characters which must be enclosed in single quotes. The char data type in Java
supports Unicode characters .
Example: // Demonstrate char data type.
class CharDemo
{
public static void main(String args[])
{
char ch1, ch2;
ch1 = 88; // code for X
ch2 = 'Y';
[Link]("ch1 and ch2: ");
[Link](ch1 + " " + ch2);
}
} Output: ch1 and ch2: X Y

iv. Booleans
• Java has a primitive type, called boolean, for logical values. It can have only one of
two possible values , true or false. Boolean data type represents only one bit of
information either true or false.
Example: // Demonstrate boolean values
class BoolTest
{
public static void main(String args[])
{
boolean b;
b = false;
[Link]("b is " + b);
b = true;
[Link]("b is " + b);
if(b) [Link]("This is executed."); //a boolean value can control the if statement
b = false;
if(b) [Link]("This is not executed.");
// outcome of a relational operator is a boolean value
[Link]("10 > 9 is " + (10 > 9));
}
}
Output: b is false
b is true
This is executed.
10 > 9 is true

2. Non-primitive data types


Non-primitive data types refer to instances or objects. They cannot store the value of a
variable directly in memory. They store a memory address of the variable. The non-primitive
data types include Classes, Interfaces, Strings and Arrays etc., Non-primitive data types are
user-defined and they are created by programmers .
i. Strings
A String a sequence of array of characters enclosed with in double-quotes. A string is
predefined in Java. A String class provides a number of methods to perform operations on
strings such as compare(), concat(), equals(), split(), length(), replace(), compareTo(),
intern(), substring() etc. Syntax for declaring a string:
String_Type string_variable = “sequence_of_string”;
Example:
public class StringExample{
public static void main(String args[]){
String s1="Java Programming"; //creating string by Java string literal
char ch[]={'W','e','l','c','o','m','e'};
String s2=new String(ch); //converting char array to string
String s3=new String("II CSE"); //creating Java string by new keyword
[Link](s1);
[Link](s2);
[Link](s3);
}} Output: Java Programming
Welcome
II CSE
ii. Arrays
An array is used to hold elements of the same type. It is an object in java and all arrays
are dynamically allocated. A Java array variable can also be declared like other variables with
[] after the data type. The variables in the array are ordered and each has an index beginning
from 0. Array in Java is index-based, the first element of the array is stored at the 0th index,
2nd element is stored on 1st index and so on.
Syntax to Declare an Array in Java:
dataType[] arr; (or)
dataType []arr; (or)
dataType arr[];
Syntax for instantiation of an Array in Java
arrayRefVar=new datatype[size];
Both statements are combined into single statement as follows:
dataType arr[] = new datatype[size];
Example:
class Testarray{
public static void main(String args[]){
int a[]=new int[3]; //declaration and instantiation
a[0]=20; //initialization
a[1]=30;
a[2]=40;
//traversing array
for(int i=0;i<[Link];i++) //length is the property of array
[Link](a[i]);
}} Output: 20
30
40
iii. Classes
A class is a user-defined from which objects are created. It represents the set of
properties or methods that are common to all objects of one type. A class contains one or
more objects and each object is an instance of a class.
Syntax: class classname{
type instance-variable1;
type instance-variable2;
…………………..
type instance-variableN;
type methodname1(parameter-list)
{ body of method
}
type methodname2(parameter-list)
{ body of method
}
………………
type methodnameN(parameter-list)
{ body of method
} }
Example for Classes and objects
class Rectangle {
int length;
int width;
int calculateArea(int l, int w)
{
length=l;
width=w;
int Result=length*width;
return Result;
}
}
public class TestRectangle
{
public static void main(String args[])
{
Rectangle r1=new Rectangle();
int rectArea=[Link](3,4);
[Link]("Area of Rectangle:"+ " "+rectArea);
}
} output: Area of Rectangle: 12

iv. Interface
An interface is declared like a class. Interface is an abstract way of defining the structure of a
class. Java permits multiple inheritance through interfaces. An interface can have methods
and variables, but the methods declared in an interface are by default abstract .
Syntax: interface interfacename{
final type varname1= value;
…………….
final type varnameN= value;
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
…………………………..
return-type method-nameN(parameter-list);
}

Example for Interface:


interface I1
{
public void display();
}
class Test implements I1
{
public void display()
{
[Link]("Welcome to CSE");
}
}
public class InterfaceDemo
{
public static void main(String []args)
{
Test ob1=new Test();
[Link]();
}
}

15. Variables in Java


• The variable is the basic unit of storage in a Java program. A variable is defined by
the combination of an identifier, a type, and an optional initializer. In addition, all
variables have a scope, which defines their visibility, and a lifetime.
• The value stored in a variable can be changed during program execution. A variable is
only a name given to a memory location.
Declaring a Variable:
• In Java, all variables must be declared before they can be used. The basic form of a
variable declaration is shown below:
• type identifier [ = value][, identifier [= value] ...] ;
• Here the type is any primitive data types, or class name. The identifier is the name of
the variable. We can initialize the variable by specifying the equal sign and value.
• To declare more than one variable of the specified type, use a comma-separated list.

Example :
int a, b, c; // declares three integers, a, b, and c.
int d = 3, e, f = 5; // declares three more integerss, initializing d and f.
byte z = 22; // initializes z.
double pi = 3.14159; // declares an approximation of pi.
char x = 'x'; //the variable x ahs the value 'x‘
Dynamic Initialization of the variable
Java allows variables to be initialized dynamically, using any expression valid at the
time the variable is declared. We can also assign a value to the variable dynamically.
Example: Demonstrate dynamic initialization
class DynInit {
public static void main(String []args) {
double a=2.0 , b=3.0;
double c=a+b; // c is dynamically initialized
[Link](“c value is:”+ “ “+c);
}
}
Types of variables: In Java, there are three types of variables:
1. Local Variables
2. Instance Variables
3. Static Variables
1. Local Variables
• Local Variables are a variable that are declared inside the body of a method.
2. Instance Variables
• Instance variables are defined outside a method declaration. They are object specific
and are known as instance variables.
3. Static Variables
• We use the static keyword before the variable to define a variable, and this variable is
called as static variable.
• Static variables are initialized only once, at the start of the program execution. These
variables should be initialized first, before the initialization of any instance variables.
• When a method is completed, all of its variables are normally deleted. Sometimes we
need to store a variable even after completion of method execution.
Example for declaring types of variables
class VarTypes
{
static int a = 1; //static variable
int b = 2; //instance variable
void method1()
{
int c = 3; //local variable
}}
The Scope and Lifetime of Variables:
Scope of a variable is the part of the program where the variable is accessible. Java
allows, to declare a variable within any block. A block begins with opening curly brace and
ended with end curly brace. Thus, each time we start new block, we create new scope. A
scope determines what objects are visible to parts of your program. It also determines the life
time of the objects. Many programming languages define two scopes: Local and Global. As
a general rule a variable defined within one scope, is not visible to code defined outside of the
scope. Scopes can be also nested. The variable defined in outer scope are visible to the inner
scopes, but reverse is not possible.
Example for Scope and Lifetime of Variables
public class ScopeDemo
{
public static void main(String args[]) {
void method1()
{ //outer block
int a;
int a=10;
if(a==10) // here a , b, c are visible to the inner scope
{ // inner block
int b=a*20;
int c=a+30;
} //end of inner block
b=20*2; // b is not known here, which is declared in inner scope
[Link]("a is " + a); // a is still known here.
} //end of the outer block
}}
16. Symbolic Constants
• Constants may appear repeatedly in number of places in the program. Symbolic
constants are nothing more than a label or name that is used to represent a fixed value
that never changes throughout a program. They can’t be declared inside a method.
They should be used only as class data members in the beginning of the class.
Syntax : final type symbolicname = value;
Example: final float PI =3.14159; // declaring PI and STRENGTH constants
final int STRENGTH =80;
• After declaration of symbolic constants they shouldn’t be assigned any other
value with in the program by using an assignment statement.
For example, STRENTH = 100 is illegal
17. Formatted Output with printf() Method
• Java printf() is a method that belongs to the [Link] class and it is very
similar to the printf() function in C. It is used to format the output and print it to the
console..
• The printf() method of Java PrintStream class is a convenience method to write a
String which is formatted to this output Stream. It uses the specified format string and
arguments. The [Link]() function in Java allows users to print formatted
data. The general syntax of this method is as follows:
[Link](string)
[Link](format string, variables or objects separated by comma)
Example: // Java program to demonstrate working of printf() method
import [Link];
public class FormatterPrintfExample {
public static void main(String args[])
{
int x = 500;
[Link]("Printing integer value: x = %d\n",x);
// this will print it upto 2 decimal places
[Link]("Formatted with precision:PI = %.2f \n",[Link]);
float n = 5.2f; // automatically adds zero to the rightmost part of decimal
[Link]("Formatted to specific width: n = %.4f\n", n);
String str = "Department of CSE";
[Link]("%s", str);
}}

Output:
18. Static Variables and Methods
• The static keyword is used to construct methods that will exist regardless of
whether or not any instances of the class are generated. Any method that uses the
static keyword is referred to as a static method.
• A static method in Java is a method that is part of a class rather than an instance of
that class. Static methods have access to static variables without using the class’s
object (instance). It doesn’t require an object of the class.
• In both static and non-static methods, static methods can be accessed directly.
• Static variables are initialized only once, at the start of the program execution. These
variables should be initialized first, before the initialization of any instance variables.
• When a method is completed, all of its variables are normally deleted. Sometimes we
need to store a variable even after completion of method execution.
• Syntax for declare the static variable, static type variable = value;
• Syntax for declare the static method:
Access_modifier static void methodName() {
// Method body }
• The static variable and method is only accessible by class name. Syntax:
[Link];
[Link]();
Example for static variables and methods program:
public class StaticExample {
static int num = 500; //static variable
static String str = “II CSE SACET";
static void display() // This is Static method
{
[Link]("\nStatic number is " + num);
[Link]("\nStatic string is " + str);
}
void nonstatic() // non-static method
{
display(); // Static method can also access in non static method
}
public static void main(String args[]) // main method
{
StaticExample obj = new StaticExample(); //object creation
[Link](); // This is object to call non static function
[Link](); // static method can called directly without an obj
}
}

19. Attribute Final


final keyword is used in different contexts. First of all, final is a non-access
modifier applicable only to a variable, a method, or a class. The java final keyword can be
used in many context as follows:
1. final variable
2. final method
3. final class

1. Final Variables
When a variable is declared with the final keyword, its value can’t be modified,
essentially, a constant. If you make any variable as final, you cannot change the value of
final variable(It will be constant).
Example of final variable:
There is a final variable speedlimit, we are going to change the value of this variable,
but It can't be changed because final variable once assigned a value can never be changed.
class BikeRace{
final int speedlimit=90; //final variable
void run(){
speedlimit=100; // final variable value can’t be change
}
public static void main(String args[]){
BikeRace obj=new BikeRace();
[Link]();
}
} Output: Compile time Error
2. final method
When a method is declared with final keyword, it is called a final method. A final
method cannot be overridden. We must declare methods with the final keyword for which
we are required to follow the same implementation throughout all the derived classes.
Example for final method:
class A { //A is super class
final void meth() { // final method
[Link]("This is a final method.");
}
}
class B extends A { //B is sub class
void meth() { // ERROR! Can't override.
[Link]("Illegal!");
}}
• Because meth( ) is declared as final, it cannot be overridden in B. If you attempt to do
so, a compile-time error will result.
3. final class
When a class is declared with final keyword, it is called a final class. A final
class cannot be extended(inherited). Declaring a class as final implicitly declares all of its
methods as final, too.

For example,
final class A
{
// methods and fields
}
// The following class is illegal
class B extends A
{
// COMPILE-ERROR! Can't subclass A
}
• As the comments imply, it is illegal for B to inherit A since A is declared as final.

20. Type Conversion and Casting in Java


In type conversion, a data type is automatically converted into another data type by
a compiler at the compiler time. In type conversion, the destination data type cannot be
smaller than the source data type. Type casting is a mechanism in which one data type is
converted to another data type using a casting () operator by a programmer.

There are two types of conversion. They are Implicit Conversion, and Explicit Conversion.
Implicit Conversion or Java’s Automatic Conversions:
In the case of the implicit conversion type conversion is automatically performed by
java when the types are compatible. For example, the int can be assigned to long. The byte
cane assigned to short. However, all the types are compatible, thus all the type conversions
are implicitly allowed. For example, double is not compatible with byte.
Conditions for automatic conversion
1. The two types must be compatible
2. The destination type must be larger than the source type
When automatic type conversion takes place the widening conversion takes place. For
Example,
int a; //needs 32 bits
byte b=45; //needs the 8 bits
a=b; // here 8 bits data is placed in 32 bit storage. Thus widening takes place.

Explicit Conversion or Casting Incompatible Types:


Fortunately, it is still possible obtain the conversion between the incompatible types.
This is called explicit type conversion. Java provides a special keyword "cast" to facilitate
explicit conversion. For example, sometimes we want to assign int to byte, this will not be
performed automatically, because byte is smaller than int. This kind of conversion is
sometimes called "narrowing conversion". Since, you are explicitly making the value
narrow. The general form of the cast will be as follow:
destination_variable=(target type) value;
Here the target type specifies the destination type to which the value has to be converted.
Example ,
int a=1234;
byte b=(byte) a;
The above code converts the int to byte. If the integer value is larger than the byte,
then it will be reduced to modulo byte's range.

The following program demonstrates some type conversions that require casts:
// Demonstrate casts.
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); } }

This program generates the following output:


Conversion of int to byte.
i and b 257 1
Conversion of double to int.
d and i 323.142 323
Conversion of double to byte.
d and b 323.142 67
Automatic Type Promotion in Expressions:
The expression contains the three things: operator, operand and literals (constant). In
an expression, sometimes the sub expression value exceeds the either operand.
For example, examine the following expression:
byte a = 40;
byte b = 50;
byte c = 100;
int d = a * b / c;
The result of the intermediate term a * b easily exceeds the range of either of its byte
operands. To handle this kind of problem, Java automatically promotes each byte, short,or
char operand to int when evaluating an expression. This means that the sub expression a * b
is performed using integers—not bytes. Thus, 2,000, the result of the intermediate
expression,50 * 40, is legal even though a and b are both specified as type byte.
As useful as the automatic promotions are, they can cause confusing compile-time
errors. For example, this seemingly correct code causes a problem:
byte b = 50;
b = b * 2; // Error! Cannot assign an int to a byte!
The code is attempting to store 50 * 2, a perfectly valid byte value, back into a byte
[Link], because the operands were automatically promoted to int when the
expression was evaluated, the result has also been promoted to int. Thus, the result of the
expression is now of type int, which cannot be assigned to a byte without the use of a cast.
In cases where you understand the consequences of overflow, you should use an
explicit cast, such as
byte b = 50;
b = (byte)(b * 2); which yields the correct value of 100.

The Type Promotion Rules:


Java defines several type promotion rules that apply to expressions. They are as follows:
 First,all byte, short, and char values are promoted to int, as just described.
 Then, if one operandis a long, the whole expression is promoted to long.
 If one operand is a float, the entireexpression is promoted to float.
 If any of the operands is double, the result is double.
The following program demonstrates how each value in the expression gets promoted to
match the second argument to each binary operator:
class Promote {
public static void main(String args[]) {
byte b = 42;
char c = 'a';
short s = 1024;
int i = 50000;
float f = 5.67f;
double d = .1234;
double result = (f * b) + (i / c) - (d * s);
[Link]((f * b) + " + " + (i / c) + " - " + (d * s));
[Link]("result = " + result);
}}
Let’s look closely at the type promotions that occur in this line from the program: double
result = (f * b) + (i / c) - (d * s);
In the first subexpression, f * b, b is promoted to a float and the result of the subexpression is
float. Next, in the subexpression i/c, c is promoted to int, and the result is of type int. Then, in
d * s, the value of s is promoted to double, and the type of the subexpression is double
21. Operators
In Java, an operator is a special symbol used to perform operations on operands.
Operators are used in expressions to store or return a value. Java provides a rich operator
environment. An operator that performs an operation on one operand is called unary
operator. An operator that performs an operation on two operands is called binary operator.
Java operators can be classified into number of categories. Most of its operators can be
divided into the following groups:
i) Arithmetic Operators
ii) Relational or Comparison Operators
iii) Logical Operators
iv) Assignment Operators
v) Conditional Operators or Ternary Operators
vi) Unary Operators or Increment/Decrement Operators
vii) Bitwise Operators
viii) String Concatenation operator

i) Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations on the operands. They
act as basic mathematical operations. Java has the typical collection of numeric operators: the
binary operators + for addition, - for subtraction, * for multiplication, / for division, and % for
modulus. The operands of the arithmetic operations are of numeric type. The table below lists
the arithmetic operators in Java.
Operator Name Description Example Result

x+y Addition Sum of x and y 2+2 4


x-y Subtraction Difference of x and y 5-2 3
x*y Multiplication Product of x and y 5*2 10
x/y Division Quotient of x and y 15 / 5 3
x%y Modulus Remainder of x divided by y 10%2 0
Example program to perform all the arithmetic operations: [Link]
import [Link].*;
class ArithmeticExample
{
public static void main(String args[])
{
int a,b,c,d;
a=4;
b=2;
c=a+b; //arithmetic addition
[Link]("The Sum is :"+c);
d=a-b; //aritmetic subtraction
[Link]("The Subtractio is :"+d);
c=a/b; //arithmetic division
[Link]("The Dision is :"+c);
d=a*b; //arithmetic multiplication
[Link]("The multiplication is :"+d);
c=a%b;
[Link]("Remainder of a divided by b is :"+c);
}
}
ii) Relational or Comparison Operators
The relational operators determine the relationship that one operand has to the other.
Comparison operators allow comparing two values, such as number or string. The relational
operators are most frequently used in the expressions that control the if statement and the
various loop statements. The table below lists the Relational operators in Java.
Operator Name Description Example
x == y Equal True if x is equal to y 5==8 returns false
x !=y Not equal True if x is not equal to y 5!=8 returns true

x >y Greater than True if x is greater than y 5>8 returns false


x<y Less than True if x is less than y 5<8 returns true
x >= y Greater than or equal to True if x is greater than or equal to y 5>=8 returns false
x <= y Less than or equal to True if x is less than or equal to y 5<=8 returns true
As stated, the result produced by a relational operator is a boolean value. For example, the
following code fragment is perfectly valid:
int a = 4;
int b = 1;
boolean c = a < b; In this case, the result of a < b (which is false) is stored in c.

iii) Boolean Logical Operators


Boolean logical operators are used to determine the logic between variables or values.
These operators allow the evaluation and manipulation of specific bits within the integer. The
Boolean logical operators shown operate only on boolean operands. All of the binary logical
operators combine two boolean values to form a resultant boolean value.

The following table shows the effect of each logical operation:

// Demonstrate the boolean logical operators.


class BoolLogic {
public static void main(String args[]) {
boolean a = true;
boolean b = false;
boolean c = a | b;
boolean d = a & b;
boolean e = a ^ b;
boolean f = (!a & b) | (a & !b);
boolean g = !a;
[Link](" a = " + a);
[Link](" b = " + b);
[Link](" a|b = " + c);
[Link](" a&b = " + d);
[Link](" a^b = " + e);
[Link]("!a&b|a&!b = " + f);
[Link](" !a = " + g);
}}
Output:
a = true
b = false
a|b = true
a&b = false
a^b = true
!a&b|a&!b = true
!a = false
Short-Circuit Logical Operators:
These are secondary versions of the Boolean AND and OR operators, and are
commonly known as short-circuit logical operators. and are commonly known as short-circuit
logical operators. The OR operator results in true when A is true, no matter what B is.
Similarly, the AND operator results in false when A is false, no matter what B is. If you use
the || and && forms, rather than the | and & forms of these operators, Java will not bother to
evaluate the righthand operand when the outcome of the expression can be determined by the
left operand alone. Example, if (denom != 0 && num / denom > 10).

iv) Assignment Operators


Assignment operators are used to assign the result of an expression to a variable. They are =,
+=, -=, *=, /=, %=. The general form is: var = expression;
Operator Name Example Description
a = b (Simple The value of right operand is assigned to
= assignment assignment ) the left operand.
a=b=c(multiple
assignment)
+= Add then Assign A += b Addition same as a = a +b
(compound
assignment)
-= Subtract then Assign A -= b Subtraction same as a = a - b
*= Multiply then Assign A *= b Multiplication same as a = a *b

/= Divide then Assign A /= b Find quotient same as a = a / b


(quotient)
%= Divide then Assign ( A %= b Find remainder same as a = a / b
remainder)
v) Conditional Operators or Ternary Operators
Java includes a special ternary (three-way) operator that can replace certain types of if-
then-else statements. Java contains a conditional operator that assigns a value to a variable
based on some condition.
Syntax: variable_name = (condition)?value1:value2;

Example,
public class TernaryOperatorExample
{
public static void main(String args[])
{
int a, b, max;
a = 20;
b = 15;
max = (a>b) ? a: b;
[Link]("Max value is: " + max);
}
}
 The condition (a>b) is evaluated first. If the condition is true then a value will be
return to the Max. otherwise b value will be return.

vi) Incrementing/Decrementing Operators


The Java increment and decrement operators are used to increase and decrease the
value by 1. The increment operator ++, adds 1 to the operand and decrement operator--,
subtracts 1 from the operand.

Example, Demonstrates the increment and decrement operator(++ and --)


class IncDec
{
public static void main(String args[])
{
int a = 1;
int b = 2;
int c;
int d;
c = ++b; //pre increment
d = a--; //post decrement
c++; //post increment
d--; //post decrement
[Link]("a = " + a);
[Link]("b = " + b);
[Link]("c = " + c);
[Link]("d = " + d);
}
}

vii) The Bitwise Operators:


The bitwise operators are used to perform bit-level operations on operands. These operators
allow the evaluation and manipulation of specific bits within the integer. Java defines several
bitwise operators that can be applied to the integer types, long, int, short, char, and byte.
They are summarized in the following table:

These operators are again classified into two categories: Bitwise Logical operators, and
Shift operators.
The Bitwise Logical Operators:
The bitwise logical operators are &, |, ^, and ~. The following table shows the outcome of
each operation. The bitwise operators are applied to each individual bit within each operand.

The Bitwise NOT


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

00001010 10
The Bitwise OR
The OR operator, |, combines bits such that if either of the bits in the operands is a 1, then
the resultant bit is a 1, as shown here:
00101010 42
| 00001111 15

00101111 47
The Bitwise XOR
The XOR operator, ^, combines bits such that if exactly one operand is 1, then the result is 1.
Otherwise, the result is zero. The following example shows the effect of the ^.

00101010 (42)
^ 00001111 (15)

00100101 (37)
// Demonstrate the bitwise logical operators.
class BitLogic
{
public static void main(String args[])
{
int a = 3; // 0 + 2 + 1 or 0011 in binary
int b = 6; // 4 + 2 + 0 or 0110 in binary
int c = a | b;
int d = a & b;
int e = a ^ b;
int f = (~a & b) | (a & ~b);
int g = ~a & 0x0f;
[Link](" a|b = " +c);
[Link](" a&b = " +d);
[Link](" a^b = " +e);
[Link]("~a&b|a&~b = " +f);
[Link](" ~a = " + g);
}
}
Output:
a = 0011
b = 0110
a|b = 0111
a&b = 0010
a^b = 0101
~a&b|a&~b = 0101
~a = 1100
Bitwise Shift Operators: (left shift and right shift):
The Left Shift
The left shift operator, <<, shifts all of the bits in a value to the left a specified number of
times. It has this general form: value << num
Here, num specifies the number of positions to left-shift the value in value. That is, the
<<moves all of the bits in the specified value to the left by the number of bit positions
specified by num.
The Right Shift
The right shift operator, >>, shifts all of the bits in a value to the right a specified number
oftimes. Its general form is shown here: value >> num
Here, num specifies the number of positions to left-shift the value in value. That is, the
>>moves all of the bits in the specified value to the right by the number of bit positions
specified by num.

Example for Left shifting and Right shifting a byte value:


class ShiftBits
{
public static void main(String args[])
{
byte b=6;
int c,d;
c=b<<2; //left shift
d=b>>3; //right shift
[Link]("The left shift result is :"+c);
[Link]("The right shift result is :"+d);
}
}
Difference between >> (shift right) and >>>(shift right zero fill)
 There are two types of right shift operator in Java >> and >>>, former is known as
right shift and later is known as right shift with zero fill or simply unsigned right shift
operator in Java.
 Though both of them are known as bit shift operators and moves bits patterns towards
right hand side of a bit sequence, there is subtle difference between them. When we
use right shift operator i.e. ">>" it keeps sign bit intact i.e. if original number is
negative then it will remain negative even after right shift i.e. first or most significant
bit never lost, doesn't matter how many times you shift.
 On the other hand unsigned right shift operator ">>>" doesn't preserve sign of original
number and fills the new place with zero, that's why it's known as unsigned right shift
operator or simply right shift with zero fill.
22. Operator Precedence Rules and Associativity
The precedence rules are used to determine the priority in the case there are two
operators with different precedence. The Associativity rules are used to determine the order
of evaluation, in case two operators are having the same precedence. Associativity is two
types: Left to Right and Right to Left.
Table shows the order of precedence for Java operators, from highest to lowest.
Notice that the first row shows items that you may not normally think of as operators:
parentheses, square brackets, and the dot operator. Technically, these are called
separators, but they act like operators in an expression. Parentheses are used to alter the
precedence of an operation. Below table shows the Precedence of the Java Operators.

Note: The operators =,?:, ++, and – are having Right to Left Associativity. The remaining
Operators are having Left to Right Associativity.

Using Parentheses
Parentheses raise the precedence of the operations that are inside them. This is often
necessary to obtain the result you desire. For example, consider the following expression:
a >> b + 3
This expression first adds 3 to b and then shifts a right by that result. That is, this
expression
can be rewritten using redundant parentheses like this: a >> (b + 3)
However, if you want to first shift a right by b positions and then add 3 to that result,
you will need to parenthesize the expression like this:(a >> b) + 3
23. Control Statements
The control statements are used to control the flow of execution of statements in a
program. The control statements in Java are categorized into 3 categories:
1. Conditional/Selection Statements/Decision Making Statements
2. Iteration Statements/Loops/Repetative
3. Jump Statements or Unconditional Statements

1. Conditional Statements /Selection Statements/Decision Making Statements:


Conditional statements are used to decide the flow of execution based on different
conditions. If a condition is true, you can perform one action and if the condition is false, you
can perform another action. To perform different actions on different decisions, we can use
conditional statements in Java. In Java, we have the following conditional statements:
i) if statement
ii) if… else statement
iii) Nested if-else statement
iii) else-if ladder statement or if … else if statement
iv) switch statement
i) if statement:
It is a powerful two way decision making statement and it is used to control the flow of
execution of statements. if statement is the most simple decision-making statement. It is used
to decide whether a certain statement or block of statements will be executed or not. The
general form of if statement is as follows:
if (conditional expression)
{
//Code to executed if condition is true
}
Here, first condition is evaluated. If condition is true then statements are executed. Otherwise,
the control is transferred out of if statement.

Example for simple if statement:


import [Link].*;
classs IfExample
{
public static void main(String args[])
{
int n;
[Link]("Enter the value of n");
DataInputStream dis=new DataInputStream([Link]);
n=[Link]([Link]());
if (n > 20)
[Link](n+”is greater than 20");
}
}
ii) if… else statement
It is used to execute some code if a condition is true and another code if the condition
is not true. The syntax for if-else statement is given below.
if(condition)
{
statement1; //content to be executed if condition is true
}
else
{
statement2; //code to be executed if condition is false
}
Here, the statements inside the block can be single statement or multiple statements.
The conditional expression is any expression that returns the Boolean value. If the condition
is true then block-1 statements are executed. Otherwise block-2 statements are executed. But
both blocks statements are not executed at the same time.
Example: Write a java program to find whether the given number is even or odd?
import [Link].*;
public class EvenOdd
{
public static void main(String args[]) throws IOException
{
int num;
[Link]("Enter the Number:");
DataInputStream dis=new DataInputStream([Link]);
num=[Link]([Link]());
if(num%2==0)
{
[Link](num+" "+"is the Even Number");
}
else
{
[Link](num+" "+"is the Odd Number");
}
} }
Output:

iii) Nested if-else statement


When a series of conditions are involved, we can use more than on if-else statement in nested
form. The general form of nested if-else statement is as follows:
if(condition 1)
{
if(condition 2)
{
block-1 Statements;
}
else
{
block-2 Statements;
}
}
else
{
block-3 Statements;
}
• If condition1 is true then second condition is performed. If second condition is true
then statement-1 will be executed. If condition2 is false then statement-2 will be
executed. If condition1 is false then statement-3 will be executed and then the control
is transferred to the out of the if statement.
For example, Find the biggest number from the given 3 integer numbers.
import [Link].*;
public class FindBigNum
{
public static void main(String a[])
{
int a , b , c ;
Scanner in = new Scanner([Link]);
[Link]("Enter a valiue");
a = [Link]();
[Link]("Enter b valiue");
b = [Link]();
[Link]("Enter c valiue");
c = [Link]();
if(a>b)
{
if(a>c)
{
[Link](a+” “+” is Biggest Number”);
}
else
{
[Link](c+” “+” is Biggest Number”);
}
}
else
{
if(b>c)
{
[Link](b+” “+” is Biggest Number”);
}
else
{
[Link](c+” “+” is Biggest Number”);
}
}
}}
iv) The if-else-if Ladder or if … else if statement
• Java if-else-if is a special statement used to combine multiple if-else statements. It
evaluates the code only if condition is true from several expressions. To test multiple
conditions, we have to use else-if ladder. The syntax is as follows:
if(condition1)
{
block-1 Statements; //if condition1 is true
}
else if(condition2)
{
block-2 Statements; //if condition2 is true
}
……..
else
{
default block Statements; // if no condition is true
}
• The if statements are executed from the top down. As soon as one of the conditions
controlling the if is true, the statement associated with that if is executed, and the rest
of the ladder is bypassed. If none of the conditions is true, then the default block
statement will be executed.
Example: Write a Java Program to test whether a given character is Vowel or
Consonant?
import [Link].*;
class VowelConsonant
{
public static void main(String args[]) throws IOException
{
char ch;
[Link](" Enter the Character:");
//[Link]() in java is used to read the input from the user.
ch=(char)[Link]();
if(ch=='a')
[Link]("Vowel");
else if(ch=='e')
[Link]("Vowel");
else if(ch=='i')
[Link]("Vowel");
else if(ch=='o')
[Link]("Vowel");
else if(ch=='u')
[Link]("Vowel");
else
[Link]("Consonant");
}
}
iv) Switch statement:
The switch statement is a multi-way decision maker. It is used to execute one code
from multiple expressions. It is just like if..else..if statement but it is convenient
than if..else..if because it can be used with numbers, characters etc. Use this statement to
select one of many blocks of code to be executed. The syntax for switch statement is as
follows;
switch(expression)
{
case value1: block-1 statement(s);
break;
case value2: block-2 statement(s);
break;
................
case label-n: block-n statement(s);
break;
default: default-block statement(s);
}
The switch statement test the value of a variable or expression. The expression is an
integer or character. The expression must be of type byte, short, int, or char; each of the
values specified in the case statements must be of a type compatible with the expression. This
statement within the group must be preceded by one or more case labels and case labels end
with a colon(:) operator.
If the expression value is equal to case label-1 then block-1 statements will be executed.
If the expression value is equal to case label-2 then block-2 statements will be executed. If
the expression value does not equal to any case label then default block statements will be
executed. There is no need to put the braces around these blocks. The break statement is used
to break the particular case and the control is transferred to the out of the switch statement.

Example,
import [Link].*;
public class SwitchExample {
public static void main(String[] args)
{
Scanner in = new Scanner([Link]);
[Link]("Enter day value");
int day = [Link]();
String strday;
switch (day)
{ // Switch statement with int data type
case 1: strday = "Monday";
break;
case 2: strday = "Tuesday";
break;
case 3: strday = "Wednesday";
break;
case 4: strday = "Thursday";
break;
case 5: strday = "Friday";
break;
case 6: strday = "Saturday";
break;
case 7: strday = "Sunday";
break;
default: strday = "Invalid day"; // Default case
}
[Link](strday);
}}
Nested-Switch Statement:
Nested-Switch statements refers to Switch statements inside of another Switch Statements.
You can use a switch as part of the statement sequence of an outer switch. This is called a
nested switch.
Syntax:
switch(expression1) //outer switch
{
case 1: switch(expression2) // inner switch or // Nested switch
{
case 4: //statement sequence
break;
case 5: //statement sequence
break;
default: //code to be executed if expression2 doesn't
match with any cases
} //end of inner switch
break;
case 2: //statement sequence
break;
default: //code to be executed if expression2 doesn‘t match with any cases
} //end of outer switch
Example, output:
import [Link];
public class NestedSwitchExample {
public static void main(String args[]) {
Scanner in = new Scanner([Link]);
[Link]("Enter Branch Code");
int BranchCode = [Link]();
char branch = 'C'; //C - CSE, E - ECE, A - AI&ML
switch( BranchCode ) //outer switch
{
case 1: switch( branch ) //inner switch 1
{
case 'C‘: [Link](" Java Programig, Web Technologies");
break;
case 'E‘:[Link]("Micro processors, Embedded Systems");
break;
case 'A‘: [Link]("Machine Learning, Artficial Intelligence");
break;
} //end of inner switch 1
break;
case 2: switch( branch ) //inner switch2
{
case 'C‘: [Link]("Computer Organization, Mean Stack Technologies");
break;
case 'E': [Link]("VLSI, Microelectronics");
break;
case 'A': [Link]("DBMS, CYBER SECURITY");
break;
} //end of inner switch 2
break;
default: [Link]("Invalid Branch");
} } } //end of outer switch
2. Loops (Iteration Statements):
The loop control statements are used to execute a group of statements repetitively.
Java provides three ways for executing the loops. There are three types of loops in Java.
i. while loop
ii. do-while loop
iii. for loop
i. while loop
The while loop executes a block of code repeatedly until the condition is FALSE.
Once the condition gets FALSE, it exits from the body of loop. The while loop is called
an Entry control loop because the condition is checked before entering the loop body. This
means that first the condition is checked. If the condition is true, then block of code will be
executed. The general form of the while statement is as follows:
while(condition)
{
// body of loop
increment or decrement statement
}
• The condition can be any Boolean expression. The body of the loop will be executed
as long as the conditional expression is true. When condition becomes false, control
passes to the next line of code immediately following the loop. The curly braces are
unnecessary if only a single statement is being repeated.
For example, Write a Java program to check whether given number is Prime number
or not using while loop.
//A prime number is a positive integer and that is divisible only by itself and 1
import [Link].*;
public class PrimeNumCheck
{
public static void main(String args[])
{
int i=1, num, k=0;
Scanner in = new Scanner([Link]);
[Link]("Enter the Number:"); output:
num =[Link]();
while(i<=num)
{
if(num%i==0)
k++;
i++;
}
if(k==2)
[Link](num+"is a prime number");
else
[Link](num+"is not a prime number");
}
}

ii. do-while loop


The do-while statement is related to the while statement, but the test for completion is
logically at the end rather than the beginning of the loop construct. The body of a do-while
construct is always executed at least once. The do-while loop is called an exit control loop
structure.
The syntax of a do-while statement is as follows:
do
{
Statement or compound statement;
increment or decrement statement
} while (condition);
Each iteration of the do-while loop first executes the body of the loop and then evaluates the
conditional expression. If this expression is true, the loop will repeat. Otherwise, the loop
terminates. As with all of Java’s loops, condition must be a Boolean expression.
Example: Write a Java program to find the sum of n natural numbers using do-while
loop
The natural numbers are the numbers that include all the positive integers from 1 to
infinity. For example, 1, 2, 3, 4, 5, ......, n. When we add these numbers together, we get
the sum of natural numbers.
import [Link].*;
class NaturalNumbersSum
{
int i=1,sum=0;
void display(int num)
{ output:
do
{
sum+=i;
i++;
}while(i<=num);
[Link]("SUM is: "+sum);
}
}
public class NaturalNumbers
{
public static void main(String args[])
{
NaturalNumbersSum s1 = new NaturalNumbersSum();
Scanner in = new Scanner([Link]);
[Link]("Enter the range of the Number:");
int num =[Link]();
[Link](num);
}
}
iii. for loop
The for statement is used to execute a group of statements repeatedly based on some
condition. The for loop is also called as entry control loop structure. The syntax of a for
statement is as follows:
for(initialization; condition; iteration)
{
//body of the loop
}
• The for loop operates as follows.
When the loop first starts, the initialization portion of the loop is executed. Generally,
this is an expression that sets the value of the loop control variable, which acts as a
counter that controls the loop. It is important to understand that the initialization
expression is only executed once.
Next, condition is evaluated. This must be a Boolean expression. It usually tests the loop
control variable against a target value. If this expression is true, then the body of the loop is
executed. If it is false, the loop terminates. But condition is only one condition.
Third, Increment/Decrement is used to increment /decrement the loop control variable
value by one.
import [Link].*; // Find the factorial of a given number
class FactorialNum
{
int i=1,fact=1;
int factorial(int num)
{
for(i=1; i<=num; i++) output:
fact*=i;
return fact;
}
}
public class FactFind
{
public static void main(String args[]) {
FactorialNum f1 = new FactorialNum();
Scanner in = new Scanner([Link]);
[Link]("Enter the Number:");
int num =[Link]();
int f=[Link](num);
[Link]("Factorial of a geven number: "+f);
} }
Nested for loop:
Loops may be nested. One for loop inside another for loop is called as Nested for loop.
Syntax for Nested For loop:
for ( initialization; condition; increment/decrement) // outer loop
{
for ( initialization; condition; increment/decrement) // inner loop
{
// statement of inside loop
}
// statement of outer loop output:
}
Example for Nested for loop:
public class NestedForLoop
{
public static void main(String[] args)
{
int weeks = 2;
int days = 7;
for (int i = 1; i <= weeks; i++) // outer loop prints weeks
{
[Link]("Week: " + i);
for (int j = 1; j <= days; j++) // inner loop prints days
{
[Link](" Day: " + j);
}
}
} }
For–Each Version of the for Loop:
The Java for-each loop traverses the array or collection until the last element. For
each element, it stores the element in the variable and executes the body of the for-each loop.
The general form of the for-each version of the for is shown here:
for(type itr-var : collection)
{
statement-block
}
Here, type specifies the type and itr-var specifies the name of an iteration variable that
will receive the elements from a collection, one at a time, from beginning to end. The
collection being cycled through is specified by collection. There are various types of
collections that can be used with the for, but here, we can use the array type.
Example : Traversing the array elements using For-each loop : Output:
public class ForEach
{
public static void main(String args[])
{
int nums[] = { 2, 4, 6, 3, 5 }; // Array initialization
int sum = 0;
for(int x : nums) { // use for-each style for to display and sum the values
[Link](“Array Value is: " + x);
sum += x;
}
[Link]("Summation: " + sum);
}
}
Jump Statements or Unconditional statements:
Java supports three jump statements: break, continue, and return. These statements
transfer control to another part of your program. There are three Jump statements that are
provided in the Java programming language:
1. Break Statement
2. Continue Statement
3. Return Statement
1. Break Statement
In Java, the break statement has three uses. First, as you have seen, it terminates a
statement sequence in a switch statement. Second, it can be used to exit a loop. Third, it can
be used as civilized” form of goto statement.
Using break to terminate switch statement:
• By using break, you can terminates a statement sequence in a switch statement.
Example for break to terminate switch statement:
public class SwitchExample {
public static void main(String[] args) {
int number=20;
switch(number) {
case 10: [Link]("10");
break;
case 20: [Link]("20");
break;
case 30: [Link]("30");
break;
default:[Link]("Not in 10, 20 or 30"); //Default case statement
}
} }
Using break to Exit a Loop:
When a break statement is encountered inside a loop, the loop is terminated and
program control resumes at the next statement following the loop.
Example for break to Exit a Loop : output:
class BreakLoop i: 0
{ i: 1
public static void main(String args[]) i: 2
{ i: 3
for(int i=0; i<100; i++) i: 4
{ i: 5
if(i == 10) break; // terminate loop if i is 10 i: 6
[Link]("i: " + i); i: 7
} i: 8
[Link]("Loop complete."); i: 9
} Loop complete.
}

Using break as a Form of Goto


Java does not have a goto statement because it provides a way to branch in an
arbitrary and unstructured manner. This usually makes goto-ridden code hard to understand
and hard to maintain. The general form of the labeled break statement is shown here:
break label;
Most often, label is the name of a label that identifies a block of code. A label is any
valid Java identifier followed by a colon. Once you have labeled a block, you can then use
this label as the target of a break statement. When this form of break executes, control is
transferred out of the named block.
Example, Using break as a civilized form of goto.
class Break {
public class Break {
public static void main(String args[]) {
first: {
second: {
third: {
[Link]("Before the break.");
if(true) break second; // break out of second block
[Link]("This won't execute");
}
[Link]("This won't execute"); Output:
} Before the break.
[Link]("This is after second block."); This is after second block.
}
}}
2. continue statement
It is used to stop the current iteration and go back to continue with next iteration.
Sometimes it is useful to force an early iteration of a loop. That is, you might want to
continue running the loop but stop processing the remainder of the code in its body for this
particular iteration. In while and do-while loops, a continue statement causes control to be
transferred directly to the conditional expression that controls the loop. Syntax: continue;
Example for continue statement:
public class ContinueExample {
public static void main(String[] args) {
//for loop
for(int i=1;i<=10;i++)
{ output:
if(i==5)
{
continue; // it will skip the rest statement
}
[Link](i);
}
}
}

• continue may specify a label to describe which enclosing loop to continue. Here is an
example program that uses continue to print a triangular multiplication table for 0
through 5. Syntax : label: statement(s);
continue label;
Example, // Using continue with a label.
public class ContinueLabel { output:
public static void main(String args[]) {
outer: for (int i=0; i<5; i++)
{
for(int j=0; j<5; j++)
{
if(j > i)
{
[Link]();
continue outer;
}
[Link](“ " + (i * j));
}
}
} }
3. return statement
The return statement is used to explicitly return from a method. At any time in a
method, the return statement can be used to cause execution to branch back to the caller of
the method. Thus, the return statement immediately terminates the method in which it is
executed.
Syntax: return returnvalue;
Example for return statement:
class ReturnExample {
int compareNum(int x,int y)
{
if(x>y)
return x;
else
return y;
}}
public class ReturnDemo {
public static void main(String ar[]) {
ReturnExample obj = new ReturnExample();
int result = [Link](5,6);
[Link]("The biggest number among x and y is: " + result);
} }
ST. ANN’S COLLEGE OF ENGINEERING &TECHNOLOGY :: CHIRALA
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
FAQs
Subject : JAVA PROGRAMMING Year/Sem: II [Link] – II Sem
Academic Year: 2022-23 Regulation: R20

UNIT-1:
1. a) List and explain Java buzzwords. Which factors are making Java famous
Language?
b) What are the components of JAVA platform? Explain
2. a) What is the role and responsibility of JVM in program execution? With a neat
diagram, explain the Java Virtual Machine architecture.
b) Justify the validity of the statement “Byte code of Java gives high performance”.
3. a) Explain in detail the most significant features of JAVA programming.
b) Is Java a secure and robust language? Justify your answer.
c) Why Java is architectural neutral language?
d) How JAVA is a platform independent language?
4. a) Write a java program to illustrate the increment & decrement operators, shift
operators and ternary operator.
b) Demonstrate precedence rules and associativity with an example Java program.
5. a) Why ‘main()’ method is declared as public static in JAVA programming?
b) How to perform type casting in java? Differentiate it from primitive type
conversion with an example program.
6. a) What are the different primitive data types in java? Give their sizes in bits. How
they are different from reference data types?
b) How to use break and continue statements in java?
7. a)Write a java program to illustrate the usage of conditional statements and looping
statements.
b) Write a java program that inputs an integer, ‘n’ from the command line and
displays the string “1+2+3+…+n=sum” and also compute the sum.
8. a) Write the importance of command line arguments. Write a Java program which
accepts the input from keyboard to display Fibonacci series.
b) Write the purpose of static keyword in Java.
c) List out the characteristics of the static method.
9. a) Discuss the differences between Procedural Programming Language and
Object Oriented Programming language.
b) What is meant by byte code? Explain how Java is platform independent
10 a) Discuss any three OOP Principles with an example.
b) Describe the structure of a typical Java program with an example
11 a) List and explain the Tokens in the Java language.
b) Demonstrate Bitwise operators using a Java program.
12 a) List and explain the control statements with examples.
b) Demonstrate the operator precedence using a Java program
13 a) Explain various Key Words available in Java.
b) Discuss the rules in Automatic Type Promotion in Expressions.
14.a) Explain various Operators in Java.
b) Write a Java Program to test whether a given character is Vowel or Consonant.

You might also like