[go: up one dir, main page]

0% found this document useful (0 votes)
2 views40 pages

JAVA UNIT 1

This document provides an overview of Java programming, covering its structure, data types, variables, operators, control statements, and user input methods. It introduces key concepts such as Java applications, writing simple programs, and the use of command-line arguments and the Scanner class for user input. Additionally, it explains the various elements and tokens that make up Java programs, including keywords, identifiers, literals, and operators.

Uploaded by

buppalaiah.svist
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)
2 views40 pages

JAVA UNIT 1

This document provides an overview of Java programming, covering its structure, data types, variables, operators, control statements, and user input methods. It introduces key concepts such as Java applications, writing simple programs, and the use of command-line arguments and the Scanner class for user input. Additionally, it explains the various elements and tokens that make up Java programs, including keywords, identifiers, literals, and operators.

Uploaded by

buppalaiah.svist
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
You are on page 1/ 40

UNIT I

PROGRAM STRUCTURE IN JAVA


1.1 PROGRAM STRUCTURE IN JAVA:
1.1.1 Introduction
1.1.2 Writing Simple Java Programs
1.1.3 Elements or Tokens in Java Programs
1.1.4 Java Statements
1.1.5 Command Line Arguments
1.1.6 User Input to Programs
1.1.7 Escape Sequences
1.1.8 Comments
1.1.9 Programming Style.
1.2 DATA TYPES VARIABLES AND OPERATORS
1.2.1 Introduction Data Types in Java
1.2.2 Declaration of Variables Data Types
1.2.3 Type Casting
1.2.4 Scope of Variable Identifier
1.2.5 Literal Constants
1.2.6 Symbolic Constants
1.2.7 Formatted Output with printf() Method
1.2.8 Static Variables and Methods
1.2.9 Attribute Final
1.2.10 Introduction to Operators
1.2.11 Precedence and Associativity of Operators
1.2.12 Assignment Operator ( = )
1.2.13 Basic Arithmetic Operators
1.2.14 Increment (++) and Decrement (--) Operators
1.2.15 Ternary Operator
1.2.16 Relational Operators
1.2.17 Boolean Logical Operators
1.2.18 Bitwise Logical Operators.
1.3 CONTROL STATEMENTS:
1.3.1 Introduction
1.3.2 if Expression
1.3.3 Nested if Expressions
1.3.4 if–else Expressions
1.3.5 Switch Statement
1.3.6 Iteration Statements
1.3.7 while Expression
1.3.8 do –while Loop
1.3.9 for Loop
1.3.10 Nested for Loop
1.3.11 For–Each for Loop
1.3.12 Break Statement
1.3.13 Continue Statement.

JAVA PROGRAMMING 1 KKVPRASAD@CSE


1.1 PROGRAM STRUCTURE IN JAVA
1.1.1 INTRODUCTION
Java is a programming language and a platform. Java is a high level, robust, object-oriented and
secure programming language.
Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the year 1995.
James Gosling is known as the father of Java. Before Java, its name was Oak initially it was designed for
small, embedded systems in electronic appliances like set-top boxes. Firstly, it was called “Green talk” by
James Gosling, and the file extension was .gt. After that, it was called Oak and was developed as a part of
the Green project. Since Oak was already a registered company, so James Gosling and his team changed the
name from Oak to Java.
Platform: Any hardware or software environment in which a program runs, is known as a platform. Since
Java has a runtime environment (JRE) and API, it is called a platform.

Types of Java Applications:


There are mainly 4 types of applications that can be created using Java programming:
1) Standalone Application
Standalone applications are also known as desktop applications or window-based applications. These
are traditional software that we need to install on every machine. Examples of standalone application are
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 a dynamic page is called a web application.
Currently, Servlet, JSP, Struts, Spring, Hibernate, 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. is called an enterprise
application. It has advantages like high-level security, load balancing, and clustering. In Java, EJB is used
for creating enterprise applications.
4) Mobile Application
An application which is created for mobile devices is called a mobile application. Currently, Android
and Java ME are used for creating mobile applications.

1.1.2 WRITING SIMPLE JAVA PROGRAMS


The requirement for executing simple Java Program
 Install the JDK if you don't have installed it, download the JDK and install it.
 Set path of the jdk/bin directory https://www.javatpoint.com/how-to-set-path-in-java
 Create the Java program https://www.javatpoint.com/how-to-run-java-program-in-cmd-using-
notepad
 Compile and run the Java program
Executing Simple Java Program

JAVA PROGRAMMING 2 KKVPRASAD@CSE


Simple Java Program
class Simple{
public static void main(String args[])
{
System.out.println("Java Programming");
}
}
Save the above file as Simple.java.
To compile: javac Simple.java
To execute: java Simple
Output:
Java Programming

Parameters used in First Java Program


Let's see what is the meaning of class, public, static, void, main, String[], System.out.println().
 class keyword is used to declare a class in Java.
 public keyword is an access modifier that represents visibility. It means it is visible to all.
 static is a keyword. If we declare any method as static, it is known as the static method. The core
advantage of the static method is that there is no need to create an object to invoke the static method.
The main() method is executed by the JVM, so it doesn't require creating an object to invoke the
main() method. So, it saves memory.
 void is the return type of the method. It means it doesn't return any value.
 main represents the starting point of the program.
 String[] args or String args[] is used for command line argument.
 System.out.println() is used to print statement. Here, System is a class, out is an object of the
PrintStream class, println() is a method of the PrintStream class. We will discuss the internal
working of System.out.println() statement in the coming section.

1.1.3 ELEMENTS OR TOKENS IN JAVA PROGRAMS


 In Java, the program contains classes and methods. Further, the methods contain the expressions and
statements required to perform a specific operation.
 These statements and expressions are made up of tokens. The tokens are the small building blocks of
a Java program that are meaningful to the Java compiler.
 The Java compiler breaks the line of code into text (words) is called Java tokens. These are the
smallest element of the Java program.
 The Java compiler identified these words as tokens. These tokens are separated by the delimiters. It
is useful for compilers to detect errors. Remember that the delimiters are not part of the Java tokens.
token <= identifier | keyword | separator | operator | literal | comment

For example, consider the following code.


