0% found this document useful (0 votes)
17 views54 pages

Module 1 Part1

The document provides an overview of Java, highlighting its features, applications, and history, including its development by the Green Team at Sun Microsystems. It explains Java's key characteristics such as being object-oriented, platform-independent, and secure, along with a list of keywords and a simple 'Hello, World!' program example. Additionally, it covers Java's primitive and non-primitive data types, emphasizing their significance in programming.

Uploaded by

jose2985
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)
17 views54 pages

Module 1 Part1

The document provides an overview of Java, highlighting its features, applications, and history, including its development by the Green Team at Sun Microsystems. It explains Java's key characteristics such as being object-oriented, platform-independent, and secure, along with a list of keywords and a simple 'Hello, World!' program example. Additionally, it covers Java's primitive and non-primitive data types, emphasizing their significance in programming.

Uploaded by

jose2985
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

MODULE I FUNDAMENTALS, INHERITANCE, AND INTERFACE 9

Introduction - Java features – Java Platform – Java Fundamentals – Expressions, Operators, and
Control Structures–Constructor-The Java Class- Inheritance, Derived Classes, Method Overriding,
Method Overloading, Abstract Class and Method, Interfaces, Packages.

What is Java?

• Java is a high level programming language and it is also called as a platform. Java is a secured
and robust high level object-oriented programming language.
• Platform: Any software or hardware environment in which a program runs is known as a
platform.
• Java has its own runtime environment (JRE) and API so java is also called as platform.
• Java follows the concept of Write Once, Run Anywhere.

Applications of Java

1. Desktop Applications

2. Web Applications

3. Mobile

4. Enterprise Applications

5. Smart Card

6. Embedded System

7. Games

8. Robotics etc.

History of Java

Java history begins from Green Team. The Java team members (otherwise called Green Team), started a
revolutionary task to build up a language for digital devices, for example, set-top boxes, televisions and
so on. For the green team members, it was the advanced concept at that time. However, it was suitable for
internet programming. Afterwards, Java technology as joined by Netscape. At present, Java is used in
many places such as internet programming, mobile devices, games, e-business solutions and so on. There
are given the main points which describe the history of java.

o James Gosling, Mike Sheridan, and Patrick Naughton started the Java language project in
June 1991. The tiny team of sun engineers called Green Team.
o In the beginning, it is designed for small, embedded systems in electronic appliances like
set-top boxes.
oFirst of all, it was known as "Greentalk" by James Gosling and .gt was the file extension.
oLater, it was known as Oak and was developed as a piece of the Green project.
Why "Oak" name

• Oak is a symbol of strength and chosen as a national tree of many countries like U.S.A., France,
Germany, Romania etc.
• In the year 1995, Oak was renamed as "Java" since it was previously a trademark by Oak
Technologies.
Why "Java" name

• The team gathered to decide a new name. The recommended words were "dynamic",
"revolutionary", "Silk", "jolt", "DNA" and so on.
• They needed something that mirrored the quintessence of the technology: revolutionary,
dynamic, cool, unique, and simple to spell and fun to say.
• As indicated by James Gosling, "Java was one of the best choices along with Silk".
• Since java was so unique, majority of the team members favored java.
• The Java is an island of Indonesia where first coffee was produced (known as java coffee).
• Notice that Java is only a name not an acronym.
• Initially developed by James Gosling at Sun Microsystems (which is currently a subsidiary of
Oracle Corporation) and then released in 1995.
• In the year 1995, Time magazine said Java is one of the Ten Best Products of 1995.
• JDK 1.0 released in (23rd January, 1996).
Java Version History

• There are numerous java versions are released. Present stable release of Java will be Java SE 8.
o JDK Alpha and Beta (1995)
o JDK 1.0 (23rd Jan, 1996)
o JDK 1.1 (19th Feb, 1997)
o J2SE 1.2 (8th Dec, 1998)
o J2SE 1.3 (8th May, 2000)
o J2SE 1.4 (6th Feb, 2002)
o J2SE 5.0 (30th Sep, 2004)
o Java SE 6 (11th Dec, 2006)
o Java SE 7 (28th July, 2011)
o Java SE 8 (18th March, 2014)
o Java SE 9 (21th Sep, 2017)
Special Features of Java

The features are given by,

o Simple
o Object-Oriented
o Portable
o Platform independent
o Secured
o Robust
o Architecture neutral
o Dynamic
o Interpreted
o High Performance
o Multithreaded
o Distributed
o

Simple

• According to Sun, Java language is simple because:


o Java syntax is based on C++ (so easier for programmers to learn it after C++).
o Java removed many confusing and/or rarely-used features e.g., explicit pointers, operator
overloading etc.
o No need to remove unreferenced objects because there is Automatic Garbage Collection
in java.
Object-oriented

• Object-oriented programming (OOP) refers to a type of computer programming (software design)


in which programmers define not only the data type of a data structure, but also the types of
operations (functions) that can be applied to the data structure.
• Basic concepts of OOPs,
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation

Platform Independent

