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

UNIT I java

Java is a high-level, robust, secured, and object-oriented programming language developed by James Gosling at Sun Microsystems and released in 1995. It is widely used for various applications, including desktop and web applications, mobile operating systems, and embedded systems, and features such as platform independence, security, and multithreading. The Java architecture comprises the Java Development Kit (JDK), Java Runtime Environment (JRE), and Java Virtual Machine (JVM), which together facilitate the development and execution of Java programs.

Uploaded by

aswinrsgc
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 views88 pages

UNIT I java

Java is a high-level, robust, secured, and object-oriented programming language developed by James Gosling at Sun Microsystems and released in 1995. It is widely used for various applications, including desktop and web applications, mobile operating systems, and embedded systems, and features such as platform independence, security, and multithreading. The Java architecture comprises the Java Development Kit (JDK), Java Runtime Environment (JRE), and Java Virtual Machine (JVM), which together facilitate the development and execution of Java programs.

Uploaded by

aswinrsgc
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/ 88

Java Programming

Java is a programming language and a platform. Java is a high level,


robust, secured and object-oriented programming language.

History of Java

• Originally developed by James Gosling at Sun Microsystems (which is


now a subsidiary of Oracle Corporation) and released in 1995.

• The initial name was Oak but it was renamed to Java in 1995 as OAK was
a registered trademark of another Tech company.

• Java is an island of Indonesia where first coffee was produced (called java
coffee).

• Notice that Java is just a name not an acronym.

• In 1995, Time magazine called Java one of the Ten Best Products of 1995.

• JDK 1.0 released in (January 23, 1996).


James Gosling
Java Version History

• There are many java versions that has been released. Current stable release of Java is
Java SE 16.

• JDK Alpha and Beta (1995)


• JDK 1.0 (23rd Jan, 1996)
• JDK 1.1 (19th Feb, 1997)
• J2SE 1.2 (8th Dec, 1998)
• J2SE 1.3 (8th May, 2000)
• J2SE 1.4 (6th Feb, 2002)
• J2SE 5.0 (30th Sep, 2004)
• Java SE 6 (11th Dec, 2006)
• Java SE 7 (28th July, 2011)
• Java SE 8 (18th March, 2014)
• Java SE 9 (21st Sep, 2017)
• Java SE 10 (20th March, 2018)
• Java SE 11 (25th Sep, 2018)
• Java SE 12 (19th March, 2019)
• Java SE 13 (19th Sep, 2019)
• Java SE 14 (17th March, 2020)
• Java SE 15 (15th Sep, 2020)
• Java SE 16 (16th March, 2021)

Application of Java

Java is widely used in every corner of world and of human life. Java is not only
used in softwares but is also widely used in designing hardware controlling
software components. There are more than 930 million JRE downloads each
year and 3 billion mobile phones run java.

Following are some other usage of Java :

1. Developing Desktop Applications

2. Web Applications like Linkedin.com, Snapdeal.com etc

3. Mobile Operating System like Android

4. Embedded Systems
5. Robotics and games etc.

Features of Java
Following are some of the useful and advanced features of java:

1. Simple

Java is a very simple programming language, it is easy to learn, read and write
in Java. The syntax of Java is clean and easy to understand. Here’s why java
is simple programming language compared to other popular programming
language:

 Java syntax is similar to C/C++ so it is easier to learn java if one is


familiar with C or C++. However java doesn’t use the complex features of
C and C++ such as Pointers, go to statements, preprocessors/ header files,
multiple inheritance, operator overloading etc.
 There is no need to remove unreferenced objects explicitly as there is an
Automatic Garbage Collection in Java.

2. Platform Independent

Java is a platform independent language. Compiler(javac) converts source code


(.java file) to the byte code(.class file). JVM executes the bytecode produced
by compiler. This byte code can run on any platform such as Windows, Linux,
Mac OS etc. Which means a program that is compiled on windows can run on
Linux and vice-versa.

Each operating system has different JVM, however the output they produce
after execution of bytecode is same across all operating systems. That is why
we call java as platform independent language.
3. Secure

Security is one of the biggest concerns in programming language as these


programming langauges are used to develop some of the critical and sensitive
applications that needs to be secured such as banking applications. Java is more
secure than C/C++ as does not allow developers to create pointers, thus it
becomes impossible to access a variable from outside if it’s not been
initialized. We don’t have pointers and we cannot access out of bound arrays
(you get ArrayIndexOutOfBoundsException if you try to do so) in java. That’s
why several security flaws like stack corruption or buffer overflow is
impossible to exploit in Java.

4. Object-Oriented Programming language

Object oriented programming is a way of organizing programs as collection of


objects, each of which represents an instance of a class. The main concepts of
Object Oriented programming are:

1. Abstraction
2. Encapsulation
3. Inheritance
4. Polymorphism

5. Robust

Robust means reliable. Java programming language is developed in a way that


puts a lot of emphasis on early checking for possible errors, that’s why java
compiler is able to detect errors that are not easy to detect in other
programming languages.
The main features of java that makes it robust are:

1. Garbage collection,
2. Exception Handling
3. Memory allocation.

6. Distributed

Using java programming language we can create distributed applications.


RMI(Remote Method Invocation) and EJB(Enterprise Java Beans) are used for
creating distributed applications in java.