public class Demo
{
public static void main(String args[])
{
System.out.println("javatpoint");
}
}
In the above code snippet, public, class, Demo, {, static, void, main, (, String, args, [, ], ), System, ., out,
println, javatpoint, etc. are the Java tokens.

JAVA PROGRAMMING 3 KKVPRASAD@CSE


Types of Tokens
1. Keywords: These are the pre-defined reserved words of any programming language.
Each keyword has a special meaning.
2. Identifier: Identifiers are used to name a variable, constant, function, class, and array. It usually
defined by the user. It uses letters, underscores, or a dollar sign as the first character.
3. Literals: In programming literal is a notation that represents a fixed value (constant) in the source
code. It can be categorized as an integer literal, string literal, Boolean literal, etc. It is defined by the
programmer. Once it has been defined cannot be changed. types of literals are as follows: Integer,
Floating Point, Character, String, Boolean
4. Operators: In programming, operators are the special symbol that tells the compiler to perform a
special operation. Java provides different types of operators that can be classified according to the
functionality they provide. There are eight types of operators in Java.
5. Separators: The separators in Java is also known as punctuators. There are nine separators in Java,
are as follows: separator <= ; | , | . | ( | ) | { | } | [ | ]
6. Comments: Comments allow us to specify information about the program inside our Java code. Java
compiler recognizes these comments as tokens but excludes it form further processing. The Java
compiler treats comments as whitespaces.

1.1.4 JAVA STATEMENTS

 Statements are roughly equivalent to sentences in natural languages. In general, statements are just
like English sentences that make valid sense.
 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
Statement Description
Empty statement These are used during program development.
Variable declaration It defines a variable that can be used to store the values.
statement
Labeled statement A block of statements is given a label. The labels should notbe keywords,
previously used labels, or already declared local variables.
Expression statement Most of the statements come under this category. There are seven types of
expression statements that include assignment, method call and allocation,
pre-increment, postincrement, pre-decrement, and post decrement statements.
Control statement This comprises selection, iteration, and jump statements.
Selection statement In these statements, one of the various control flows is selected when a
certain condition expression is true.
Iteration statement These involve the use of loops until some condition for the termination of
loop is satisfied. There are three types ofiteration statements that make use of
while, do, and for.
Jump statement In these statements, the control is transferred to the beginning or end of the
current block or to a labeled statement. There are four types of Jump
statements including break, continue, return, and throw.
Synchronization statement These are used with multi-threading
Guarding statement These are used to carry out the code safely that may cause exceptions
These statements make use of try and catch block, and finally
JAVA PROGRAMMING 4 KKVPRASAD@CSE
Some of the Java Statements are as follows:
 Expression Statements
 Declaration Statements
 Control Statements
Expression Statements
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.
There are three types of expressions in Java:
 Expressions that produce a value. For example, (6+9), (9%2), (pi*radius) + 2. Note that the
expression enclosed in the parentheses will be evaluate first, after that rest of the expression.
 Expressions that assign a value. For example, number = 90, pi = 3.14.
 Expression that neither produces any result nor assigns a value. For
example, increment or decrement a value by using increment or decrement operator
respectively, method invocation, etc. These expressions modify the value of a variable or state
(memory) of a program. For example, count++, int sum = a + b; The expression changes only the
value of the variable sum. The value of variables a and b do not change, so it is also a side effect.
Declaration Statements
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;
boolean flag;
String message;
Also, we can initialize a value to a variable. For example:
int quantity = 20;
boolean flag = false;
String message = "Hello";
Control Statement
Control statements decide the flow (order or sequence of execution of statements) of a Java program.
In Java, statements are parsed from top to bottom. Therefore, using the control flow statements can interrupt
a particular section of a program based on a certain condition.
There are the following types of control statements:
1. Conditional or Selection Statements
 if Statement
 if-else statement
 if-else-if statement
 switch statement
2. Loop or Iterative Statements
 for Loop
 while Loop
 do-while Loop
 for-each Loop
3. Flow Control or Jump Statements
 return
 continue
 Break

JAVA PROGRAMMING 5 KKVPRASAD@CSE


1.1.5 COMMAND LINE ARGUMENTS
 The java command-line argument is an argument i.e. passed at the time of running the java program.
 The arguments passed from the console can be received in the java program and it can be used as an
input.
 So, it provides a convenient way to check the behavior of the program for the different values. You
can pass N (1,2,3 and so on) numbers of arguments from the command prompt.
Simple example of command-line argument in java

In this example, we are receiving only one argument and printing it.To run this java program, you
must pass at least one argument from the command prompt.
class CommandLineExample{
public static void main(String args[]){
System.out.println("Your first name is: "+args[0]);
}
}
compile by > javac CommandLineExample.java
run by > java CommandLineExample Krishna
Output:
Your first argument is: Krishna

Example of command-line argument that prints all the values


In this example, we are printing all the arguments passed from the command-line. For this purpose,
we have traversed the array using for loop
class A
{
public static void main(String args[]){
for(int i=0;i<args.length;i++)
System.out.println(args[i]);
}
}
compile by > javac A.java
run by > java A Krishna Cse 08
Output: Krishna
Cse
08

1.1.6 USER INPUT TO PROGRAMS


 Java Scanner class allows the user to take input from the console. It belongs to java.util package.
 It is used to read the input of primitive types like int, double, long, short, float, and byte. It is the
easiest way to read input in Java program.
Syntax:
Scanner sc=new Scanner(System.in);

The above statement creates a constructor of the Scanner class having System.inM as an argument.
It means it is going to read from the standard input stream of the program. The java.util package should be
import while using Scanner class.

JAVA PROGRAMMING 6 KKVPRASAD@CSE


Methods of Java Scanner Class
Method Description
int nextInt() It is used to scan the next token of the input as an integer.
float nextFloat() It is used to scan the next token of the input as a float.
double nextDouble() It is used to scan the next token of the input as a double.
byte nextByte() It is used to scan the next token of the input as a byte.
String nextLine() Advances this scanner past the current line.
boolean nextBoolean() It is used to scan the next token of the input into a boolean value.
long nextLong() It is used to scan the next token of the input as a long.
short nextShort() It is used to scan the next token of the input as a Short.
BigInteger nextBigInteger() It is used to scan the next token of the input as a BigInteger.
BigDecimal nextBigDecimal() It is used to scan the next token of the input as a BigDecimal.

Example of integer input from user


The following example allows user to read an integer form the System.in.
import java.util.*;
class UserInputDemo {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in); //System.in is a standard input stream
System.out.print("Enter first number- ");
int a= sc.nextInt();
System.out.print("Enter second number- ");
int b= sc.nextInt();
System.out.print("Enter third number- ");
int c= sc.nextInt();
int d=a+b+c;
System.out.println("Total= " +d);
} }
Output:

Example of String Input from user


Let's see another example, in which we have taken string input.
import java.util.*;
class UserInputDemo1 {
public static void main(String[] args) {
Scanner sc= new Scanner(System.in); //System.in is a standard input stream
System.out.print("Enter a string: ");
String str= sc.nextLine(); //reads string
System.out.print("You have entered: "+str);
} }
Output:

JAVA PROGRAMMING 7 KKVPRASAD@CSE


1.1.7 ESCAPE SEQUENCES
 In Java, if a character is preceded by a backslash (\) is known as Java escape sequence or escape
characters. It may include letters, numerals, punctuations, etc.
 Remember that escape characters must be enclosed in quotation marks (“”). These are the valid
character literals.
List of Java Escape Characters
In Java, there is a total of eight escape sequences that are described in the following table.

Escape Characters Description


\t It is used to insert a tab in the text at this point.
\' It is used to insert a single quote character in the text at this point.
\" It is used to insert a double quote character in the text at this point.
\r It is used to insert a carriage return in the text at this point.
\\ It is used to insert a backslash character in the text at this point.
\n It is used to insert a new line in the text at this point.
\f It is used to insert a form feed in the text at this point.
\b It is used to insert a backspace in the text at this point.

Using Escape Characters in Java Program - EscapeCharaterExample.java


public class EscapeCharaterExample {
public static void main(String args[]) {
String str = "Andrew\tGarfield";
System.out.println(str);
//it inserts a New Line
String str1 = "the best way\nto communicate \nan idea \nis to act it out";
System.out.println(str1);
//it insert a backslash
String str2 = "And\\Or";
System.out.println(str2);
//it insert a Carriage
String str3 = "Carriage\rReturn";
System.out.println(str3);
//it prints a single quote
String str4 = "Wall Street\'s";
System.out.println(str4);
//it prints double quote
//String str5 = "New\'Twilight'Line";
String str5 = "'JavaTpoint'";
System.out.println(str5);
} }
Output:
Andrew Garfield
the best way
to communicate
an idea
is to act it out
And\Or
Carriage
Return
Wall Street's
'JavaTpoint'

JAVA PROGRAMMING 8 KKVPRASAD@CSE


1.1.8 COMMENTS
 The Java comments are the statements in a program that are not executed by the compiler and
interpreter.
Why do we use comments in a code?
 Comments are used to make the program more readable by adding the details of the code.
 It makes easy to maintain the code and to find the errors easily.
 The comments can be used to provide information or explanation about the variable, method, class,
or any statement.
 It can also be used to prevent the execution of program code while testing the alternative code.
Types of Java Comments
There are three types of comments in Java.
1. Single Line Comment
2. Multi Line Comment
3. Documentation Comment
1) Java Single Line Comment
The single-line comment is used to comment only one line of the code. It is the widely used and
easiest way of commenting the statements.
Single line comments starts with two forward slashes (//). Any text in front of // is not executed by Java.
Syntax:
//This is single line comment
2) Java Multi Line Comment
The multi-line comment is used to comment multiple lines of code. It can be used to explain a
complex code snippet or to comment multiple lines of code at a time (as it will be difficult to use single-line
comments there).
Multi-line comments are placed between /* and */. Any text between /* and */ is not executed by Java.
Syntax:
/*
This
is
multi line
comment
*/
3) Java Documentation Comment
Documentation comments are usually used to write large programs for a project or software
application as it helps to create documentation API. These APIs are needed for reference, i.e., which classes,
methods, arguments, etc., are used in the code.
To create documentation API, we need to use the javadoc tool. The documentation comments are placed
between /** and */.
Syntax:
/**
*
*We can use various tags to depict the parameter
*or heading or author name
*We can also use HTML tags
*
*/