• A platform is the hardware or software environment in which a program runs. There are two types
of platforms one is software-based another one is hardware-based. The Java platform differs from
most other platforms in the sense that it is a software-based platform that runs on the top of other
hardware-based platforms. It has two components:
o Runtime Environment
o API(Application Programming Interface)
• The Java code can be running on multiple platforms like Windows, Linux, Sun Solaris, and
Mac/OS and so on.
• This code is compiled by the compiler and then converted it into a bytecode.
• This bytecode is platform-independent code since it can be running on multiple platforms i.e.
Write Once and Run Anywhere (WORA).

Secured

• Java is secured because,


o No explicit pointer
o Java Programs run within virtual machine sandbox
o Classloader: it includes security by isolating the package for the classes of the local file
system from those are imported from network sources.
o Bytecode Verifier: it checks the code fragments for illegal code that can violate access
correct to objects.
o Security Manager: it determines what resources a class can access, for example, reading
and writing to the local disk.
• These securities are given by java language. Some security can likewise be given by application
developer through SSL, JAAS, and Cryptography and so on.
Robust

• Robust simply means strong. Java uses strong memory management. There is lack of pointers that
avoids security problem.
• There is automatic garbage collection in java.
• In Java exception handling and type checking mechanism are available. These all make java
robust.
Architecture-neutral

• There are no implementation dependent features (e.g. size of primitive types is fixed).
• In C programming, int data type occupies two bytes of memory for 32-bit architecture and four
bytes of memory for 64-bit architecture. However in java, it occupies four bytes of memory for
both 32 and 64 bit architectures.
Portable

• We may carry the java bytecode to any platform.


High-performance

• The Java programming language is quicker than traditional interpretation whereas the byte code
is "close" to local code still slower than compiled language like C++.
Distributed

• You can make distributed applications in java. The RMI and EJB are used for making distributed
applications.
• We might access files by calling the methods from several machine on the internet/web.
Multi-threaded

• Thread is similar to a separate program, it executing concurrently. You can write Java codes that
deal with lots of tasks at only once by defining multiple threads.
• The most important benefit of multi-threading is, it couldn’t occupies memory for each thread and
it shares a common memory area to every thread. Threads are important for multi-media, Web
applications and so on.
Key words
• In Java, keywords are reserved words that have a predefined meaning in the language.
• They form the foundation of Java's syntax and cannot be used as identifiers, such as variable
names, method names, or class names.
• Each keyword has a specific function, and the Java compiler uses these to parse the structure of
Java code.

List of Java Keywords

Keyword Description

abstract Defines abstract classes and methods.

assert Used for debugging purposes to test assumptions in the code.

boolean Defines a boolean variable with true or false values.

break Exits a loop or a switch statement.

byte Defines a byte variable (8-bit signed integer).

case Defines a block of code in switch statements.

catch Handles exceptions in a try-catch block.


char Defines a character variable.

class Declares a class.

continue Skips the current iteration of a loop and continues.

default Defines the default block in a switch statement.

do Executes a block of code at least once in a do-while loop.

double Defines a double precision floating-point variable.

else Defines the alternative block for an if statement.

enum Declares an enumerated type.

extends Indicates a subclass inherits from a superclass.

final Defines constants or methods that cannot be overridden.

finally Ensures code execution after a try-catch block.

float Defines a floating-point variable.

for Declares a loop that repeats a block of code.

if Starts a conditional block.

implements Indicates that a class implements an interface.

import Imports classes or entire packages.

instanceof Tests whether an object is an instance of a specific class.

int Defines an integer variable.

interface Declares an interface.


long Defines a long integer variable.

native Indicates that a method is implemented in native code.

new Creates a new object instance.

null Represents the null reference, no value.

package Declares a package.

private Declares a private member, accessible only within its class.

protected Declares a protected member, accessible within package or subclasses.

public Declares a public member, accessible by any other class.

return Exits a method and optionally returns a value.

short Defines a short integer variable.

static Declares a static member that belongs to the class, not instances.

strictfp Restricts floating-point calculations to ensure portability.

super Refers to the superclass of the current object.

switch Declares a multi-branch conditional statement.

synchronized Locks a block of code or method to prevent concurrent access.

this Refers to the current object instance.

throw Throws an exception.

throws Declares exceptions that a method can throw.

transient Marks a field to be skipped during serialization.


try Starts a block to test for exceptions.

void Indicates that a method does not return a value.

volatile Marks a variable as being used by multiple threads.

while Declares a loop that executes while a condition is true.

Execution Process of Java Program


The following three steps are used to create and execute a java program.

• Create a source code (.java file).


• Compile the source code using javac command.
• Run or execute .class file using java command.
First Java Program:Hello World
Creating your first Java program is an essential step in learning the language. The "Hello, World!" program is a simple
yet fundamental example that demonstrates the basic structure of a Java application. This guide will walk you through
writing, compiling, and running your first Java program.

Writing Your First Java Program

To create a "Hello, World!" program, follow these steps:

1. Open a Text Editor: You can use any text editor, such as Notepad, TextEdit, or an Integrated Development
Environment (IDE) like Eclipse or IntelliJ IDEA.
2. Write the Code: Type the following code into your text editor:

public class HelloWorld {

public static void main(String[] args) {

System.out.println("Hello, World!");

Explanation of the Code

• public class HelloWorld: This line declares a public class named HelloWorld. In Java, every application must
have at least one class definition.
• public static void main(String[] args): This is the main method, the entry point for any Java application.
The main method is always required in a standalone Java application.
• System.out.println("Hello, World!");: This line prints the text "Hello, World!" to the console. System.out is a
standard output stream, and println is a method that prints a line of text.

Compiling the Program

Before running your program, you need to compile it:

1. Save the File: Save your file with the name HelloWorld.java. The filename must match the class name and be
case-sensitive.
2. Open Command Prompt/Terminal: Navigate to the directory where your HelloWorld.java file is saved.
3. Compile the Program: Enter the following command to compile your program:
javac HelloWorld.java

This command uses the Java compiler (javac) to convert your Java code into bytecode, generating
a HelloWorld.class file.

Running the Program

After successful compilation, run your program with the following command:

java HelloWorld

If everything is set up correctly, you should see the output:

Hello, World!

Tips and Best Practices

• Case Sensitivity: Java is case-sensitive. Ensure that you use the correct capitalization for class names, method
names, and file names.
• File Naming: The filename must match the public class name exactly, including capitalization.
• Environment Setup: Ensure that Java Development Kit (JDK) is installed and configured correctly on your
system. You can verify the installation by running java -version and javac -version in your command prompt or
terminal.
• Use Comments: Add comments to your code to improve readability and maintainability. For example:

Java Comments
Comments can be used to explain Java code, and to make it more readable. It can also be used to prevent execution
when testing alternative code.

1.Single-line Comments

Single-line comments start with two forward slashes (//).

Any text between // and the end of the line is ignored by Java (will not be executed).

This example uses a single-line comment before a line of code:


ExampleGet your own Java Server

// This is a comment

System.out.println("Hello World");

This example uses a single-line comment at the end of a line of code:

Example

System.out.println("Hello World"); // This is a comment

2.Java Multi-line Comments

Multi-line comments start with /* and ends with */.

Any text between /* and */ will be ignored by Java.

This example uses a multi-line comment (a comment block) to explain the code:

Example

/* The code below will print the words Hello World

to the screen, and it is amazing */

System.out.println("Hello World");
Java Data Types
Java programming language has a rich set of data types. The data type is a category of data stored in variables.
In java, data types are classified into two types and they are as follows.

• Primitive Data Types


• Non-primitive Data Types

Primitive Data Types

The primitive data types are built-in data types and they specify the type of value stored in a variable and the
memory size. The primitive data types do not have any additional methods.
In java, primitive data types includes byte, short, int, long, float, double, char, and boolean.
The following table provides more description of each primitive data type.

Data type Meaning Memory size Range Default Value

byte Whole numbers 1 byte -128 to +127 0

short Whole numbers 2 bytes -32768 to +32767 0


long Whole numbers 8 bytes -9,223,372,036,854,775,808 to 0L
+9,223,372,036,854,775,807

float Fractional numbers 4 bytes - 0.0f

double Fractional numbers 8 bytes - 0.0d

char Single character 2 bytes 0 to 65535 \u0000

boolean unsigned char 1 bit 0 or 1 0 (false)


int Whole numbers 4 bytes -2,147,483,648 to +2,147,483,647 0

Non-primitive Data Types

In java, non-primitive data types are the reference data types or user-created data types. All non-primitive data
types are implemented using object concepts. Every variable of the non-primitive data type is an object. The non-
primitive data types may use additional methods to perform certain operations. The default value of non- primitive
data type variable is null.
In java, examples of non-primitive data types are String, Array, List, Queue, Stack, Class, Interface, etc.
Java Variables
A variable is a named memory location used to store a data value. A variable can be defined as a container that
holds a data value.
In java, we use the following syntax to create variables.
Syntax

data_type
variable_name; (or)

data_type variable_name_1,
variable_name_2,...; (or)

data_type variable_name = value;


(or)

In java programming language variables are classified as follows.

• Local variables
• Instance variables or Member variables or Global variables
• Static variables or Class variables
• Final variables

Local variables

The variables declared inside a method or a block are known as local variables. A local variable is visible within
the method in which it is declared. The local variable is created when execution control enters into the method or
block and destroyed after the method or block execution completed.
Let's look at the following example java program to illustrate local variable in java.

public class LocalVariables

public void show() { int


a = 10;
//static int x = 100;

System.out.println("Inside show method, a = " + a);

public void display() {

int b = 20;

System.out.println("Inside display method, b = " + b);

// trying to access variable 'a' - generates an ERROR


System.out.println("Inside display method, a = " + a);

public static void main(String args[]) { LocalVariables


obj = new LocalVariables(); obj.show();

obj.display();
}
}

Instance variables or member variables or global variables

The variables declared inside a class and outside any method, constructor or block are known as instance variables
or member variables. These variables are visible to all the methods of the class. The changes made to these
variables by method affects all the methods in the class. These variables are created separate copy for every object
of that class.

Let's look at the following example java program to illustrate instance variable in java.

Example

public class ClassVariables { int x

= 100;

public void show() {


System.out.println("Inside show method, x = " + x); x
= x + 100;

public void display() {

System.out.println("Inside display method, x = " + x);

public static void main(String[] args) { ClassVariables


obj = new ClassVariables(); obj.show();

obj.display();

Static variables or Class variables

A static variable is a variable that declared using static keyword. The instance variables can be static variables
but local variables can not. Static variables are initialized only once, at the start of the program execution. The
static variable only has one copy per class irrespective of how many objects we create.
The static variable is access by using class name.
Let's look at the following example java program to illustrate static variable in java.
Example

public class Counter {


// Static variable
// This variable is shared among all instances of the Counter class.
static int count = 0;

// Constructor to increment the static variable 'count'


public Counter() {
count++;
}

// Method to display the value of the static variable 'count'


public static void displayCount() {
System.out.println("Number of instances created: " + count);
}
public static void main(String[] args) {
// Creating instances of the Counter class
Counter c1 = new Counter();
Counter c2 = new Counter();
Counter c3 = new Counter();

// All instances share the same static variable 'count'


Counter.displayCount(); // Output will be: Number of instances created: 3
}
}
Final variables

A final variable is a variable that declared using final keyword. The final variable is initialized only once, and
does not allow any method to change it's value again. The variable created using final keyword acts as constant.
All variables like local, instance, and static variables can be final variables.
Let's look at the following example java program to illustrate final variable in java.

Example

public class FinalVariableExample { final

int a = 10;

void show() {

System.out.println("a = " + a);

a = 20; //Error due to final variable cann't be modified

public static void main(String[] args) {

FinalVariableExample obj = new FinalVariableExample();


obj.show();

Java Type Casting


Type casting is when you assign a value of one primitive data type to another type.
In Java, there are two types of casting:

• Widening Casting (automatically) - converting a smaller type to a larger type size


byte -> short -> char -> int -> long -> float -> double

• Narrowing Casting (manually) - converting a larger type to a smaller size type


double -> float -> long -> int -> char -> short -> byte

Widening Casting

Widening casting is done automatically when passing a smaller size type to a larger size type:

ExampleGet your own Java Server

public class Main {

public static void main(String[] args) {

int myInt = 9;

double myDouble = myInt; // Automatic casting: int to double

System.out.println(myInt); // Outputs 9

System.out.println(myDouble); // Outputs 9.0

Narrowing Casting

Narrowing casting must be done manually by placing the type in parentheses () in front of the value:

Example

public class Main {

public static void main(String[] args) {

double myDouble = 9.78d;


int myInt = (int) myDouble; // Manual casting: double to int

System.out.println(myDouble); // Outputs 9.78

System.out.println(myInt); // Outputs 9

Java Arrays
• An array is a collection of similar data values with a single name.
• An array can also be defined as, a special type of variable that holds multiple values of the same data
type at a time.
• In java, arrays are objects and they are created dynamically using new operator.
• Every array in java is organized using index values.
• The index value of an array starts with '0' and ends with 'size-1'.
• We use the index value to access individual elements of an array.

In java, there are two types of arrays and they are as follows.
• One Dimensional Array
• Multi-Dimensional Array

Creating an array

In the java programming language, an array must be created using new operator and with a specific size. The
size must be an integer value but not a byte, short, or long. We use the following syntax to create an array.
Syntax

data_type array_name[ ] = new data_type[size];


(or)

data_type[ ] array_name = new data_type[size];

Let's look at the following example program.


Example

public class ArrayExample {

public static void main(String[] args) {

int list[] = new int[5];

list[0] = 10;

System.out.println("Value at index 0 - " + list[0]);


System.out.println("Length of the array - " + list.length);

In java, an array can also be initialized at the time of its declaration. When an array is initialized at the time of
its declaration, it need not specify the size of the array and use of the new operator.
Here, the size is automatically decided based on the number of values that are initialized.

Java Operators
An operator is a symbol used to perform arithmetic and logical operations. Java provides a rich set of operators.
In java, operators are classified into the following four types.

• Arithmetic Operators
• Relational (or) Comparison Operators
• Logical Operators
• Assignment Operators
• Bitwise Operators
• Conditional Operators

Let's look at each operator in detail


Arithmetic Operators
In java, arithmetic operators are used to performing basic mathematical operations like addition, subtraction,
multiplication, division, modulus, increment, decrement, etc.,

Operator Meaning Example


+ Addition 10 + 5 = 15

- Subtraction 10 - 5 = 5

* Multiplication 10 * 5 = 50

/ Division 10 / 5 = 2

% Modulus - Remainder of the Division 5%2=1

++ Increment a++

-- Decrement a--

◻ The addition operator can be used with numerical data types and character or string data type. When it is used
with numerical values, it performs mathematical addition and when it is used with character or string data type
values, it performs concatenation (appending).

◻ The modulus (remainder of the division) operator is used with integer data type only.

◻ The increment and decrement operators are used as pre-increment or pre-decrement and post-
increment or post-decrement.
◻ When they are used as pre, the value is get modified before it is used in the actual expresion and when it is
used as post, the value is get modified after the the actual expression evaluation.

Let's look at the following example program.


Example

public class ArithmeticOperators {

public static void main(String[] args) {


int a = 10, b = 20, result;
System.out.println("a = " + a + ", b = " + b);
result = a + b;

System.out.println("Addition : " + a + " + " + b + " = " + result);


result = a - b;

System.out.println("Subtraction : " + a + " - " + b + " = " + result); result


= a * b;

System.out.println("Multiplucation : " + a + " * " + b + " = " + result); result


= b / a;

System.out.println("Division : " + b + " / " + a + " = " + result);


result = b % a;

System.out.println("Modulus : " + b + " % " + a + " = " + result);


result = ++a;

System.out.println("Pre-increment : ++a = " + result);


result = b--;

System.out.println("Post-decrement : b-- = " + result);

Relational Operators (<, >, <=, >=, ==, !=)

The relational operators are the symbols that are used to compare two values. That means the relational operators
are used to check the relationship between two values. Every relational operator has two posible results either
TRUE or FALSE. In simple words, the relational operators are used to define conditions in a program. The
following table provides information about relational operators.

Operator Meaning Example


< Returns TRUE if the first value is smaller than second value 10 < 5 is FALSE
otherwise returns FALSE
> Returns TRUE if the first value is larger than second value 10 > 5 is TRUE
otherwise returns FALSE
<= Returns TRUE if the first value is smaller than or equal to 10 <= 5 is FALSE
second value otherwise returns FALSE

>= Returns TRUE if the first value is larger than or equal to 10 >= 5 is TRUE
second value otherwise returns FALSE

== Returns TRUE if both values are equal otherwise returns 10 == 5 is FALSE


FALSE

!= Returns TRUE if both values are not equal otherwise returns 10 != 5 is TRUE
FALSE
Look at the following example program.
Example

public class RelationalOperators {

public static void main(String[] args) {


boolean a;

a = 10<5;

System.out.println("10 < 5 is " + a);


a = 10>5;

System.out.println("10 > 5 is " + a);


a = 10<=5;

System.out.println("10 <= 5 is " + a);


a = 10>=5;

System.out.println("10 >= 5 is " + a);


a = 10==5;

System.out.println("10 == 5 is " + a);


a = 10!=5;

System.out.println("10 != 5 is " + a);

Logical Operators

The logical operators are the symbols that are used to combine multiple conditions into one condition. The
following table provides information about logical operators.

Operator Meaning Example

& Logical AND - Returns TRUE if all conditions are TRUE otherwise false & true =>
returns FALSE false

| Logical OR - Returns FALSE if all conditions are FALSE otherwise false | true => true
returns TRUE

^ Logical XOR - Returns FALSE if all conditions are same otherwise true ^ true => false
returns TRUE

! Logical NOT - Returns TRUE if condition is FLASE and returns !false => true
FALSE if it is TRUE
&& short-circuit AND - Similar to Logical AND (&), but once a false & true =>
decision is finalized it does not evaluate remianing. false

|| short-circuit OR - Similar to Logical OR (|), but once a decision is false | true => true
finalized it does not evaluate remianing.

◻ The operators &, |, and ^ can be used with both boolean and integer data type values. When they are used
with integers, performs bitwise operations and with boolean, performs logical operations.

◻ Logical operators and Short-circuit operators both are similar, but in case of short-circuit operators once the
decision is finalized it does not evaluate remaining expressions.

Look at the following example program.

Example

public class LogicalOperators {

public static void main(String[] args) { int


x = 10, y = 20, z = 0; boolean a
= true;

a = x>y && (z=x+y)>15;

System.out.println("a = " + a + ", and z = " + z); a


= x>y & (z=x+y)>15;
} }
System.out.println("a = " + a + ", and z = " + z);
Assignment Operators

The assignment operators are used to assign right-hand side value (Rvalue) to the left-hand side variable (Lvalue).
The assignment operator is used in different variants along with arithmetic operators. The following table
describes all the assignment operators in the java programming language.

Operator Meaning Example

= Assign the right-hand side value to left-hand side variable A = 15

+= Add both left and right-hand side values and store the result into left- A += 10
hand side variable

-= Subtract right-hand side value from left-hand side variable value and A -= B
store the result into left-hand side variable

*= Multiply right-hand side value with left-hand side variable value and A *= B
store the result into left-hand side variable

/= Divide left-hand side variable value with right-hand side variable value A /= B
and store the result into the left-hand side variable

%= Divide left-hand side variable value with right-hand side variable value A %= B
and store the remainder into the left-hand side variable

&= Logical AND assignment -

|= Logical OR assignment -

^= Logical XOR assignment -

Look at the following example program.


Example

public class AssignmentOperators {

public static void main(String[] args) {


int a = 10, b = 20, c;

boolean x = true;

System.out.println("a = " + a + ", b = " + b);


a += b;

System.out.println("a = " + a);


a -= b;

System.out.println("a = " + a);


a *= b;

System.out.println("a = " + a);


a /= b;

System.out.println("a = " + a);


a %= b;

System.out.println("a = " + a);


x |= (a>b);
System.out.println("x = " + x);
x &= (a>b);
System.out.println("x = " + x);

Bitwise Operators

The bitwise operators are used to perform bit-level operations in the java programming language.
When we use the bitwise operators, the operations are performed based on binary values.
The following table describes all the bitwise operators in the java programming language.
Let us consider two variables A and B as A = 25 (11001) and B = 20 (10100).
Operator Meaning Example

& the result of Bitwise AND is 1 if all the bits are 1 otherwise it is 0 A&B
⇒ 16
(10000)

| the result of Bitwise OR is 0 if all the bits are 0 otherwise it is 1 A|B


⇒ 29
(11101)

Operator Meaning Example

^ the result of Bitwise XOR is 0 if all the bits are same otherwise it is 1 A^B
⇒ 13 (01101)

~ the result of Bitwise once complement is negation of the bit (Flipping) ~A


⇒ 6 (00110)

<< the Bitwise left shift operator shifts all the bits to the left by the specified A << 2
number of positions ⇒ 100 (1100100)

>> the Bitwise right shift operator shifts all the bits to the right by the specified A >> 2
number of positions ⇒ 6 (00110)

Look at the following example program.


Example

public class BitwiseOperators {

public static void main(String[] args) {


int a = 25, b = 20;

System.out.println(a + " & " + b + " = " + (a & b));


System.out.println(a + " | " + b + " = " + (a | b));
System.out.println(a + " ^ " + b + " = " + (a ^ b));
System.out.println("~" + a + " = " + ~a);
System.out.println(a + ">>" + 2 + " = " + (a>>2));
System.out.println(a + "<<" + 2 + " = " + (a<<2));
System.out.println(a + ">>>" + 2 + " = " + (a>>>2));

Conditional Operators

The conditional operator is also called a ternary operator because it requires three operands. This
operator is used for decision making. In this operator, first, we verify a condition, then we perform one operation
out of the two operations based on the condition result. If the condition is TRUE the first option is performed, if
the condition is FALSE the second option is performed. The conditional operator is used with the following
syntax.
Syntax

Condition ? TRUE Part : FALSE Part;


Look at the following example program.

Example

public class ConditionalOperator {

public static void main(String[] args) {


int a = 10, b = 20, c;

c = (a>b)? a : b;
System.out.println("c = " + c);

Java Expressions

• In any programming language, if we want to perform any calculation or to frame any condition etc., we
use a set of symbols to perform the task.

• These set of symbols makes an expression.


In the java programming language, an expression is defined as follows.

An expression is a collection of operators and operands that represents a specific value.

• In the above definition, an operator is a symbol that performs tasks like arithmetic operations, logical
operations, and conditional operations, etc.

• Operands are the values on which the operators perform the task. Here operand can be a direct value or
variable or address of memory location.

Expression Types

In the java programming language, expressions are divided into THREE types. They are as follows.
• Infix Expression
• Postfix Expression
• Prefix Expression

The above classification is based on the operator position in the expression.

Infix Expression

The expression in which the operator is used between operands is called infix expression.
The infix expression has the following general structure.
Example

Postfix Expression

The expression in which the operator is used after operands is called postfix expression.
The postfix expression has the following general structure.
Example

Prefix Expression

The expression in which the operator is used before operands is called a prefix expression.
The prefix expression has the following general structure.
Example

Java Control Statements

In java, the default execution flow of a program is a sequential order. But the sequential order of execution flow
may not be suitable for all situations. Sometimes, we may want to jump from line to another line, we may want
to skip a part of the program, or sometimes we may want to execute a part of the program again and again. To
solve this problem, java provides control statements.

In java, the control statements are the statements which will tell us that in which order the instructions are getting
executed. The control statements are used to control the order of execution according to our requirements. Java
provides several control statements, and they are classified as follows.

Types of Control Statements

In java, the control statements are classified as follows.

• Selection Control Statements ( Decision Making Statements )


• Iterative Control Statements ( Looping Statements )
• Jump Statements

Let's look at each type of control statements in java.

Selection Control Statements

In java, the selection statements are also known as decision making statements or branching statements. The
selection statements are used to select a part of the program to be executed based on a condition. Java provides
the following selection statements.

• if statement
• if-else statement
• if-elif statement
• nested if statement
• switch statement

Iterative Control Statements

In java, the iterative statements are also known as looping statements or repetitive statements. The iterative
statements are used to execute a part of the program repeatedly as long as the given condition is True. Using
iterative statements reduces the size of the code, reduces the code complexity, makes it more efficient, and
increases the execution speed. Java provides the following iterative statements.

• while statement
• do-while statement
• for statement
• for-each statement

Jump Statements

In java, the jump statements are used to terminate a block or take the execution control to the next iteration. Java
provides the following jump statements.

• break
• continue
• return

In java, the selection statements are also known as decision making statements or branching statements or
conditional control statements. The selection statements are used to select a part of the program to be executed
based on a condition. Java provides the following selection statements.

• if statement
• if-else statement
• nested if statement
• if-else if statement
• switch statement

Selection Control Statements

if statement in java

In java, we use the if statement to test a condition and decide the execution of a block of statements based on that
condition result. The if statement checks, the given condition then decides the execution of a block of statements.
If the condition is True, then the block of statements is executed and if it is False, then the block of statements is
ignored. The syntax and execution flow of if the statement is as follows.
Let's look at the following example java code.
Java Program

import java.util.Scanner;
public class IfStatementTest {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
System.out.print("Enter any number: ");
int num = read.nextInt();
if((num % 5) == 0) {
System.out.println("We are inside the if-block!");
System.out.println("Given number is divisible by 5!!");
}

System.out.println("We are outside the if-block!!!");


}

In the above execution, the number 12 is not divisible by 5. So, the condition becomes False and the condition
is evaluated to False. Then the if statement ignores the execution of its block of statements.

When we enter a number which is divisible by 5, then it produces the output as follows.
if-else statement in java

In java, we use the if-else statement to test a condition and pick the execution of a block of statements out of two
blocks based on that condition result. The if-else statement checks the given condition then decides which block
of statements to be executed based on the condition result. If the condition is True, then the true block of
statements is executed and if it is False, then the false block of statements is executed. The syntax and execution
flow of if-else statement is as follows.

Let's look at the following example java code.


Java Program

import java.util.Scanner;
public class IfElseStatementTest {
public static void main(String[] args) {

Scanner read = new Scanner(System.in);


System.out.print("Enter any number: ");
int num = read.nextInt();
if((num % 2) == 0) {
System.out.println("We are inside the true-block!");
System.out.println("Given number is EVEN number!!");
}

else {
System.out.println("We are inside the false-block!");
System.out.println("Given number is ODD number!!");
}
System.out.println("We are outside the if-block!!!");
}

Nested if statement in java

Writing an if statement inside another if-statement is called nested if statement. The general syntax of the nested
if-statement is as follows.
Syntax

if(condition_1){
if(condition_2){
inner if-block of statements;
...

...

Let's look at the following example java code.


Java Program

import java.util.Scanner;
public class NestedIfStatementTest {
public static void main(String[] args) {

Scanner read = new Scanner(System.in);


System.out.print("Enter any number: ");
int num = read.nextInt();
if (num < 100) {

System.out.println("\nGiven number is below 100");


if (num % 2 == 0)
System.out.println("And it is EVEN");
else
System.out.println("And it is ODD");
} else
System.out.println("Given number is not below 100");

System.out.println("\nWe are outside the if-block!!!");


}

}
if-else if statement in java

Writing an if-statement inside else of an if statement is called if-else-if statement. The general syntax of the an
if-else-if statement is as follows.
Syntax

if(condition_1){
condition_1 true-block;
...

else if(condition_2){
condition_2 true-block;
condition_1 false-block too;
...

Let's look at the following example java code.

Java Program

import java.util.Scanner;
public class IfElseIfStatementTest {
public static void main(String[] args) {
int num1, num2, num3;
Scanner read = new Scanner(System.in);
System.out.print("Enter any three numbers: ");
num1 = read.nextInt();
num2 = read.nextInt();
num3 = read.nextInt();
if( num1>=num2 && num1>=num3)
System.out.println("\nThe largest number is " + num1) ;
else if (num2>=num1 && num2>=num3)
System.out.println("\nThe largest number is " + num2) ;
else
System.out.println("\nThe largest number is " + num3) ;
System.out.println("\nWe are outside the if-block!!!");
}

switch statement in java

Using the switch statement, one can select only one option from more number of options very easily. In the switch
statement, we provide a value that is to be compared with a value associated with each option. Whenever the
given value matches the value associated with an option, the execution starts from that option. In the switch
statement, every option is defined as a case.
The switch statement has the following syntax and execution flow diagram.
Let's look at the following example java code.

Java Program

import java.util.Scanner;
public class SwitchStatementTest {
public static void main(String[] args) {
Scanner read = new Scanner(System.in);
System.out.print("Press any digit: ");
int value = read.nextInt();
switch( value )
{

case 0: System.out.println("ZERO") ; break ;


case 1: System.out.println("ONE") ; break ;
case 2: System.out.println("TWO") ; break ;
case 3: System.out.println("THREE") ; break ;
case 4: System.out.println("FOUR") ; break ;
case 5: System.out.println("FIVE") ; break ;
case 6: System.out.println("SIX") ; break ;
case 7: System.out.println("SEVEN") ; break ;
case 8: System.out.println("EIGHT") ; break ;
case 9: System.out.println("NINE") ; break ;
default: System.out.println("Not a Digit") ;
}

Java Iterative Statements

The java programming language provides a set of iterative statements that are used to execute a statement or a
block of statements repeatedly as long as the given condition is true. The iterative statements are also known as
looping statements or repetitive statements. Java provides the following iterative statements.

• while statement
• do-while statement
• for statement
• for-each statement
while statement in java

The while statement is used to execute a single statement or block of statements repeatedly as long as the given
condition is TRUE. The while statement is also known as Entry control looping statement. The syntax and
execution flow of while statement is as follows.

Let's look at the following example java code.

Java Program

ipublic class WhileTest {


public static void main(String[] args) {
int num = 1;
while(num <= 10) {
System.out.println(num);
num++;
}

System.out.println("Statement after while!");


}

do-while statement in java

The do-while statement is used to execute a single statement or block of statements repeatedly as long as given
the condition is TRUE. The do-while statement is also known as the Exit control looping statement. The do-
while statement has the following syntax.
Let's look at the following example java code.

Java Program

public class DoWhileTest {


public static void main(String[] args) {
int num = 1;
do {
System.out.println(num);
num++;
}while(num <= 10);
System.out.println("Statement after do-while!");
}

for statement in java

❖ The for statement is used to execute a single statement or a block of statements repeatedly as long as the
given condition TRUE.
❖ In for-statement, the execution begins with the initialization statement.
❖ After the initialization statement, it executes Condition.
❖ If the condition is evaluated to true, then the block of statements executed otherwise it terminates the
for-statement.
❖ After the block of statements execution, the modification statement gets executed, followed by
condition again.
is T

Let's look at the following example java code.


Java Program

public class ForTest {


public static void main(String[] args) {
for(int i = 0; i < 10; i++) {
System.out.println("i = " + i);
}

System.out.println("Statement after for!");


}

for-each statement in java

The Java for-each statement was introduced since Java 5.0 version. It provides an approach to traverse through
an array or collection in Java. The for-each statement also known as enhanced for statement. The for-each
statement executes the block of statements for each element of the given array or collection.
◻ In for-each statement, we can not skip any element of given array or collection.

The for-each statement has the following syntax and execution flow diagram.

Let's look at the following example java code.


Java Program

public class ForEachTest {


public static void main(String[] args) {
int[] arrayList = {10, 20, 30, 40, 50};
for(int i : arrayList) {
System.out.println("i = " + i);
}

System.out.println("Statement after for-each!");


}

}
Java Jump Statements

The java programming language supports jump statements that used to transfer execution control from one line
to another line. The java programming language provides the following jump statements.

• break statement

• continue statement

• labelled break and continue statements


• return statement

break statement in java

The break statement in java is used to terminate a switch or looping statement. That means the break statement
is used to come out of a switch statement and a looping statement like while, do-while, for, and for-each.
◻ Using the break statement outside the switch or loop statement is not allowed.

The following picture depicts the execution flow of the break statement.

Let's look at the following example java code.


Java Program

public class JavaBreakStatement {


public static void main(String[] args) {
int list[] = {10, 20, 30, 40, 50};
for(int i : list) {

if(i == 30)
break;
System.out.println(i);
}

continue statement in java

The continue statement is used to move the execution control to the beginning of the looping statement. When

the continue statement is encountered in a looping statement, the execution control skips the rest of the statements
in the looping block and directly jumps to the beginning of the loop. The continue statement can be used with

looping statements like while, do-while, for, and for-each.

When we use continue statement with while and do-while statements, the execution control directly jumps to the
condition. When we use continue statement with for statement the execution control directly jumps to the

modification portion (increment/decrement/any modification) of the for loop. The continue statement flow of
execution is as shown in the following figure.

Let's look at the following example java code.


Java Program

public class JavaContinueStatement {


public static void main(String[] args) {
int list[] = {10, 20, 30, 40, 50};
for(int i : list) {
if(i == 30)
continue;
System.out.println(i);
}

Labelled break and continue statement in java

The java programming langauge does not support goto statement, alternatively, the break and continue
statements can be used with label.

The labelled break statement terminates the block with specified label. The labbeled contonue statement takes
the execution control to the beginning of a loop with specified label.

Let's look at the following example java code.


Java Program

import java.util.Scanner;
public class JavaLabelledStatement {
public static void main(String args[]) {
Scanner read = new Scanner(System.in);
reading: for (int i = 1; i <= 3; i++) {
System.out.print("Enter a even number: ");
int value = read.nextInt();
verify: if (value % 2 == 0) {
System.out.println("\nYou won!!!");
System.out.println("Your score is " + i*10 + " out of 30.");

break reading;
} else {
System.out.println("\nSorry try again!!!");
System.out.println("You let with " + (3-i) + " more options...");
continue reading;
}

}
return statement in java

In java, the return statement used to terminate a method with or without a value. The return statement takes the
execution control to the calling function. That means the return statement transfer the execution control from
called function to the calling function by carrying a value.
◻ Java allows the use of return-statement with both, with and without return type methods.

In java, the return statement used with both methods with and without return type. In the case of a method with

the return type, the return statement is mandatory, and it is optional for a method without return type.

When a return statement used with a return type, it carries a value of return type. But, when it is used without a
return type, it does not carry any value. Instead, simply transfers the execution control.

Let's look at the following example java code.


Java Program

import java.util.Scanner;
public class JavaReturnStatementExample {
int value; int readValue() {
Scanner read = new Scanner(System.in);
System.out.print("Enter any number: ");
return this.value=read.nextInt(); }
void showValue(int value) {
for(int i = 0; i <= value; i++) {
if(i == 5) return;

System.out.println(i);
} }
public static void main(String[] args) {

JavaReturnStatementExample obj = new JavaReturnStatementExample();


obj.showValue(obj.readValue());

} }

You might also like