In simple words: The java programs can be distributed on more than one
systems that are connected to each other using internet connection.

7. Multithreading

Java supports multithreading. Multithreading is a Java feature that allows


concurrent execution of two or more parts of a program for maximum
utilisation of CPU.

8. Portable

As discussed above, java code that is written on one machine can run on
another machine. The platform independent byte code can be carried to any
platform for execution that makes java code portable.

9. Architectural Neutral

As we know Java is a platform independent language, which means program


written and compiled on one machine can run on any other machine having
different operating system. Java follows the principle of “Write once run
anywhere“

Compiler converts the java file into byte-code and this byte code is machine
independent, java virtual machine can easily translate this byte code into
machine specific code. This makes java architectural neutral programming
language.

Java is architecture neutral because there are no implementation dependent


features, for example, the size of primitive types is fixed. In C programming,
int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes of
memory for 64-bit architecture. However, it occupies 4 bytes of memory for
both 32 and 64-bit architectures in Java.

10. Dynamic

Java is a dynamic programming language. OOPs allows developers to add new


classes to the existing packages, add new methods to the existing classes as
well as modifying the method without changing the original method code by
using the concept of method overriding. All these features make java dynamic.
It also allows classes to be loaded on demand. It also supports functions from
its native languages such as C and C++.

11. Performance

Java is significantly faster than other traditional interpreted programming


languages. Compiled java code which is known as byte code is like a machine
code, that allows a faster execution. Java uses Just in Time compiler which can
execute the code on demand, this allows to execute only the method that is
being called, which makes it faster and efficient.
Also java uses the concept of multithreading, which allows concurrent
execution of several parts of the code at the same time. This provides high
performance.

Components of Java Architecture

The Java architecture includes the three main components:

o Java Virtual Machine (JVM)

o Java Runtime Environment (JRE)

o Java Development Kit (JDK)

JDK (Java Development Kit)

1. JDK stands for Java Development Kit. To install Java on your system,
you need to first install JDK on your system.
2. JDK contains the tools that you need, in order to write and execute java
programs.
3. JDK consists of Private JRE, JVM, compiler, Java application launcher,
etc. It also provides the Standard Edition (SE) of java API.
So from the above diagram, we can conclude that,

JRE = JVM + library classes.


JDK = JRE + Developer tools.
Features of JDK

1. The JDK comes with a complete Java Runtime Environment (JRE), that
is different from the regular JRE thats the reason it is usually called a
private runtime so we can say that it includes all the features that JRE has.
2. It has all the java development tools such as compiler, JVM, JRE,
debugger etc.
3. You need jdk in order to write and run java program.
4. JDK supports multiple platforms and can be installed on Windows, Mac
and other operating systems.

JRE (Java Runtime Environment)

1. JRE stands for Java Runtime Environment. It provides runtime


environment for java applications.
2. You need JRE in order to run java programs. If you are not a developer
and not writing java programs, you do not need JDK but you still need
JRE to run java programs.
3. All the JDK already comes with JRE so you do not need to download and
install it separately.
4. JRE contains set of libraries and other files that JVM uses at runtime.

Features of JRE

1. JRE contains set of libraries and other tools that JVM needs at runtime.
2. You can easily run any java program on JRE but you need jdk to write
and compile java programs.
3. JRE contains libraries that are required for integrations such as Java
Database Connectivity (JDBC), Java Naming and Directory Interface
(JNDI), Remote Method Invocation (RMI) etc.

JVM (Java Virtual Machine)

Java Virtual Machine (JVM) is a virtual machine that resides in the real
machine (your computer) and the machine language for JVM is byte code.
This makes it easier for compiler as it has to generate byte code for JVM rather
than different machine code for each type of machine. JVM executes the byte
code generated by compiler and produce output. JVM is the one that makes
java platform independent.

Features of JVM

1. JVM makes it possible to run java code on any machine, it is the JVM
that makes java truly platform independent.
2. It also allows to run java applications on cloud platforms.
3. JDK and JRE both of these contain JVM.
4. JVM is an interpreter as it executes the java code line by line.
5. JVM converts the bytecode into machine code. JVM is platform
independent as JVM doesn’t depend on the hardware and operating
system of the machine.
Differences between C, C++, and Java
OOPs Concepts in JAVA

The following are the major characteristics of OOP‟s:

Objects

• Objects are basic building blocks for designing programs.

• An object is a collection of data members and associated member functions.

• An object may represent a person, place or a table of data.

• Each object is identified by a unique name. Each object must be a member of a particular
class.

• Example: Apple, orange, mango

Classes

• The objects can be made user defined data types with the help of a class.
• A class is a collection of objects that have identical properties, common
behavior and shared relationship.

• Once class is defined, any number of objects of that class is created.

• Classes are user defined data types.

• A class can hold both data and functions.

• For example: Planets, sun, moon are member of class solar system.

Abstraction

Abstraction is the concept of hiding the internal details and describing things in
simple terms. Data Abstraction refers to the process of representing essential
features without including background details or explanations.For example, a
method that adds two integers. The internal processing of the method is hidden
from the outer world. There are many ways to achieve abstraction in object-
oriented programmings, such as encapsulation and inheritance.