JAVA PROGRAMMING 9 KKVPRASAD@CSE


1.1.9 PROGRAMMING STYLE

 Programming style refers to the technique used in writing the source code for a computer program.
 Most programming styles are designed to help programmers quickly read and understands the
program as well as avoid making errors.
 The goal of good programming style is to provide understandable, straightforward, elegant code.
 The programming style used in a various program may be derived from the coding standards or code
conventions of a company or other computing organization, as well as the preferences of the actual
programmer.
Some general rules or guidelines in respect of programming style:
1. Clarity and simplicity of Expression: The programs should be designed in such a manner so that
the objectives of the program is clear.
2. Naming: In a program, you are required to name the module, processes, and variable, and so on.
Care should be taken that the naming style should not be cryptic and non-representative.
For Example:
a = 3.14 * r * r
area of circle = 3.14 * radius * radius;
3. Control Constructs: It is desirable that as much as a possible single entry and single exit constructs
used.
4. Information hiding: The information secure in the data structures should be hidden from the rest of
the system where possible. Information hiding can decrease the coupling between modules and make
the system more maintainable.
5. Nesting: Deep nesting of loops and conditions greatly harm the static and dynamic behavior of a
program. It also becomes difficult to understand the program logic, so it is desirable to avoid deep
nesting.
6. User-defined types: Make heavy use of user-defined data types like enum, class, structure, and
union. These data types make your program code easy to write and easy to understand.
7. Module size: The module size should be uniform. The size of the module should not be too big or
too small. If the module size is too large, it is not generally functionally cohesive. If the module size
is too small, it leads to unnecessary overheads.
8. Module Interface: A module with a complex interface should be carefully examined.
9. Side-effects: When a module is invoked, it sometimes has a side effect of modifying the program
state. Such side-effect should be avoided where as possible.

JAVA PROGRAMMING 10 KKVPRASAD@CSE


1.2 DATA TYPES, VARIABLES AND OPERATORS
1.2.1 INTROCUTION TO DATA TYPES
 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: The primitive data types include boolean, char, byte, short, int, long, float
and double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.

Java Primitive Data Types:


In Java language, primitive data types are the building blocks of data manipulation. These are the
most basic data types available in Java language. There are 8 types of primitive data types:
 boolean data type
 byte data type
 char data type
 short data type
 int data type
 long data type
 float data type
 double data type

Data Type Default Value Default size


boolean false 1 bit
char '\u0000' 2 byte
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
float 0.0f 4 byte
double 0.0d 8 byte
Boolean Data Type
The Boolean data type is used to store only two possible values: true and false. This data type is used
for simple flags that track true/false conditions.
The Boolean data type specifies one bit of information, but its "size" can't be defined precisely.
Example:
Boolean one = false
Byte Data Type
The byte data type is an example of primitive data type. It isan 8-bit signed two's complement
integer. Its value-range lies between -128 to 127 (inclusive). Its minimum value is -128 and maximum value
is 127. Its default value is 0.
The byte data type is used to save memory in large arrays where the memory savings is most required. It
saves space because a byte is 4 times smaller than an integer. It can also be used in place of "int" data type.
Example:
byte a = 10, byte b = -20
Short Data Type
The short data type is a 16-bit signed two's complement integer. Its value-range lies between -32,768
to 32,767 (inclusive). Its minimum value is -32,768 and maximum value is 32,767. Its default value is 0.
The short data type can also be used to save memory just like byte data type.
Example:
short s = 10000, short r = -5000

JAVA PROGRAMMING 11 KKVPRASAD@CSE


Int Data Type
The int data type is a 32-bit signed two's complement integer. Its value-range lies between -
2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value is - 2,147,483,648and
maximum value is 2,147,483,647. Its default value is 0.
The int data type is generally used as a default data type for integral values unless if there is no problem
about memory.
Example:
int a = 100000, int b = -200000
Long Data Type
The long data type is a 64-bit two's complement integer. Its value-range lies between -
9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)(inclusive). Its minimum value is
- 9,223,372,036,854,775,808and maximum value is 9,223,372,036,854,775,807. Its default value is 0. The
long data type is used when you need a range of values more than those provided by int.
Example:
long a = 100000L, long b = -200000L
Float Data Type
The float data type is a single-precision 32-bit IEEE 754 floating point.Its value range is unlimited. It
is recommended to use a float (instead of double) if you need to save memory in large arrays of floating
point numbers. The float data type should never be used for precise values, such as currency. Its default
value is 0.0F.
Example:
float f1 = 234.5f
Double Data Type
The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range is
unlimited. The double data type is generally used for decimal values just like float. The double data type
also should never be used for precise values, such as currency. Its default value is 0.0d.
Example:
double d1 = 12.3
Char Data Type
The char data type is a single 16-bit Unicode character. Its value-range lies between '\u0000' (or 0) to
'\uffff' (or 65,535 inclusive).The char data type is used to store characters.
Example:
char letterA = 'A'

1.2.2 DECLARATION OF VARIABLES DATA TYPES


 Java programming language requires variables to operate and handle data. Java creates several
variables as per data format and data types.
 The variable declaration means creating a variable in a program for operating different information.
 The Java variable declaration creates a new variable with required properties. The programming
language requires four basic things to declare a variable in the program.
Data-type Variable name = Initial value;
Data-type: It represent the type of value variable.
Variable name: The Java variable declaration requires a unique name. We prefer to declare small and
understandable variable names.
Initial value: Java language requires the initial value of the variable. Declare variable with initial value does
not necessary in the main class. We must assign the initial value in the default constructor. The "final
variable" needs to declare the initial value.
Semicolon: The semicolon represents the end of the variable declaration statement.
Variable Declaration
There are two ways to declare a variable in Java. The first method is to assign the initial value to the
variable. The second method declares variable without initial value.
JAVA PROGRAMMING 12 KKVPRASAD@CSE
Java Variable Declaration Example: With Initialization:
Create several variables with the different data formats. Here, we can use int, String, Boolean and other data
types.
 Create variables with required data types in the default method.
 Use variable name and its value.
 Return this value in the method as per data format.
CreateVariable.java
public class CreateVariable {
public static void main(String[] args) {
//variable declaration
int student_id = 10;
String student_name = "Java coder";
double numbers = 3.21;
Boolean shows = true;
System.out.println("Name:" +student_name+ "\nAge:" +student_id);
System.out.println("Number:" +numbers+ "\nBoolean:" +shows);
} }
Output:

Here, the output displays several types of variable values. Java variable declaration is necessary to
allocate data memory and display relevant data.
Java Variable Declaration Example: Without Initialization
Java language needs to create multiple variables with different data formats. Here, Java requires int,
float, string, boolean, and other data types.
 Create variable in the default method.
 Initialize value with the respective variable name and data type.
 Then return value in the method.
DeclareVariable.java
public class DeclareVariable {
public static void main(String[] args) {
int student_id;
String student_name;
double numbers;
Boolean shows;
float nan;
student_id = 21;
student_name = "java programmer";
numbers = 45.22;
shows = false;
nan= 6.8f;
System.out.println( "Name:" +student_name+ "\n Age:" +student_id);
System.out.println( "Number:" +numbers+ "\n Boolean:" +shows);
System.out.println( "float:" +nan);
} }
Output:

JAVA PROGRAMMING 13 KKVPRASAD@CSE


1.2.3 TYPE CASTING
 In Java, type casting is a method or process that converts a data type into another data type in both
ways manually and automatically.
 The automatic conversion is done by the compiler and manual conversion performed by the
programmer. In this section, we will discuss type casting and its types with proper examples.

Types of Type Casting


There are two types of type casting:
 Widening Type Casting
 Narrowing Type Casting
Widening Type Casting
Converting a lower data type into a higher one is called widening type casting. It is also known
as implicit conversion or casting down. It is done automatically. It is safe because there is no chance to
lose data. It takes place when:
 Both data types must be compatible with each other.
 The target type must be larger than the source type.
byte -> short -> char -> int -> long -> float -> double