Consider a real-life example of a man driving a car. The man only knows that
pressing the accelerators will increase the car speed or applying brakes will
stop the car, but he does not know how on pressing the accelerator, the speed
is actually increasing. He does not know about the inner mechanism of the car
or the implementation of the accelerators, brakes etc. in the car. This is what
abstraction is.

A Java program is also a great example of abstraction. Here java takes care of
converting simple statements to machine language and hides the inner
implementation details from the outer world. In Java, abstraction is achieved
by interfaces and abstract classes.

Data Encapsulation:

The wrapping of data and functions into a single unit (class) is called
data encapsulation. Data encapsulation enables data hiding and information
hiding.

Inheritance

Inheritance is the process by which objects of one class acquire some


properties of objects of another class. Inheritance supports the concept of
hierarchical classification.

In OOP, the idea of inheritance provides the concept of reusability. It means


that we can add additional features to parent class without modification; this is
possible by deriving a new class from the parent class. The new class consists
of the combined features from both the classes. In Java, the derived class is
also known as the subclass.
• The existing class is known as base class or super class.
• The new class is known as derived class or sub class.
• The derived class shares the properties of the base class. Therefore a
code from a base class can be reused by a derived class.

Polymorphism

Polymorphism is an important OOP concept; it means the ability to take many


forms. For Example, an operation exhibits different behavior in different
situations. The behavior depends on the type of data used in operation. For
Example, in the operation of addition, the operation generates a sum for two
numbers. If the operands are strings, then a third-string is produced by the
operation by concatenation. The figure below demonstrates that a single
function name can be used to handle the different numbers and different types
of arguments.
Dynamic binding

Binding is the process of connecting one program to another. Dynamic


binding is the process of linking the procedure call to a specific sequence of
code or function at run time or during the execution of the program.

Message Passing

Message Passing is nothing but sending and receving of information by


the objects same as people exchange information. So this helps in building
systems that simulate real life. Following are the basic steps in message
passing.

 Creating classes that define objects and its behaviour.


 Creating objects from class definitions
 Establishing communication among objects
Message passing involves specifying the name of the object, the name of the
function (message) and the information to be sent.
Association

Association is the OOPS concept to define the relationship between objects.


The association defines the multiplicity between objects. For example Teacher
and Student objects. There is a one-to-many relationship between a teacher and
students. Similarly, a student can have a one-to-many relationship with teacher
objects. However, both student and teacher objects are independent of each
other. Association represents the relationship between the objects. Here, one
object can be associated with one object or many objects. There can be four
types of association between the objects:

o One to One
o One to Many
o Many to One, and
o Many to Many

Let's understand the relationship with real-time examples. For example, One
country can have one prime minister (one to one), and a prime minister can
have many ministers (one to many). Also, many MP's can have one prime
minister (many to one), and many ministers can have many departments (many
to many).

Association can be unidirectional or bidirectional.

Aggregation is a special form of association which is a unidirectional one way


relationship between classes (or entities), for e.g. Wallet and Money classes.
Wallet has Money but money doesn’t need to have Wallet necessarily so its a
one directional relationship. In this relationship both the entries can survive if
other one ends. In our example if Wallet class is not present, it does not mean
that the Money class cannot exist.
Composition is a restricted form of Aggregation in which two entities (or you
can say classes) are highly dependent on each other. For e.g. Human and Heart.
A human needs heart to live and a heart needs a Human body to survive. In
other words when the classes (entities) are dependent on each other and their
life span are same (if one dies then another one too) then its a composition.
Heart class has no sense if Human class is not present.

Basic Structure of Java Program


Documentation Section

It is used to improve the readability of the program. It consists of comments in


Java which include basic information such as the method’s usage or
functionality to make it easier for the programmer to understand it while
reviewing or debugging the code. A Java comment is not necessarily limited to
a confined space, it can appear anywhere in the code.

The compiler ignores these comments during the time of execution and is
solely meant for improving the readability of the Java program.

There are three types of comments that Java supports

 Single line Comment


 Multi-line Comment
 Documentation Comment

Let’s take a look at an example to understand how we can use the above-
mentioned comments in a Java program.

Package Statement
There is a provision in Java that allows you to declare your classes in a
collection called package. There can be only one package statement in a Java
program and it has to be at the beginning of the code before a
ny class or interface declaration. This statement is optional, for example,
take a look at the statement below.

This statement declares that all the classes and interfaces defined in this source
file are a part of the student package. And only one package can be declared in
the source file.

Import Statement
Many predefined classes are stored in packages in Java, an import statement is
used to refer to the classes stored in other packages. An import statement is
always written after the package statement but it has to be before any class
declaration. We can import a specific class or classes in an import statement.
Take a look at the example to understand how import statement works in Java.

Interface Section
This section is used to specify an interface in Java. It is an optional section
which is mainly used to implement multiple inheritance in Java. An interface is
a lot similar to a class in Java but it contains only constants
and method declarations.

An interface cannot be instantiated but it can be implemented by classes or


extended by other interfaces.
Class Definition

A Java program may contain several class definitions, classes are an essential
part of any Java program. It defines the information about the user-defined
classes in a program. A class is a collection of variables and methods that
operate on the fields. Every program in Java will have at least one class with
the main method.

Main Method Class


The main method is from where the execution actually starts and follows the
order specified for the following statements. Let’s take a look at a sample
program to understand how it is structured.

Let’s analyze the above program line by line to understand how it works.
public class Example

This creates a class called Example. You should make sure that the class name
starts with a capital letter, and the public word means it is accessible from any
other classes.

Comments

To improve the readability, we can use comments to define a specific note or


functionality of methods, etc for the programmer.

Braces

The curly brackets are used to group all the commands together. To make sure
that the commands belong to a class or a method.

public static void main

 When the main method is declared public, it means that it can be used
outside of this class as well.
 The word static means that we want to access a method without making
its objects. As we call the main method without creating any objects. The
word static means that we want to access a method without making
object of the class within which the method is declared. We call the main
method without creating any objects.
 The word void indicates that it does not return any value. The main is
declared as void because it does not return any value.
 Main is the method, which is an essential part of any Java program.
String[] args

It is an array where each element is a string, which is named as args. If you run
the Java code through a console, you can pass the input parameter. The main()
takes it as an input.

System.out.println();

The statement is used to print the output on the screen where the system is a
predefined class, out is an object of the system class. The method println prints
the text on the screen with a new line. All Java statements end with a
semicolon.

Life cycle of a java program


Life cycle of a java program tells us what happens right from the point when
we type source code in a text editor to the point that source code is converted
into machine code (0’s and 1’s).

There are three main stages in the life cycle of a java program. They are:

 Editing the program


 Compiling the source code
 Executing the byte code

First, you will start with typing the program in a text-editor (ex: notepad,
notepad++, wordpad, textedit etc). After completing editing of the program, we
have to save the file. While saving the file you should remember that the file
must be saved with .java extension. For example, let’s think that I had written a
Java program which contains a single class Sample (more on classes in future
posts). It is a good convention to save the file with the name of the class. So, as
per my example, the file will be saved as Sample.java.

Second step is compilation. The name of the Java compiler is javac. The input
to the compiler is Java source code which is available in Sample.java. The
output of the compiler is machine independent or platform independent code
which is known as bytecode. The file which is generated after compilation
is .class file. As per my example, the bytecode file will be Sample.class.

Last step is execution. The bytecode generated by the compiler will be


executed by Java Virtual Machine (JVM). Input to the JVM is bytecode and
output is machine code (0’s and 1’s) which will be executed by the CPU of the
local machine.
We can use any text editor to create the high-level Java text file. This file is
saved as a .java file on the disk. We then compile this text file using the Java
compiler, which result in a .class file being created on the disk. The .class file
contains the bytecodes. The file is then loaded into memory by the class loader.
The bytecode verifier confirms that the bytecodes are valid and not hostile.
Finally, the JVM reads the bytecodes in memory and translates them into
machine code.

Comments

Comments in Java are the statements that are not executed by the compiler and interpreter. It
can be used to provide information or explanation about the variable, method, class or any
statement. It can also be used to hide program code for a specific time.
Types of Comments
Basically, there are three types of comments in Java. They are as follows:

 Single-line comments
 Multi-line comments
 Documentation comments

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).
Syntax-

// A comment is written here

Example

// This is a comment

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

2. Java Multi-line Comments

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


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

Example

/* The code below will print the words Hello World

to the screen, and it is amazing */

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

3. Documentation Comments

This type of comments is used generally when you are writing code for a project/ software
package. It helps you to generate a documentation page for reference, which can be used for
getting information about methods present, its parameters, etc. The documentation
comment statement is used to create documentation of APIs. To generate documentation of
API, you need to use the Javadoc tool.
Example
Java Data Types
Data types are divided into two groups:

 Primitive data types - includes byte, short, int, long, float, double, boolean and char
 Non-primitive data types – such as String,interfaces, Arrays ,enum and Classes.
Primitive Data Types
A primitive data type specifies the size and type of variable values, and it has no additional
methods.There are eight primitive data types in Java:

Data Type Size Description

Byte 1 byte Stores whole numbers from -128 to 127

Short 2 bytes Stores whole numbers from -32,768 to 32,767

Int 4 bytes Stores whole numbers from -2,147,483,648 to 2,147,483,647

Long 8 bytes Stores whole numbers from -9,223,372,036,854,775,808 to


9,223,372,036,854,775,807

Float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7


decimal digits

Double 8 bytes Stores fractional numbers. Sufficient for storing 15 decimal


digits
boolean 1 bit Stores true or false values

Char 2 bytes Stores a single character/letter or ASCII values

Example

float myNum = 5.75f;

System.out.println(myNum);

double myNum = 19.99d;

System.out.println(myNum);

The float and double data types can store fractional numbers. Note that you should end the value
with an "f" for floats and "d" for doubles: The precision of a floating point value indicates how
many digits the value can have after the decimal point. The precision of float is only six or seven
decimal digits, while double variables have a precision of about 15 digits. Therefore it is safer to
use double for most calculations.
Variables
Variables are containers for storing data values.

In Java, there are different types of variables, for example:

 String - stores text, such as "Hello". String values are surrounded by double quotes
 int - stores integers (whole numbers), without decimals, such as 123 or -123
 float - stores floating point numbers, with decimals, such as 19.99 or -19.99
 char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single