For example, the conversion between numeric data type to char or Boolean is not done
automatically. Also, the char and Boolean data types are not compatible with each other. Let's see an
example.
WideningTypeCastingExample.java
public class WideningTypeCastingExample
{
public static void main(String[] args)
{
int x = 7;
//automatically converts the integer type into long type
long y = x;
//automatically converts the long type into float type
float z = y;
System.out.println("Before conversion, int value "+x);
System.out.println("After conversion, long value "+y);
System.out.println("After conversion, float value "+z);
} }
Output
Before conversion, the value is: 7
After conversion, the long value is: 7
After conversion, the float value is: 7.0
Narrowing Type Casting
Converting a higher data type into a lower one is called narrowing type casting. It is also known
as explicit conversion or casting up. It is done manually by the programmer. If we do not perform casting
then the compiler reports a compile-time error.
double -> float -> long -> int -> char -> short -> byte
JAVA PROGRAMMING 14 KKVPRASAD@CSE
In the following example, we have performed the narrowing type casting two times. First, we have
converted the double type into long data type after that long data type is converted into int type.
NarrowingTypeCastingExample.java
public class NarrowingTypeCastingExample {
public static void main(String args[])
{
double d = 166.66;
//converting double data type into long data type
long l = (long)d;
//converting long data type into int data type
int i = (int)l;
System.out.println("Before conversion: "+d);
//fractional part lost
System.out.println("After conversion into long type: "+l);
//fractional part lost
System.out.println("After conversion into int type: "+i);
}
}
Output
Before conversion: 166.66
After conversion into long type: 166
After conversion into int type: 166

1.2.4 SCOPE OF VARIABLE IDENTIFIER


 In programming, scope of variable defines how a specific variable is accessible within the program
or across classes.
 In programming, a variable can be declared and defined inside a class, method, or block. It defines the scope
of the variable i.e. the visibility or accessibility of a variable.
 Variable declared inside a block or method are not visible to outside. If we try to do so, we will get a
compilation error. Note that the scope of a variable can be nested.
 We can declare variables anywhere in the program but it has limited scope.
 A variable can be a parameter of a method or constructor.
 A variable can be defined and declared inside the body of a method and constructor.
 It can also be defined inside blocks and loops.
 Variable declared inside main() function cannot be accessed outside the main() function

Demo.java
public class Demo {
//instance variable
String name = "Andrew";
//class and static variable
static double height= 5.9;
public static void main(String args[]) {
//local variable
int marks = 72;
}
}

JAVA PROGRAMMING 15 KKVPRASAD@CSE


In Java, there are three types of variables based on their scope:
1. Member Variables (Class Level Scope)
2. Local Variables (Method Level Scope)

Member Variables (Class Level Scope)


These are the variables that are declared inside the class but outside any function have class-level
scope. We can access these variables anywhere inside the class. Note that the access specifier of a member
variable does not affect the scope within the class. Java allows us to access member variables outside the
class with the following rules:
Access Modifier Package Subclass Word
public Yes Yes Yes
protected Yes Yes No
private No No No
default Yes No No

VariableScopeExample1.java
public class VariableScopeExample1
{
public static void main(String args[])
{
int x=10;
{
//y has limited scope to this block only
int y=20;
System.out.println("Sum of x+y = " + (x+y));
}
//here y is unknown
y=100;
//x is still known
x=50;
}
}
Output:

We see that y=100 is unknown. If you want to compile and run the above program remove or comment the
statement y=100. After removing the statement, the above program runs successfully and shows the
following output.
Sum of x+y = 30
There is another variable named an instance variable. These are declared inside a class but outside
any method, constructor, or block. When an instance variable is declared using the keyword static is known
as a static variable. Their scope is class level but visible to the method, constructor, or block that is defined
inside the class.
Product.java
public class Product
{
//variable visible to any child class
public String pName;
//variable visible to product class only
private double pPrice;

JAVA PROGRAMMING 16 KKVPRASAD@CSE


//creating a constructor and parsed product name as a parameter
public Product (String pname)
{
pName = pname;
}
//function sets the product price
public void setPrice(double pprice)
{
pPrice= pprice;
}
//method prints all product info
public void getInfo()
{
System.out.println("Product Name: " +pName );
System.out.println("Product Price: " +pPrice);
}
public static void main(String args[])
{
Product pro = new Product("Mac Book");
pro.setPrice(65000);
pro.getInfo();
}
}
Output:
Product Name: Mac Book
Product Price: 65000.0
Local Variables (Method Level Scope)
These are the variables that are declared inside a method, constructor, or block have a method-
level or block-level scope and cannot be accessed outside in which it is defined. Variables declared inside a
pair of curly braces {} have block-level scope.
Declaring a Variable Inside a Method
public class DemoClass1
{
void show()
{
//variable declared inside a method has method level scope
int x=10;
System.out.println("The value of x is: "+x);
}
public static void main(String args[])
{
DemoClass1 dc = new DemoClass1();
dc.show();
}
}
Output:
The value of x is: 10
Let's see another example of method-level scope.
DemoClass2.java
public class DemoClass2
{

JAVA PROGRAMMING 17 KKVPRASAD@CSE


private int a;
public void setNumber(int a)
{
this.a = a;
System.out.println("The value of a is: "+a);
}
public static void main(String args[])
{
DemoClass2 dc = new DemoClass2();
dc.setNumber(3);
}
}
Output:
The value of a is: 3

In the above example, we have passed a variable as a parameter. We have used this keyword that
differentiates the class variable and local variable.
Declaring a Variable Inside a Constructor : VariableInsideConstructor.java
public class VariableInsideConstructor
{
//creating a default constructor
VariableInsideConstructor()
{
int age=24;
System.out.println("Age is: "+age);
}
//main() method
public static void main(String args[])
{
//calling a default constructor
VariableInsideConstructor vc=new VariableInsideConstructor();
}
}
Output:
Age is: 24

1.2.5 LITERAL CONSTANTS


In Java, literal is a notation that represents a fixed value in the source code. In lexical analysis,
literals of a given type are generally known as tokens.
In Java, literals are the constant values that appear directly in the program. It can be assigned
directly to a variable. Java has various types of literals. The following figure represents a literal.
Types of Literals in Java
There are the majorly four types of literals in Java:
1. Integer Literal
2. Character Literal
3. Boolean Literal
4. String Literal

Integer Literals
Integer literals are sequences of digits. There are three types of integer literals:

JAVA PROGRAMMING 18 KKVPRASAD@CSE


 Decimal Integer: These are the set of numbers that consist of digits from 0 to 9. It may have a
positive (+) or negative (-) Note that between numbers commas and non-digit characters are not
permitted. For example, 5678, +657, -89, etc.
int decVal = 26;
 Octal Integer: It is a combination of number have digits from 0 to 7 with a leading 0. For
example, 045, 026,
int octVal = 067;
 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, 0xd, 0xf,
int hexVal = 0x1a;
 Binary Integer: Base 2, whose digits consists of the numbers 0 and 1 (you can create binary literals
in Java SE 7 and later). Prefix 0b represents the Binary system. For example, 0b11010.
int binVal = 0b11010;
Real Literals
The numbers that contain fractional parts are known as real literals. We can also represent real
literals in exponent form. For example, 879.90, 99E-3, etc.
Backslash Literals
Java supports some special backslash character literals known as backslash literals. They are used in
formatted output. For example:
\n: It is used for a new line
\t: It is used for horizontal tab
\b: It is used for blank space
\v: It is used for vertical tab
\a: It is used for a small beep
\r: It is used for carriage return
\': It is used for a single quote
\": It is used for double quotes
Character Literals
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, 'a', '%', '\u000d', etc.
String Literals
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, "Jack", "12345", "\n", etc.
Floating Point Literals
The vales that contain decimal are floating literals. In Java, float and double primitive types fall into
floating-point literals. Keep in mind while dealing with floating-point literals.
 Floating-point literals for float type end with F or f. For example, 6f, 8.354F, etc. It is a 32-bit float
literal.
 Floating-point literals for double type end with D or d. It is optional to write D or d. For example, 6d,