quotes
 boolean - stores values with two states: true or false

Declaring (Creating) Variables


To create a variable, you must specify the type and assign it a value:

Syntax

type variableName = value;

Where type is one of Java's types (such as int or String), and variableName is the name of the
variable (such as x or name). The equal sign is used to assign values to the variable.

Example1

String name = "John";

System.out.println(name);

Example 2

int myNum = 5;

float myFloatNum = 5.99f;


char myLetter = 'D';

boolean myBool = true;

String myText = "Hello";

Final Variables

If you don't want others (or yourself) to overwrite existing values, use the final keyword (this
will declare the variable as "final" or "constant", which means unchangeable and read-only):

final int myNum = 15;

myNum = 20; // will generate an error: cannot assign a value to a final variable

Keywords

Java keywords are also known as reserved words. Keywords are


particular words that act as a key to a code. These are predefined
words by Java so they cannot be used as a variable or object name or
class name. A keyword is a reserved word that conveys special meaning to the
Java compiler.
Literals

In Java, literals are the 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:

Integer Literals:

Integers are probably the most commonly used type in the typical program. Any whole number
value is an integer literal. The integer literal can be specified in four ways :

Decimal (Base-10): Digits from 0-9 are allowed in this form. Example: int x=101;

Octal (Base-8): Digits from 0 – 7 are allowed. It should always have a prefix 0. Example: int
x=0146;

Hexa-Decimal (Base-16): Digits 0-9 are allowed and also characters from a-f are allowed in this
form. Furthermore, both uppercase and lowercase characters can be used, Java provides an
exception here. A literal in this type should have a prefix 0x and 0X Example: int x =
0X123Face;

Binary: A literal in this type should have a prefix 0b and 0B, from 1.7 one can also specify in
binary literals, i.e. 0 and 1. Example: int x = 0b1111;
Floating-Point Literals

Floating-point numbers represent decimal values with a fractional component. For Floating-
point data types, we can specify literals in only decimal form and we can’t specify in Octal and
Hexadecimal forms.
Decimal (Base-10): In this form, the allowed digits are 0-9.
Example: double d = 123.456;

Boolean Literal

Boolean literals are simple. There are only two logical values that a boolean value can have, true
and false. The values of true and false do not convert into any numerical representation. The true
literal in Java does not equal 1, nor does the false literal equal 0.

Example: boolean b = true;

Character Literal
A literal character is represented inside a pair of single quotes. There are four types of character
literal:
1. Single-Quote: Java Literal can be specified to a char data type as a single character
within a single quote.
Example: char ch = „a‟;
2. Char as Integral: A char literal in Java can specify an integral literal which also
represents the Unicode value of a character.
Example: char ch = 062;
3. Unicode Representation: Char literals can specify in Unicode representation ‘\uxxxx’.
Here XXXX represents 4 hexadecimal numbers.
Example: char ch = „\u0061‟; // Here 0061 represent a.
4. Escape Sequence: Escape sequences can also specify as char literal.
Example: char ch = „\n‟;

String Literals:
String Literals in Java are specified like they are in most other languages – by enclosing a
sequence of characters between a pair of double quotes.
Example: String s = “Hello”;

Scope of Variables in Java

The scope of variables in Java is a location (or region) of the program where
the variable is visible to a program and can be accessible. Scope of a variable
refers to in which areas or sections of a program can the variable be accessed
and lifetime of a variable refers to how long the variable stays alive in
memory.

In other words, the variable scope is the location from which we can access its
value. The scope of variables determines its accessibility for other parts of the
program. Java allows declaring variables within any block. A block defines a
scope that starts with an opening curly brace and ends with a closing curly
brace.

There are three types of variables in java, depending on their scope:


 local variables
 instance variables
 class variables (static variables).

1) Scope of Local Variables

1. When we create a local variable inside a method, constructor, or block, its


scope only remains within the method, block, or constructor.
They are visible only within the method, constructor, or block. As you exit
from the method or block, then the scope of a local variable is destroyed.
Scope of a local variable is within the block in which it is declared and
the lifetime of a local variable is until the control leaves the block in which it
is declared.

2. We cannot access local variables from outside the method, constructor, or


block.

2) Scope of Instance variables

1. When we define an instance variable inside a class, its scope is within the
class. It is visible inside all the methods, constructors, and from the beginning
of its program block to the end of program block in the class. General scope of
an instance variable is throughout the class except in static methods. Lifetime
of an instance variable is until the object stays in memory.

Therefore, all the methods, constructors, and blocks inside the class can access
instance variables. Normally, it is recommended to make these variables
private in the class.

However, the visibility of instance variables for the sub-classes can be given
with the use of access modifiers.
2. In the user-defined method, we can access the instance variables directly by
calling the variable name inside the class.

3. Within static methods and different classes, instance variables should be


called using object reference variable.

4. Values for instance variables can be assigned during the declaration or


within the constructor. Instance variables can be accessed directly by calling
the variable name inside the class. Instance variables are created when an
object is created and destroyed once the object is destroyed.

It has the following general form:


ObjectReference.VariableName;

3) Scope of Static variables