8.354D, etc. It is a 64-bit double literal.
Floating: float length = 155.4f;
Decimal: double interest = 99658.445;
Decimal in Exponent form: double val= 1.234e2;
Boolean Literals
Boolean literals are the value that is either true or false. It may also have values 0 and 1. For
example, true, 0, etc.
boolean isEven = true;

JAVA PROGRAMMING 19 KKVPRASAD@CSE


Null Literals
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.
String stuName = null;
Student age = null;
Class Literals
Class literal formed by taking a type name and appending .class extension. For example, Scanner.class.
It refers to the object (of type Class) that represents the type itself.
class classType = Scanner.class;

1.2.6 SYMBOLIC CONSTANTS

As the name suggests, a constant is an entity in programming that is immutable. In other words, the
value that cannot be changed.
Constant is a value that cannot be changed after assigning it. Java does not directly support the
constants. There is an alternative way to define the constants in Java by using the non-access modifiers static
and final.
In Java, to declare any variable as constant, we use static and final modifiers. It is also known
as non-access modifiers. According to the Java naming convention the identifier name must be in capital
letters.
Static and Final Modifiers
 The purpose to use the static modifier is to manage the memory.
 It also allows the variable to be available without loading any instance of the class in which it is
defined.
 The final modifier represents that the value of the variable cannot be changed. It also makes the
primitive data type immutable or unchangeable.
The syntax to declare a constant is as follows:
static final datatype identifier_name=value;
For example, price is a variable that we want to make constant.
static final double PRICE=432.78;
Why we use constants?
The use of constants in programming makes the program easy and understandable which can be
easily understood by others. It also affects the performance because a constant variable is cached by both
JVM and the application.
Example 1: Declaring Constant as Private
ConstantExample1.java
import java.util.Scanner;
public class ConstantExample1 {
//declaring constant
private static final double PRICE=234.90;
public static void main(String[] args) {
int unit;
double total_bill;
System.out.print("Enter the number of units you have used: ");
Scanner sc=new Scanner(System.in);
unit=sc.nextInt();
total_bill=PRICE*unit;
System.out.println("The total amount you have to deposit is: "+total_bill);
} }
Output:

JAVA PROGRAMMING 20 KKVPRASAD@CSE


Example 2:
ConstantExample2.java
public class ConstantExample2
{
private static final double PRICE=2999;
public static void main(String[] args)
{
System.out.println("Old Price of Iron: "+PRICE);
ConstantExample obj = new ConstantExample();
obj.showPrice();
}
}
class ConstantExample
{
private static final double PRICE=3599;
void showPrice()
{
System.out.print("New Price of Iron: "+PRICE);
}
}
Output:

1.2.7 FORMATTED OUTPUT WITH PRINTF () METHOD

The printf() method of java PrintStream consists of 2 types with parameters :-


1. printf(String format, Object... args)
2. printf(Locale l, String format, Object... args)

Java PrintStream printf(String format, Object... args) Method

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.
There is an invocation of this method of the form "out.printf(format, args)" which behaves exactly same as
the follows:-
out.format( format, args)
Syntax :
public PrintStream printf(String format, Object... args)
Parameter :
format - a format string as described in Format string syntax
Returns :
The printf() method returns this output stream.
Throws
This method throws:
1. IllegarArgumentException - If a format string contains an illegal syntax, a format specifier that is
incompatible with the given arguments, insufficient arguments given the format string, or other
illegal conditions.
2. NullPointerException - If the format is null.

JAVA PROGRAMMING 21 KKVPRASAD@CSE


Example 1
import java.io.FileNotFoundException;
import java.io.PrintStream;
public class JavaPrintStreamPrintfExample1 {
public static void main(String[] args) throws FileNotFoundException {
PrintStream p=new PrintStream("C:\\Users\\Shubham Jadon\\eclipse-
workspace\\splittable\\src\\printstream\\PipedReader.txt");
System.out.println("printing string...");
p.printf("my name", 0);
p.printf(" is shubham jadon.", 1);
System.out.println("Done !, check the text file.");
}
}
Output:
printing string...
Done !, check the text file.
Example 2
public class JavaPrintStreamPrintfExample2 {
public static void main(String[] args) {
System.out.println("Printing String...");
System.out.printf("my name is shubham jadon.",1 ); //out is the object class P
rintStream
}
}
Output:
Printing String...
my name is shubham jadon.

Java PrintStream printf(Locale l, String format, Object.... args) Method

The printf() method of Java PrintStream class is a convenience method which is used to write a
String which is formatted to this output Stream. It uses the specified format string and arguments to write the
string.
There is an invocation of this method of the form " out.printf(l, format, args)" which behaves exactly same
as the follows:-
out.format(l, format, args)
Syntax
public PrintStreamprintf(Locale l, String format, Object... args)
Parameter
l - the locale to apply during formatting. If it is null then no localised is applied.
format - a format string as described in Format string syntax
args - Arguments referenced by the format specifiers in the format string.
Returns
The printf() method returns this output stream.
Throws
This method throws:
1. IllegarArgumentException - If a format string contains an illegal syntax, a format specifier that is
incompatible with the given arguments, insufficient arguments given the format string, or other
illegal conditions.
2. NullPointerException - if the format is null.

JAVA PROGRAMMING 22 KKVPRASAD@CSE


Example 1
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.Locale;
public class JavaPrintStreamPrintfExample3 {
public static void main(String[] args) throws FileNotFoundException {
PrintStream p=new PrintStream("C:\\Users\\Shubham Jadon\\eclipse-
workspace\\splittable\\src\\printstream\\PipedReader.txt");
System.out.println("printing string...");
p.printf(Locale.getDefault(),"my name", 0);
p.printf(Locale.CANADA," is shubham jadon.", 1);
System.out.println("Done !, check the text file.");
}
}
Output:
printing string...
Done !, check the text file.
Example 2
import java.util.Locale;
public class JavaPrintStreamPrintfExample4 {
public static void main(String[] args) {
System.out.println("Printing String...");
System.out.printf(Locale.getDefault(),"my name is shubham jadon.",1 ); //
out is the object class PrintStream
}
}
Output:
Printing String...
my name is shubham jadon.

1.2.8 STATIC VARIABLES AND METHODS


The static keyword in Java is used for memory management mainly. We can apply static keyword
with variables, methods, blocks and nested classes. The static keyword belongs to the class than an instance
of the class.The static can be:
1. Variable (also known as a class variable)
2. Method (also known as a class method)
3. Block
4. Nested class
1) Java static variable
If you declare any variable as static, it is known as a static variable.
 The static variable can be used to refer to the common property of all objects (which is not unique
for each object), for example, the company name of employees, college name of students, etc.
 The static variable gets memory only once in the class area at the time of class loading.
Advantages of static variable
It makes your program memory efficient (i.e., it saves memory).
Understanding the problem without static variable
class Student{
int rollno;
String name;
String college="ITS";
}

JAVA PROGRAMMING 23 KKVPRASAD@CSE


Suppose there are 500 students in my college, now all instance data members will get memory each
time when the object is created. All students have its unique rollno and name, so instance data member is
good in such case. Here, "college" refers to the common property of all objects. If we make it static, this
field will get the memory only once.
Example of static variable
//Java Program to demonstrate the use of static variable
class Student{
int rollno;//instance variable
String name;
static String college ="ITS";//static variable
//constructor
Student(int r, String n){
rollno = r;
name = n;
}
//method to display the values
void display (){System.out.println(rollno+" "+name+" "+college);}
}
//Test class to show the values of objects
public class TestStaticVariable1{
public static void main(String args[]){
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
//we can change the college of all objects by the single line of code
//Student.college="BBDIT";
s1.display();
s2.display();
}
}
Output:
111 Karan ITS
222 Aryan ITS
Java static method
If you apply static keyword with any method, it is known as static method.
 A static method belongs to the class rather than the object of a class.
 A static method can be invoked without the need for creating an instance of a class.
 A static method can access static data member and can change the value of it.
Example of static method
//Java Program to demonstrate the use of a static method.
class Student{
int rollno;
String name;
static String college = "ITS";
//static method to change the value of static variable
static void change(){
college = "BBDIT";
}
//constructor to initialize the variable
Student(int r, String n){
rollno = r;
name = n;
}
//method to display values
JAVA PROGRAMMING 24 KKVPRASAD@CSE
void display(){System.out.println(rollno+" "+name+" "+college);}
}
//Test class to create and display the values of object
public class TestStaticMethod{
public static void main(String args[]){
Student.change();//calling change method
//creating objects
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
Student s3 = new Student(333,"Sonoo");
//calling display method
s1.display();
s2.display();
s3.display();
}
}
Output:
111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT

1.2.9 ATTRIBUTE FINAL


The final keyword in java is used to restrict the user. The java final keyword can be used in many
context. Final can be:
1. variable
2. method
3. class
The final keyword can be applied with the variables, a final variable that have no value it is called
blank final variable or uninitialized final variable. It can be initialized in the constructor only. The blank
final variable can be static also which will be initialized in the static block only.

Advantages of Final Keyword:


 Stop Value Change
 Stop Method Overriding
 Stop Inheritance
1) Java final variable
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 speed limit, 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 Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class
Output:
Compile Time Error

JAVA PROGRAMMING 25 KKVPRASAD@CSE


2) Java final method
If you make any method as final, you cannot override it.
Example of final method
class Bike{
final void run(){System.out.println("running");}
}
class Honda extends Bike{
void run(){System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Honda honda= new Honda();
honda.run();
}
}
Output:
Compile Time Error

3) Java final class


If you make any class as final, you cannot extend it.
Example of final class
final class Bike{}
class Honda1 extends Bike{
void run(){System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Honda1 honda= new Honda1();
honda.run();
}
}
Output:
Compile Time Error

Is final method inherited?


Yes, final method is inherited but you cannot override it. For Example:
class Bike{
final void run(){System.out.println("running...");}
}
class Honda2 extends Bike{
public static void main(String args[]){
new Honda2().run();
}
}
Output:
running...

1.2.10 INTRODUCTION TO OPERATORS


A Java operator is a special symbol that performs a certain operation on multiple operands and gives
the result as an output.
Java has a large number of operators that are divided into two categories. First, an operator's
performance is based on the number of operands it performs on. Second, the type or nature of the operation
performed by an operator.
Operators can be categorized into the following groups based on the sort of operation they perform:
JAVA PROGRAMMING 26 KKVPRASAD@CSE
 Arithmetic Operators
 Increment Decrement Operators
 Assignment Operators
 Bitwise Operators
 Relational Operators
 Logical Operators
 Miscellaneous Operators
 Unary Operator
 Shift Operator
 Ternary Operator

1.2.11 PRECEDENCE AND ASSOCIATIVITY OF OPERATORS


 Precedence and associativity are two features of Java operators. When there are two or more
operators in an expression, the operator with the highest priority will be executed first.
 For example, consider the equation, 1 + 2 * 5. Here, the multiplication (*) operator is executed first,
followed by addition. Because multiplication operator takes precedence over the addition operator.
Associativity specifies the order in which operators are executed, which can be left to right or right to left.
 For example, in the phrase a = b = c = 8, the assignment operator is used from right to left. It means
that the value 8 is assigned to c, then c is assigned to b, and at last b is assigned to a. This phrase can
be parenthesized as (a = (b = (c = 8)).
 The priority of a Java operator can be modified by putting parenthesis around the lower order priority
operator, but not the associativity. In the equation (1 + 2) * 3, for example, the addition will be
performed first since parentheses take precedence over the multiplication operator.
Operator Precedence in Java (Highest to Lowest)

Category Operators Associativity


Postfix ++ - - Left to right
Unary + - ! ~ ++ - - Right to left
Multiplicative */% Left to right
Additive +- Left to right
Shift << >> Left to right
Relational < <= > >= Left to right
Equality == != Left to right
Bitwise AND & Left to right
Bitwise XOR ^ Left to right
Bitwise OR | Left to right
Logical AND && Left to right
Logical OR || Left to right
Conditional ?: Right to left
Assignment = += -= *= /= %=>>= <<= &= ^= |= Right to left

Java Operator Associativity


 Operators with the same precedence follow the operator group's operator associativity. Operators in
Java can be left-associative, right-associative, or have no associativity at all.
 Left-associative operators are assessed from left to right, right-associative operators are reviewed
from right to left, and operators with no associativity are evaluated in any order.
Operator Precedence Vs. Operator Associativity
 The operator's precedence refers to the order in which operators are evaluated within an expression
whereas associativity refers to the order in which the consecutive operators within the same group
are carried out.
 Precedence rules specify the priority (which operators will be evaluated first) of operators.

JAVA PROGRAMMING 27 KKVPRASAD@CSE


1.2.12 ASSIGNMENT OPERATOR ( = )

 Java assignment operator is one of the most common operators. It is used to assign the value on its
right to the operand on its left.
Java Assignment Operator Example
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=20;
a+=4;//a=a+4 (a=10+4)
b-=4;//b=b-4 (b=20-4)
System.out.println(a);
System.out.println(b);
}}
Output:
14
16
Java Assignment Operator Example: Adding short
public class OperatorExample{
public static void main(String args[]){
short a=10;
short b=10;
//a+=b;//a=a+b internally so fine
a=a+b;//Compile time error because 10+10=20 now int
System.out.println(a);
}}
Output:
Compile time error
After type cast:
public class OperatorExample{
public static void main(String args[]){
short a=10;
short b=10;
a=(short)(a+b);//20 which is int now converted to short
System.out.println(a);
}}
Output:
20

1.2.13 BASIC ARITHMETIC OPERATORS


 Java arithmetic operators are used to perform addition, subtraction, multiplication, and division.
They act as basic mathematical operations.
Java Arithmetic Operator Example
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
System.out.println(a+b);//15
System.out.println(a-b);//5
System.out.println(a*b);//50
System.out.println(a/b);//2
System.out.println(a%b);//0
}}
JAVA PROGRAMMING 28 KKVPRASAD@CSE
Java Arithmetic Operator Example: Expression
public class OperatorExample{
public static void main(String args[]){
System.out.println(10*10/5+3-1*4/2);
}}
Output:
21

1.2.14 INCREMENT (++) AND DECREMENT (- -) OPERATORS

Increment Operator
 Increment Operators are the unary operators used to increment or add 1 to the operand value. The
Increment operand is denoted by the double plus symbol (++).
 It has two types, Pre Increment and Post Increment Operators.
Pre-increment Operator
The pre-increment operator is used to increase the original value of the operand by 1 before
assigning it to the expression.
Syntax
X = ++A;
In the above syntax, the value of operand 'A' is increased by 1, and then a new value is assigned to
the variable 'B'.
Post increment Operator
The post-increment operator is used to increment the original value of the operand by 1 after
assigning it to the expression.
Syntax
X = A++;
In the above syntax, the value of operand 'A' is assigned to the variable 'X'. After that, the value of
variable 'A' is incremented by 1.
Decrement Operator
Decrement Operator is the unary operator, which is used to decrease the original value of the
operand by 1. The decrement operator is represented as the double minus symbol (--). It has two types, Pre
Decrement and Post Decrement operators.
Pre-Decrement Operator
The Pre-Decrement Operator decreases the operand value by 1 before assigning it to the
mathematical expression. In other words, the original value of the operand is first decreases, and then a new
value is assigned to the other variable.
Syntax
B = --A;
In the above syntax, the value of operand 'A' is decreased by 1, and then a new value is assigned to the
variable 'B'.
Post decrement Operator:
Post decrement operator is used to decrease the original value of the operand by 1 after assigning to
the expression.
Syntax
B = A--;
In the above syntax, the value of operand 'A' is assigned to the variable 'B', and then the value of A is
decreased by 1.
Java Unary Operator Example: ++ and --
public class OperatorExample{
public static void main(String args[]){
int x=10;
System.out.println(x++);//10 (11)
System.out.println(++x);//12
JAVA PROGRAMMING 29 KKVPRASAD@CSE
System.out.println(x--);//12 (11)
System.out.println(--x);//10
}}
Output:
10
12
12
10
Java Unary Operator Example 2: ++ and --
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=10;
System.out.println(a++ + ++a);//10+12=22
System.out.println(b++ + b++);//10+11=21
}}
Output:
22
21

1.2.15 TERNARY OPERATOR

 In Java, the ternary operator is a type of Java conditional operator.


 The meaning of ternary is composed of three parts. The ternary operator (? :) consists of three
operands. It is used to evaluate Boolean expressions.
 The operator decides which value will be assigned to the variable. It is the only conditional operator
that accepts three operands. It can be used instead of the if-else statement.
 It makes the code much more easy, readable, and shorter.
Syntax:
variable = (condition) ? expression1 : expression2
The above statement states that if the condition returns true, expression1 gets executed, else
the expression2 gets executed and the final result stored in a variable.

TernaryOperatorExample.java
public class TernaryOperatorExample {
public static void main(String args[])
{
int x, y;
x = 20;
y = (x == 1) ? 61: 90;
System.out.println("Value of y is: " + y);
y = (x == 20) ? 61: 90;
System.out.println("Value of y is: " + y);
}
}
Output
Value of y is: 90
Value of y is: 61
JAVA PROGRAMMING 30 KKVPRASAD@CSE
LargestNumberExample.java
public class LargestNumberExample {
public static void main(String args[])
{
int x=69;
int y=89;
int z=79;
int largestNumber= (x > y) ? (x > z ? x : z) : (y > z ? y : z);
System.out.println("The largest numbers is: "+largestNumber);
}
}
Output
The largest number is: 89

1.2.16 RELATIONAL OPERATORS


 The Java Relational operators compare between operands and determine the relationship between
them.
 There are six types of relational operators in Java, these are:

Operatoror Meaning
== Is equal to
!= Is not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to

Example Program on Relational Operators in Java


public class relatiop {
public static void main(String[] args) {
//Variables Definition and Initialization
int num1 = 12, num2 = 4;
//is equal to
System.out.println("num1 == num2 = " + (num1 == num2) );
//is not equal to
System.out.println("num1 != num2 = " + (num1 != num2) );
//Greater than
System.out.println("num1 > num2 = " + (num1 > num2) );
//Less than
System.out.println("num1 < num2 = " + (num1 < num2) );
//Greater than or equal to
System.out.println("num1 >= num2 = " + (num1 >= num2) );
//Less than or equal to
System.out.println("num1 <= num2 = " + (num1 <= num2) );
}
}
Output:
num1 == num2 = false
num1 != num2 = true
num1 > num2 = true
num1 < num2 = false
num1 >= num2 = true
num1 <= num2 = false

JAVA PROGRAMMING 31 KKVPRASAD@CSE


1.2.17 BOOLEAN LOGICAL OPERATORS
 Logical operators are used to performing logical “AND”, “OR” and “NOT” operations, i.e. the
function similar to AND gate and OR gate in digital electronics.
AND Operator ( && ) – if( a && b ) [if true execute else don’t]
OR Operator ( || ) – if( a || b) [if one of them is true execute else don’t]
NOT Operator ( ! ) – !(a<b) [returns false if a is smaller than b]
There are following boolean operators supported by Java language.
Assume variable A holds 10 and variable B holds 20, then −

Operator Description Example


== (equal to) Checks if the values of two operands are equal or not, if (A == B) is not
yes then condition becomes true. true.
!= (not equal to) Checks if the values of two operands are equal or not, if (A != B) is true.
values are not equal then condition becomes true.
> (greater than) Checks if the value of left operand is greater than the (A > B) is not
value of right operand, if yes then condition becomes true.
true.
< (less than) Checks if the value of left operand is less than the value (A < B) is true.
of right operand, if yes then condition becomes true.
>= (greater than Checks if the value of left operand is greater than or (A >= B) is not
or equal to) equal to the value of right operand, if yes then condition true.
becomes true.
<= (less than or Checks if the value of left operand is less than or equal (A <= B) is true.
equal to) to the value of right operand, if yes then condition
becomes true.
&& (logical and) Called Logical AND operator. If both the operands are (A && B) is false
non-zero, then the condition becomes true.
|| (logical or) Called Logical OR Operator. If any of the two operands (A || B) is true
are non-zero, then the condition becomes true.
! (logical not) Called Logical NOT Operator. Use to reverses the !(A && B) is true
logical state of its operand. If a condition is true then
Logical NOT operator will make false.

1.2.18 BITWISE LOGICAL OPERATORS

 In Java, an operator is a symbol that performs the specified operations.


Types of Bitwise Operator
There are six types of the bitwise operator in Java:
 Bitwise AND
 Bitwise exclusive OR
 Bitwise inclusive OR
 Bitwise Compliment
 Bit Shift Operators

Operators Symbol Uses


Bitwise AND & op1 & op2
Bitwise exclusive OR ^ op1 ^ op2
Bitwise inclusive OR | op1 | op2
Bitwise Compliment ~ ~ op
Bitwise left shift << op1 << op2
Bitwise right shift >> op1 >> op2
Unsigned Right Shift Operator >>> op >>> number of places to shift

JAVA PROGRAMMING 32 KKVPRASAD@CSE


Bitwise AND (&)
It is a binary operator denoted by the symbol &. It returns 1 if and only if both bits are 1, else returns 0
BitwiseAndExample.java
public class BitwiseAndExample {
public static void main(String[] args)
{
int x = 9, y = 8;
// bitwise and
// 1001 & 1000 = 1000 = 8
System.out.println("x & y = " + (x & y));
} }
Output
x&y=8
Bitwise exclusive OR (^)
It is a binary operator denoted by the symbol ^ (pronounced as caret). It returns 0 if both bits are the
same, else returns 1.
BitwiseXorExample.java
public class BitwiseXorExample {
public static void main(String[] args) {
int x = 9, y = 8;
// bitwise XOR
// 1001 ^ 1000 = 0001 = 1
System.out.println("x ^ y = " + (x ^ y));
} }
Output
x^y=1
Bitwise inclusive OR (|)
It is a binary operator denoted by the symbol | (pronounced as a pipe). It returns 1 if either of the bit
is 1, else returns 0.
BitwiseInclusiveOrExample.java
public class BitwiseInclusiveOrExample {
public static void main(String[] args) {
int x = 9, y = 8;
// bitwise inclusive OR
// 1001 | 1000 = 1001 = 9
System.out.println("x | y = " + (x | y));
} }
Output
x|y=9
Bitwise Complement (~)
It is a unary operator denoted by the symbol ~ (pronounced as the tilde). It returns the inverse or
complement of the bit. It makes every 0 a 1 and every 1 a 0.
BitwiseComplimentExample.java
public class BitwiseComplimentExample {
public static void main(String[] args) {
int x = 2;
// bitwise compliment
// ~0010= 1101 = -3
System.out.println("~x = " + (~x));
}
}
Output
~x = -3

JAVA PROGRAMMING 33 KKVPRASAD@CSE


Bit Shift Operators
Shift operator is used in shifting the bits either right or left. We can use shift operators if we divide or
multiply any number by 2. The general format to shift the bit is as follows:
variable << or >> number of places to shift;
For example, if a=10
a>>2; //shifts two bits
a>>4; //shifts 4 bits
Java provides the following types of shift operators:
 Signed Right Shift Operator or Bitwise Right Shift Operator
 Unsigned Right Shift Operator
 Signed Left Shift Operator or Bitwise Left Shift Operator
Signed Right Shift Operator (>>)
The signed right shift operator shifts a bit pattern of a number towards the right with a specified
number of positions and fills 0. The operator is denoted by the symbol >>. It also preserves the leftmost bit
(sign bit). If 0 is presented at the leftmost bit, it means the number is positive. If 1 is presented at the
leftmost bit, it means the number is negative.
In general, if we write a>>n, it means to shift the bits of a number toward the right with a specified
position (n). In the terms of mathematics, we can represent the signed right shift operator as follows:

Signed Left Shift Operator (<<)


The signed left shift operator (<<) shifts a bit pattern to the left. It is represented by the symbol <<. It
also preserves the leftmost bit (sign bit). It does not preserve the sign bit.
In general, if we write a<<n, it means to shift the bits of a number toward the left with specified
position (n). In the terms of mathematics, we can represent the signed right shift operator as follows:

JAVA PROGRAMMING 34 KKVPRASAD@CSE


1.3 CONTROL STATEMENTS

1.3.1 INTRODUCTION
 Java compiler executes the code from top to bottom. The statements in the code are executed