In Java class variables are declared using static keywords in a class, but outside a
method, constructor, or block. They are also known as static variables. Static
variables are created when the program starts and destroyed when the program ends.
There can be only one copy of a class variable, regardless of how many call objects
are created. All of the instance of that class shares the same copy of a static variable.
General scope of a class variable is throughout the class and
the lifetime of a class variable is until the end of the program or as long
as the class is loaded in memory. When we declare an instance variable in
java, a separate copy will be created for every object. But in the case of a
static variable, a single copy is created at the class level and shared by all
objects of that class.
When we define a variable with a static keyword inside the class, its
scope is within the class. That is, the scope of a static variable is within
the class.
When declaring class variables as public static final, then variable names
(constants) are all in upper case. If the static variables are not public and
final, the naming syntax is the same as instance and local variables.

Static/Class variables can be accessed outside with the class name as


follows
Syntax:-

ClassName.VariableName;

The visibility of the static variable is similar to the instance variable.

Example:-
class A {
String name = "Steve"; //instance variable
static double salary = 25000.5; //static variable
public static void main(String[] args)
{
int age = 35; //local variable
}
}

class CSEStudent

static int id = 5;

int stud_id;

String stud_name;

class StudentDemo

public static void main(String[] args)

CSEStudent s1 = new CSEStudent();


s1.stud_id = 5001;

s1.stud_name = "John";

CSEStudent s2 = new CSEStudent();

S2.stud_id = 5002;

S2.stud_name = "Kevin";

System.out.println("Branch id & student id:" +s1.id

+s1.stud_id);

System.out.println("Branch id & student id:" +s2.id

+s2.stud_id);

}
Control Statements
Selection Statements/Conditional/Decision Making statements

if Statement

The Java if statement tests the condition. It executes the if block if condition is
true. The condition is any expression that returns a boolean value.

Example

if-else Statements
The Java if-else statement also tests the condition. It executes the if block if
condition is true otherwise else block is executed.

Syntax:

if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}

Example
Nested if

The nested if statement represents the if block within another if block. Here, the
inner if block condition executes only when outer if block condition is true.
Nested if statements mean an if statement inside an if statement. Yes, java
allows us to nest if statements within if statements. i.e, we can place an if
statement inside another if statement.

Syntax:

if(condition)
{
statement;
if(condition)
statement;
}
else
statement;
Example

public class Example


{
public static void main(String args[])
{
int s = 18;
if (s > 10)
{
if (s%2==0)
{
System.out.println("s is an even number and greater than 10!");
}
else
{
System.out.println("s is a odd number and greater than 10!");
}
}
else
{
System.out.println("s is less than 10");
}
System.out.println("Hello World!");
}
}

Output:
s is an even number and greater than 10!
Hello World!

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. In
other words, the switch statement tests the equality of a variable against
multiple values.

o There can be one or N number of case values for a switch expression.

o The case value must be of switch expression type only. The case value must be literal or
constant. It doesn't allow variables.

o The case values must be unique. In case of duplicate value, it renders compile-time error.

o The Java switch expression must be of byte, short, int, long (with its Wrapper
type), enums and string.
o Each case statement can have a break statement which is optional. When control reaches to
the break statement, it jumps the control after the switch expression. If a break statement is
not found, it executes the next case.

o The case value can have a default label which is optional.

Syntax:

switch(expression)
{
case value1:
//code to be executed;
break;
case value2:
//code to be executed;
break;
........................
default:
code to be executed if all cases are not matched;
}
Example:
public class Example {
public static void main(String[] args) {
//Declaring a variable for switch expression
int number=20;

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");
}
}
}

if-else-if ladder Statement

Here, a user can decide among multiple options. The if statements are
executed from the top down. As soon as one of the conditions controlling the
if is true, the statement associated with that if is executed, and the rest of the
ladder is bypassed. If none of the conditions is true, then the final else
statement will be executed.

Syntax

if(condition1)
{
//code to be executed if condition1 is true
}
else if(condition2)
{
//code to be executed if condition2 is true
}
else if(condition3)
{
//code to be executed if condition3 is true
}
................
Else
{
//code to be executed if all the conditions are false
}
Example

public class Example {


public static void main(String[] args) {
int number=-13;
if(number>0)
{
System.out.println("POSITIVE");
}
else if(number<0)
{
System.out.println("NEGATIVE");
}
else{
System.out.println("ZERO");
}
}
}

Output:

NEGATIVE

Loops in Java

Looping in programming languages is a feature which facilitates the


execution of a set of instructions/functions repeatedly while some condition
evaluates to true. Java provides three ways for executing the loops.

While Loop
Syntax :

while (boolean condition)

loop statements...

Flowchart:

 While loop starts with the checking of condition. If it evaluated to true,


then the loop body statements are executed otherwise first statement
following the loop is executed. For this reason it is also called Entry
control loop
 Once the condition is evaluated to true, the statements in the loop body
are executed. Normally the statements contain an update value for the
variable being processed for the next iteration.
 When the condition becomes false, the loop terminates which marks the
end of its life cycle.

Example:
for loop:

for loop provides a concise way of writing the loop structure. Unlike a while
loop, a for statement consumes the initialization, condition and
increment/decrement in one line thereby providing a shorter, easy to debug
structure of looping.

Syntax:
for (initialization ; testing condition; increment/decrement)

statement(s);

Flowchart:

 Initialization condition: Here, we initialize the variable in use. It


marks the start of a for loop. An already declared variable can be used
or a variable can be declared, local to loop only.
 Testing Condition: It is used for testing the exit condition for a loop.
It must return a boolean value. It is also an Entry Control Loop as
the condition is checked prior to the execution of the loop statements.
 Statement execution: Once the condition is evaluated to true, the
statements in the loop body are executed.
 Increment/ Decrement: It is used for updating the variable for next
iteration.
 Loop termination:When the condition becomes false, the loop
terminates marking the end of its life cycle.
Example:

do while Loop:

do while loop is similar to while loop with only difference that it checks for
condition after executing the statements, and therefore is an example of Exit
Control Loop.

Syntax:
do

statements..

}
while (condition);

 Flowchart:

 do while loop starts with the execution of the statement(s). There is no


checking of any condition for the first time.
 After the execution of the statements, and update of the variable
value, the condition is checked for true or false value. If it is evaluated
to true, next iteration of loop starts.
 When the condition becomes false, the loop terminates which marks
the end of its life cycle.
 It is important to note that the do-while loop will execute its
statements atleast once before any condition is checked, and therefore
is an example of exit control loop.

Example:

public static void main(String args[])


{

int i = 1;
// Do-while loop
do{

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

i++;
}while (i < 6);
}
}

for-each Loop

The for-each loop is used to traverse array or collection in Java. It is easier to use than
simple for loop because we don't need to increment value and use subscript notation.It works
on the basis of elements and not the index. It returns element one by one in the defined
variable.

Syntax:

for(data_type variable : array_name){


//code to be executed
}

Example:
public class Example {
public static void main(String[] args) {
//Declaring an array
int arr[]={12,23,44,56,78};
//Printing array using for-each loop
for(int i:arr){
System.out.println(i);
}
}
}

Infinitive for Loop

If you use two semicolons ;; in the for loop, it will be infinitive for loop.

Syntax:

for(;;)
{
//code to be executed
}

Example:

public class ForExample {


public static void main(String[] args) {
//Using no condition in for loop
for(;;)
{
System.out.println("infinitive loop");
}
}
}

Output:
infinitive loop
infinitive loop
infinitive loop
infinitive loop
infinitive loop
ctrl+c

Now, you need to press ctrl+c to exit from the program.

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
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.

The floowing picture depictes the execution flow of the break statement.
Example:

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.
Example 1:
Example 2:

Output
13579

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
continue statement takes the execution control to the beginning of a loop with specified
label.
import java.util.Scanner;

public class Example {


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!!!");
break reading;
}
else
{
System.out.println("\nSorry try again!!!");
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.

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.

Syntax:

The syntax of a return statement is the return keyword is followed by the value to be
returned.

return returnvalue;
Example 1:
public class Main
{
static int myMethod(int x)
{
return 5 + x;
}
public static void main(String[] args)
{
System.out.println(myMethod(3));
}
}
// Outputs 8 (5 + 3)

Example 2:

public class SampleReturn1


{

public int CompareNum()


{
int x = 3;
int y = 8;
if(x>y)
return x;
else
return y;
}
public static void main(String ar[])
{
SampleReturn1 obj = new SampleReturn1();
int result = obj.CompareNum();
System.out.println("The greater number among x and y is: " + result);
}
}

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 clasiffied into the following four types.

 Arithmetic Operators
 Relational (or) Comparision Operators
 Logical Operators
 Assignment Operators
 Bitwise Operators
 Conditional Operators

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--

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
otherwise returns FALSE FALSE

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

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

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

== 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


FALSE TRUE

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 false & true =>
otherwise returns FALSE false

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

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

! 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 false | true =>
is finalized it does not evaluate remianing. true

Short-circuit OR

To answer the question you only needed to evaluate the first subexpression:

12 > 6 || 18 > 1
------
true

Once you know that this subexpression is true there is no need to go


further. true OR anything is true
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
Operator Meaning Example

/= 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

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)

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

~ the result of Bitwise once complement is negation of the bit ~A


(Flipping) ⇒ 6 (00110)

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

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

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;


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);

Type casting in java


The process of converting a value from one data type to another is known
as type conversion in Java.Type conversion is also known as type casting
in java or simply ‘casting’.
Type casting is when you assign a value of one primitive data type to
another type.

Types of Casting in Java

Two types of casting are possible in Java are as follows:


1. Implicit type casting (Automatic type conversion/Widening Casting)
2. Explicit type casting(Narrowing 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

Implicit Type Casting / Automatic /Widening Casting

Automatic conversion (casting) done by Java compiler internally is


called implicit conversion or implicit type casting in java.Implicit
casting is performed to convert a lower data type into a higher
data type. It is also known as automatic type promotion in Java.

An automatic type conversion takes place in Java if these two conditions


are met:
 The data types are compatible with each other.
 The destination type is bigger than the source type.
The below figure shows which conversion is allowed by Java.
From the above diagram, a byte can be promoted to short, int, long, float,
or double. Similarly, the short data type can be promoted to int, long, float,
or double. The char data type can be promoted to int, float, long or
double, and so on.

Automatic Type Promotion Rules in Expression

1. If byte, short, and int are used in a mathematical expression, Java always
converts the result into an int.
2. If a single long is used in the expression, the whole expression is
converted to long.
3. If a float operand is used in an expression, the whole expression is
converted to float.
4. If any operand is double, the result is promoted to double.
5. Boolean values cannot be converted to another type.

Example
public class Example

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

}
Explicit Type casting (Narrowing conversion)
The conversion of a higher data type into a lower data type is called
narrowing conversion.