according to the order in which they appear.
 However, Java provides statements that can be used to control the flow of Java code. Such
statements are called control flow statements.
 It is one of the fundamental features of Java, which provides a smooth flow of program.
Java provides three types of control flow statements.
Conditional or Selection Statements
 if Statement
 if-else statement
 if-else-if statement
 switch statement
Loop or Iterative Statements
 for Loop
 while Loop
 do-while Loop
 for-each Loop
Flow Control or Jump Statements
 return
 continue
 Break

1.3.2 IF EXPRESSION
 In Java, the "if" statement is used to evaluate a condition. The control of the program is diverted
depending upon the specific condition. The condition of the If statement gives a Boolean value,
either true or false
 It is the most basic statement among all control flow statements in Java. It evaluates a Boolean
expression and enables the program to enter a block of code if the expression evaluates to true.
Syntax of if statement is given below.
if(condition) {
statement 1; //executes when condition is true
}
Student.java
public class Student {
public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y > 20) {
System.out.println("x + y is greater than 20");
}
}
}
Output:
x + y is greater than 20

1.3.3 NESTED IF EXPRESSIONS


 In nested if-statements, the if statement can contain a if or if-else statement inside another if or else-if
statement.

JAVA PROGRAMMING 35 KKVPRASAD@CSE


Syntax :
if(condition 1) {
statement 1; //executes when condition 1 is true
if(condition 2) {
statement 2; //executes when condition 2 is true
}
else{
statement 2; //executes when condition 2 is false
}
}
Student.java :
public class Student {
public static void main(String[] args) {
String address = "Delhi, India";
if(address.endsWith("India")) {
if(address.contains("Meerut")) {
System.out.println("Your city is Meerut");
}else if(address.contains("Noida")) {
System.out.println("Your city is Noida");
}else {
System.out.println(address.split(",")[0]);
}
}else {
System.out.println("You are not living in India");
}
}
}
Output:
Delhi

1.3.4 IF–ELSE EXPRESSIONS


 The if-else statement is an extension to the if-statement, which uses another block of code, i.e., else
block. The else block is executed if the condition of the if-block is evaluated as false.
Syntax:
if(condition) {
statement 1; //executes when condition is true
}
else{
statement 2; //executes when condition is false
}
Student.java
public class Student {
public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y < 10) {
System.out.println("x + y is less than 10");
} else {
System.out.println("x + y is greater than 20");
}
}
}
Output:
x + y is greater than 20
JAVA PROGRAMMING 36 KKVPRASAD@CSE
1.3.5 SWITCH STATEMENT
 The Java switch statement executes one statement from multiple conditions. It is like if-else-if ladder
statement.
 The switch statement works with byte, short, int, long, enum types, String and some wrapper types
like Byte, Short, Int, and Long. Since Java 7, you can use strings in the switch statement.
Syntax:
switch(expression){
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......

default:
code to be executed if all cases are not matched;
}
SwitchExample.java
public class SwitchExample {
public static void main(String[] args) {
//Declaring a variable for switch expression
int number=20;
//Switch expression
switch(number){
//Case statements
case 10: System.out.println("10");
break;
case 20: System.out.println("20");
break;
case 30: System.out.println("30");
break;
//Default case statement
default:System.out.println("Not in 10, 20 or 30");
}
}
}
Output:
20

1.3.6 ITERATION STATEMENTS

 In programming, sometimes we need to execute the block of code repeatedly while some condition
evaluates to true.
 However, loop statements are used to execute the set of instructions in a repeated order. The
execution of the set of instructions depends upon a particular condition.
 In Java, we have three types of loops that execute similarly. However, there are differences in their
syntax and condition checking time.

1. while loop
2. do-while loop
3. for loop
4. for each
JAVA PROGRAMMING 37 KKVPRASAD@CSE
1.3.7 WHILE EXPRESSION

 The while loop is also used to iterate over the number of statements multiple times. However, if we
don't know the number of iterations in advance, it is recommended to use a while loop.
 Unlike for loop, the initialization and increment/decrement doesn't take place inside the loop
statement in while loop.
 It is also known as the entry-controlled loop since the condition is checked at the start of the loop. If
the condition is true, then the loop body will be executed; otherwise, the statements after the loop
will be executed.
Syntax:
while(condition){
//looping statements
}
Calculation .java
public class Calculation {
public static void main(String[] args) {
// TODO Auto-generated method stub
int i = 0;
System.out.println("Printing the list of first 10 even numbers \n");
while(i<=10) {
System.out.println(i);
i = i + 2;
} } }
Output:
Printing the list of first 10 even numbers
0 2 4 6 8 10

1.3.8 DO–WHILE LOOP

 The do-while loop checks the condition at the end of the loop after executing the loop statements.
 When the number of iteration is not known and we have to execute the loop at least once, we can use
do-while loop.
 It is also known as the exit-controlled loop since the condition is not checked in advance. The syntax
of the do-while loop is given below.
Syntax:
do
{
//statements
} while (condition);
Calculation.java
public class Calculation {
public static void main(String[] args) {
// TODO Auto-generated method stub
int i = 0;
System.out.println("Printing the list of first 10 even numbers \n");
do {
System.out.println(i);
i = i + 2;
}while(i<=10);
}
}
Output:
Printing the list of first 10 even numbers
0 2 4 6 8 10

JAVA PROGRAMMING 38 KKVPRASAD@CSE


1.3.9 FOR LOOP

 In Java, for loop is similar to C and C++. It enables us to initialize the loop variable, check the
condition, and increment/decrement in a single line of code.
 We use the for loop only when we exactly know the number of times, we want to execute the block
of code.
for(initialization, condition, increment/decrement) {
//block of statements
}
Calculation.java
public class Calculattion {
public static void main(String[] args) {
// TODO Auto-generated method stub
int sum = 0;
for(int j = 1; j<=10; j++) {
sum = sum + j;
}
System.out.println("The sum of first 10 natural numbers is " + sum);
} }
Output:
The sum of first 10 natural numbers is 55

1.3.10 NESTED FOR LOOP

 If we have a for loop inside the another loop, it is known as nested for loop. The inner loop executes
completely whenever outer loop executes.
PyramidExample.java
public class PyramidExample {
public static void main(String[] args) {
for(int i=1;i<=5;i++){
for(int j=1;j<=i;j++){
System.out.print("* ");
}
System.out.println();//new line
} }}
Output:
*
**
***
****
*****

1.3.11 FOR–EACH FOR LOOP

 Java provides an enhanced for loop to traverse the data structures like array or collection. In the for-
each loop, we don't need to update the loop variable.
for(data_type var : array_name/collection_name){
//statements
}
Calculation.java
public class Calculation {
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] names = {"Java","C","C++","Python","JavaScript"};
System.out.println("Printing the content of the array names:\n");
JAVA PROGRAMMING 39 KKVPRASAD@CSE
for(String name:names) {
System.out.println(name);
} } }

Output:

Printing the content of the array names:


Java
C
C++
Python
JavaScript

1.3.12 BREAK STATEMENT

 As the name suggests, the break statement is used to break the current flow of the program and
transfer the control to the next statement outside a loop or switch statement.
 However, it breaks only the inner loop in the case of the nested loop.
 The break statement cannot be used independently in the Java program, i.e., it can only be written
inside the loop or switch statement.
BreakExample.java
public class BreakExample {
public static void main(String[] args) {
// TODO Auto-generated method stub
for(int i = 0; i<= 10; i++) {
System.out.println(i);
if(i==6) {
break;
} } } }
Output:
0123456

1.3.13 CONTINUE STATEMENT

 Unlike break statement, the continue statement doesn't break the loop, whereas, it skips the specific
part of the loop and jumps to the next iteration of the loop immediately.
import java.util.*;
public class GFG {
public static void main(String args[])
{
for (int i = 0; i <= 15; i++) {
if (i == 10 || i == 12) {
// Using continue statement to skip the
// execution of loop when i==10 or i==12
continue;
}
System.out.print(i + " ");
} }}
Output:
0 1 2 3 4 5 6 7 8 9 11 13 14 15

*****
JAVA PROGRAMMING 40 KKVPRASAD@CSE

You might also like