Since this type of conversion is performed by the programmer, not by the


compiler automatically, therefore, it is also called explicit type casting in
java. It is done to convert from a higher data type to a lower data type.
The following diagram is useful to perform the narrowing conversion or
explicit type casting in Java program.

The general form of a cast is given below:


Syntax:

(type_name)expression;

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 types of data.

Some important points about Java arrays.

 In Java, all arrays are dynamically allocated.


 Arrays are stored in contagious memory [consecutive memory locations].
 Since arrays are objects in Java, we can find their length using the object
property length. This is different from C/C++, where we find length using
sizeof.
 A Java array variable can also be declared like other variables with [] after
the data type.
 The variables in the array are ordered, and each has an index beginning
from 0.
 Java array can also be used as a static field, a local variable, or a method
parameter.
 The size of an array must be specified by int or short value and not long.
 The direct superclass of an array type is Object.

Types of Array in java


There are two types of array.

o Single Dimensional Array


o Multidimensional Array

One-Dimensional Arrays
In Java, here is how we can declare an array.

dataType[ ] arrayName;
 dataType - it can be primitive data types like int, char, double, byte, etc.
or Java objects
 arrayName - it is an identifier

// both are valid declarations


int intArray[];
or int[] intArray;
When an array is declared, only a reference of an array is created. To
create or give memory to the array, you create an array like this

In Java, we can declare and allocate the memory of an array in one single
statement. For example,

double[] data = new double[10];

Initialize Arrays
In Java, we can initialize arrays during declaration. For example,

//declare and initialize and array

int[] age = {12, 4, 5, 2, 5};

Here, we have created an array named age and initialized it with the values
inside the curly brackets.
Note that we have not provided the size of the array. In this case, the Java
compiler automatically specifies the size by counting the number of elements
in the array (i.e. 5).

In the Java array, each memory location is associated with a number. The
number is known as an array index. We can also initialize arrays in Java, using
the index number.

We can access the element of an array using the index number. Here is
the syntax for accessing elements of an array,

// access array elements

array[index]
Multidimensional Arrays

A multidimensional array is an array of arrays. Each element of a


multidimensional array is an array itself. For example,

int[][] a = new int[3][4];


Here, we have created a multidimensional array named a. It is a 2-dimensional
array, that can hold a maximum of 12 elements,

2-dimensional Array
Remember, Java uses zero-based indexing, that is, indexing of arrays in Java
starts with 0 and not 1.

Initialization of 2-dimensional Array

unlike C/C++, each row of the multidimensional array in Java can be of


different lengths.

Initialization of 2-dimensional Array


Sum of two numbers using Scanner
import java.util.Scanner;
public class AddTwoNumbers2 {

public static void main(String[] args) {

int num1, num2, sum;


Scanner sc = new Scanner(System.in);
System.out.println("Enter First Number: ");
num1 = sc.nextInt();

System.out.println("Enter Second Number: ");


num2 = sc.nextInt();

sc.close();
sum = num1 + num2;
System.out.println("Sum of these numbers: "+sum);
}
}

Output:
Enter First Number:
121
Enter Second Number:
19
Sum of these numbers: 140

Java Program to check Even or Odd number

import java.util.Scanner;

class CheckEvenOdd
{
public static void main(String args[])
{
int num;
System.out.println("Enter an Integer number:");

//The input provided by user is stored in num


Scanner input = new Scanner(System.in);
num = input.nextInt();

/* If number is divisible by 2 then it's an even number


* else odd number*/
if ( num % 2 == 0 )
System.out.println("Entered number is even");
else
System.out.println("Entered number is odd");
}
}

java program to find factorial of a given number using recursion


import java.util.Scanner;
class FactorialDemo{
public static void main(String args[]){
//Scanner object for capturing the user input
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number:");
//Stored the entered value in variable
int num = scanner.nextInt();
//Called the user defined function fact
int factorial = fact(num);
System.out.println("Factorial of entered number is:
"+factorial);
}
static int fact(int n)
{
int output;
if(n==1){
return 1;
}
//Recursion: Function calling itself!!
output = fact(n-1)* n;
return output;
}
}

Program:Array using Scanner

import java.util.Scanner;
public class ArrayInputExample1
{
public static void main(String[] args)
{
int n;
Scanner sc=new Scanner(System.in);
System.out.print("Enter the number of elements you want to store: ");
//reading the number of elements from the that we want to enter
n=sc.nextInt();
//creates an array in the memory of length 10
int[] array = new int[10];
System.out.println("Enter the elements of the array: ");
for(int i=0; i<n; i++)
{
//reading array elements from the user
array[i]=sc.nextInt();
}
System.out.println("Array elements are: ");
// accessing array elements using the for loop
for (int i=0; i<n; i++)
{
System.out.println(array[i]);
}
}
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy