Java Basics

Download as pdf or txt
Download as pdf or txt
You are on page 1of 57

INTRODUCTION TO OOPS

Introduction to object-oriented programming -principles of object-oriented languages -


procedural languages Vs. OOPs -applications of OOPs -java features - JVM -program
structures -Variables -primitive data types –identifiers -naming conventions –keywords –
literals –operators –binary -unary and ternary –expression -precedence rules and associativity
-primitive type conversion and casting, flow of control. [6 Hours]

What is Java?
Java is a programming language and a platform. Java is a high level, robust,
object-oriented and secure programming language.

Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in
the year 1995. James Gosling is known as the father of Java. Before Java, its name
was Oak. Since Oak was already a registered company, so James Gosling and his
team changed the name from Oak to Java.

Platform: Any hardware or software environment in which a program runs, is known


as a platform. Since Java has a runtime environment (JRE) and API, it is called a
platform.

Types of Java Applications


There are mainly 4 types of applications that can be created using Java
programming:

1) Standalone Application

Standalone applications are also known as desktop applications or window-based


applications. These are traditional software that we need to install on every machine.
Examples of standalone application are Media player, antivirus, etc. AWT and Swing
are used in Java for creating standalone applications.

2) Web Application

An application that runs on the server side and creates a dynamic page is called a
web application. Currently, Servlet, JSP, Struts, Spring, Hibernate, JSF, etc.
technologies are used for creating web applications in Java.

3) Enterprise Application

Page 1 of 63
An application that is distributed in nature, such as banking applications, etc. is called
an enterprise application. It has advantages like high-level security, load balancing,
and clustering. In Java, EJB is used for creating enterprise applications.

4) Mobile Application

An application which is created for mobile devices is called a mobile application.


Currently, Android and Java ME are used for creating mobile applications.

Java Platforms / Editions


There are 4 platforms or editions of Java:

1) Java SE (Java Standard Edition)

It is a Java programming platform. It includes Java programming APIs such as


java.lang, java.io, java.net, java.util, java.sql, java.math etc. It includes core topics like
OOPs, String, Regex, Exception, Inner classes, Multithreading, I/O Stream,
Networking, AWT, Swing, Reflection, Collection, etc.

2) Java EE (Java Enterprise Edition)

It is an enterprise platform that is mainly used to develop web and enterprise


applications. It is built on top of the Java SE platform. It includes topics like Servlet,
JSP, Web Services, EJB, JPA, etc.

3) Java ME (Java Micro Edition)

It is a micro platform that is dedicated to mobile applications.

4) JavaFX

It is used to develop rich internet applications. It uses a lightweight user interface


API.

Java Version History


Many java versions have been released till now. The current stable release of Java is
Java SE 10.

1. JDK Alpha and Beta (1995)


2. JDK 1.0 (23rd Jan 1996)

3. JDK 1.1 (19th Feb 1997)

Page 2 of 63
4. J2SE 1.2 (8th Dec 1998)
5. J2SE 1.3 (8th May 2000)

6. J2SE 1.4 (6th Feb 2002)


7. J2SE 5.0 (30th Sep 2004)
8. Java SE 6 (11th Dec 2006)
9. Java SE 7 (28th July 2011)
10. Java SE 8 (18th Mar 2014)

11. Java SE 9 (21st Sep 2017)


12. Java SE 10 (20th Mar 2018)
13. Java SE 11 (September 2018)
14. Java SE 12 (March 2019)
15. Java SE 13 (September 2019)

16. Java SE 14 (Mar 2020)


17. Java SE 15 (September 2020)
18. Java SE 16 (Mar 2021)
19. Java SE 17 (September 2021)
20. Java SE 18 (to be released by March 2022)

Since Java SE 8 release, the Oracle corporation follows a pattern in which every even
version is release in March month and an odd version released in September month.

Features of Java
The primary objective of Java programming language creation was to make it portable,
simple and secure programming language. Apart from this, there are also some excellent
features which play an important role in the popularity of this language. The features of Java
are also known as Java buzzwords.

A list of the most important features of the Java language is given below.

Page 3 of 63
1. Simple

2. Object-Oriented

3. Portable

4. Platform independent

5. Secured

6. Robust

7. Architecture neutral

8. Interpreted

9. High Performance

10. Multithreaded

11. Distributed

12. Dynamic

Simple
Java is very easy to learn, and its syntax is simple, clean and easy to understand.
According to Sun Microsystem, Java language is a simple programming language
because:

o Java syntax is based on C++ (so easier for programmers to learn it after C++).

o Java has removed many complicated and rarely-used features, for example, explicit
pointers, operator overloading, etc.
o There is no need to remove unreferenced objects because there is an Automatic
Garbage Collection in Java.

Object-oriented
Java is an object-oriented programming language. Everything in Java is an object. Object-
oriented means we organize our software as a combination of different types of objects that
incorporate both data and behavior.

Object-oriented programming (OOPs) is a methodology that simplifies software


development and maintenance by providing some rules.

Page 4 of 63
Basic concepts of OOPs are:

1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation

Platform Independent

Java is platform independent because it is different from other languages like C, C++,
etc. which are compiled into platform specific machines while Java is a write once, run
anywhere language. A platform is the hardware or software environment in which a program
runs.

There are two types of platforms software-based and hardware-based. Java provides
a software-based platform.

The Java platform differs from most other platforms in the sense that it is a software-
based platform that runs on top of other hardware-based platforms. It has two
components:

1. Runtime Environment
2. API(Application Programming Interface)

Java code can be executed on multiple platforms, for example, Windows, Linux, Sun
Solaris, Mac/OS, etc. Java code is compiled by the compiler and converted into
bytecode. This bytecode is a platform-independent code because it can be run on
multiple platforms, i.e., Write Once and Run Anywhere (WORA).

Page 5 of 63
Secured
Java is best known for its security. With Java, we can develop virus-free systems. Java
is secured because:

o No explicit pointer
o Java Programs run inside a virtual machine sandbox

o Classloader: Classloader in Java is a part of the Java Runtime Environment (JRE)


which is used to load Java classes into the Java Virtual Machine dynamically. It adds
security by separating the package for the classes of the local file system from those
that are imported from network sources.
o Bytecode Verifier: It checks the code fragments for illegal code that can violate
access rights to objects.
o Security Manager: It determines what resources a class can access such as reading
and writing to the local disk.

Java language provides these securities by default. Some security can also be
provided by an application developer explicitly through SSL, JAAS, Cryptography, etc.

Page 6 of 63
Difference between JDK, JRE, and JVM
JVM
 JVM (Java Virtual Machine) is an abstract machine. 

 It is called a virtual machinebecause it doesn't physically exist.


 It is a specification that provides a runtime environment in which Java
bytecode can be executed.
 It can also run those programs which are written in other languages and
compiled to Java bytecode.

JVMs are available for many hardware and software platforms.

 JVM, JRE, and JDK are platform dependent because the configuration of
each OS is different from each other. However, Java is platform independent. There
are three notions of the JVM: specification, implementation, and instance.

The JVM performs the following main tasks:

o Loads code
o Verifies code
o Executes code
o Provides runtime environment

JRE
JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The
Java Runtime Environment is a set of software tools which are used for developing
Java applications.

It is used to provide the runtime environment. It is the implementation of JVM. It


physically exists. It contains a set of libraries + other files that JVM uses at runtime.

The implementation of JVM is also actively released by other companies besides Sun
Micro Systems.

JDK
JDK is an acronym for Java Development Kit. The Java Development Kit (JDK) is a
software development environment which is used to develop Java applications
and applets. It physically exists. It contains JRE + development tools.

Page 7 of 63
JDK is an implementation of any one of the below given Java Platforms released by
Oracle Corporation:

o Standard Edition Java Platform

o Enterprise Edition Java Platform


o Micro Edition Java Platform

The JDK contains a private Java Virtual Machine (JVM) and a few other resources such
as an interpreter/loader (java), a compiler (javac), an archiver (jar), a documentation
generator (Javadoc), etc. to complete the development of a Java Application.

Page 8 of 63
Java Variables
A variable is a container which holds the value while the Java program is executed. A
variable is assigned with a data type.

Variable is a name of memory location. There are three types of variables in java:
local, instance and static.

There are two types of data types in Java: primitive and non-primitive.

Variable
A variable is the name of a reserved area allocated in memory. In other words, it is a
name of the memory location. It is a combination of "vary + able" which means its
value can be changed.

1. int data=50;//Here data is variable

Types of Variables
There are three types of variables in Java:

o local variable
o instance variable
o static variable

Page 9 of 63
1) Local Variable

A variable declared inside the body of the method is called local variable. You can
use this variable only within that method and the other methods in the class aren't
even aware that the variable exists.

A local variable cannot be defined with "static" keyword.

2) Instance Variable

A variable declared inside the class but outside the body of the method, is called an
instance variable. It is not declared as static.

It is called an instance variable because its value is instance-specific and is not shared
among instances.

3) Static variable

A variable that is declared as static is called a static variable. It cannot be local. You
can create a single copy of the static variable and share it among all the instances of
the class. Memory allocation for static variables happens only once when the class is
loaded in the memory.

// Java Program to implement


// Local Variables

class localprogram {
public static void main(String[] args)
{
// Declared a Local Variable
int var = 10;

// This variable is local to this main method only


System.out.println("Local Variable: " + var);
}
Page 10 of 63
}

// Java Program to demonstrate Static variables

class sample {
// Declared static variable
public static String name = "Laxmi";

public static void main(String[] args)


{

// static variable
System.out.println("Name is : " + sample.name);

}
}

Page 11 of 63
Data Types in Java
Data types specify the different sizes and values that can be stored in the variable.
There are two types of data types in Java:

1. Primitive data types: The primitive data types include boolean, char, byte, short, int,
long, float and double.

2. Non-primitive data types: The non-primitive data types include Classes, Interfaces,
and Arrays.

Java Primitive Data Types


In Java language, primitive data types are the building blocks of data manipulation.
These are the most basic data types available in Java language.

Java is a statically-typed programming language. It means, all variables must be declared


before its use. That is why we need to declare variable's type and name.

There are 8 types of primitive data types:

 boolean data type

 byte data type

 char data type


 short data type
 int data type
 long data type

 float data type


 double data type

Page 12 of 63
Data Type Default Value Default size

boolean false 1 bit

char '\u0000' 2 byte

byte 0 1 byte

short 0 2 byte

int 0 4 byte

long 0L 8 byte

float 0.0f 4 byte

double 0.0d 8 byte

Boolean Data Type


The Boolean data type is used to store only two possible values: true and false. This
data type is used for simple flags that track true/false conditions.

The Boolean data type specifies one bit of information, but its "size" can't be defined
precisely.

Example:

1. Boolean one = false

Byte Data Type


The byte data type is an example of primitive data type. It isan 8-bit signed two's
complement integer. Its value-range lies between -128 to 127 (inclusive). Its
minimum value is -128 and maximum value is 127. Its default value is 0.

Page 13 of 63
The byte data type is used to save memory in large arrays where the memory savings
is most required. It saves space because a byte is 4 times smaller than an integer. It
can also be used in place of "int" data type.

Example:

1. byte a = 10, byte b = -20

Short Data Type


The short data type is a 16-bit signed two's complement integer. Its value-range lies
between -32,768 to 32,767 (inclusive). Its minimum value is -32,768 and maximum
value is 32,767. Its default value is 0.

The short data type can also be used to save memory just like byte data type. A short
data type is 2 times smaller than an integer.

Example:

1. short s = 10000, short r = -5000

Int Data Type


The int data type is a 32-bit signed two's complement integer. Its value-range lies
between - 2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum
value is - 2,147,483,648and maximum value is 2,147,483,647. Its default value is 0.

The int data type is generally used as a default data type for integral values unless if
there is no problem about memory.

Example:

1. int a = 100000, int b = -200000

Long Data Type


The long data type is a 64-bit two's complement integer. Its value-range lies between
-9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)(inclusive).
Its minimum value is - 9,223,372,036,854,775,808and maximum value is
9,223,372,036,854,775,807. Its default value is 0. The long data type is used when you
need a range of values more than those provided by int.

Example:

Page 14 of 63
1. long a = 100000L, long b = -200000L

Float Data Type


The float data type is a single-precision 32-bit IEEE 754 floating point.Its value range
is unlimited. It is recommended to use a float (instead of double) if you need to save
memory in large arrays of floating point numbers. The float data type should never
be used for precise values, such as currency. Its default value is 0.0F.

Example:

1. float f1 = 234.5f

Double Data Type


The double data type is a double-precision 64-bit IEEE 754 floating point. Its value
range is unlimited. The double data type is generally used for decimal values just like
float. The double data type also should never be used for precise values, such as
currency. Its default value is 0.0d.

Example:

1. double d1 = 12.3

Char Data Type


The char data type is a single 16-bit Unicode character. Its value-range lies between
'\u0000' (or 0) to '\uffff' (or 65,535 inclusive).The char data type is used to store
characters.

Example:

1. char letterA = 'A'

Example to understand the types of variables in java


public class A
{
static int m=100;//static variable
void method()
{
int n=90;//local variable

Page 15 of 63
}
public static void main(String args[])
{
int data=50;//instance variable
}
}//end of class

Java Variable Example: Add Two Numbers


public class Simple{
public static void main(String[] args){
int a=10;
int b=10;
int c=a+b;
System.out.println(c);
}
}

Output:

20

Java Variable Example: Widening


public class Simple{
public static void main(String[] args){
int a=10;
float f=a;
System.out.println(a);
System.out.println(f);
}}

Output:

10
10.0

Java Variable Example: Narrowing (Typecasting)


public class Simple{

Page 16 of 63
public static void main(String[] args){
float f=10.5f;
//int a=f;//Compile time error
int a=(int)f;
System.out.println(f);
System.out.println(a); }}

Output:

10.5
10

Java Variable Example: Overflow


class Simple{
public static void main(String[] args){
//Overflow4.
int a=130;
byte b=(byte)a;
System.out.println(a);
System.out.println(b);}}

Output:

130
-126

Java Variable Example: Adding Lower Type


class Simple{
public static void main(String[] args){
byte a=10;
byte b=10;
//byte c=a+b;//Compile Time Error: because a+b=20 will be int
byte c=(byte)(a+b);
System.out.println(c); }}

Output:

Page 17 of 63
20

Page 18 of 63
Operators in Java
Java provides a rich set of operators to manipulate variables. We can divide all the

Java operators into the following groups −

 Arithmetic Operators

 Relational Operators

 Bitwise Operators

 Logical Operators

 Assignment Operators

 Misc Operators

The Arithmetic Operators

Arithmetic operators are used in mathematical expressions in the same way that

they are used in algebra. The following table lists the arithmetic operators −

Assume integer variable A holds 10 and variable B holds 20, then −

Operator Description Example

Adds values on either side of the operator. A + B will give


+ (Addition)
30

- (Subtraction) Subtracts right-hand operand from left-hand


A - B will give

Page 19 of 63
operand. -10

* Multiplies values on either side of the operator. A * B will give

(Multiplication) 200

Divides left-hand operand by right-hand operand. B / A will give


/ (Division)
2

Divides left-hand operand by right-hand operand B % A will give


% (Modulus)
and returns remainder. 0

++ (Increment) Increases the value of operand by 1. B++ gives 21

-- (Decrement) Decreases the value of operand by 1. B-- gives 19

The following program is a simple example which demonstrates the arithmetic

operators.

public class Test {

public static void main(String args[]) {

int a = 10;

int b = 20;

int c = 25;

Page 20 of 63
int d = 25;

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

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

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

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

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

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

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

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

// Check the difference in d++ and ++d

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

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

This will produce the following result −

Output

a + b = 30

a - b = -10

a * b = 200

b / a = 2

b % a = 0

c % a = 5

a++ = 10

Page 21 of 63
b-- = 11

d++ = 25

++d = 27

The Relational Operators

There are following relational operators supported by Java language.

Assume variable A holds 10 and variable B holds 20, then −

Operator Description Example

Checks if the values of two operands are equal or (A == B) is


== (equal to)
not, if yes then condition becomes true. not true.

Checks if the values of two operands are equal or


(A != B) is
!= (not equal to) not, if values are not equal then condition becomes
true.
true.

Checks if the value of left operand is greater than


(A > B) is
> (greater than) the value of right operand, if yes then condition
not true.
becomes true.

Checks if the value of left operand is less than the (A < B) is


< (less than)
value of right operand, if yes then condition true.

Page 22 of 63
becomes true.

>= (greater Checks if the value of left operand is greater than


(A >= B) is
than or equal or equal to the value of right operand, if yes then
not true.
to) condition becomes true.

Checks if the value of left operand is less than or


<= (less than or (A <= B) is
equal to the value of right operand, if yes then
equal to) true.
condition becomes true.

The following program is a simple example that demonstrates the relational

operators.

Example

public class Test {

public static void main(String args[]) {

int a = 10;

int 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 < b = " + (a < b) );

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

Page 23 of 63
System.out.println("b <= a = " + (b <= a) );

This will produce the following result −

Output

a == b = false

a != b = true

a > b = false

a < b = true

b >= a = true

b <= a = false

The Bitwise Operators

Java defines several bitwise operators, which can be applied to the integer types,

long, int, short, char, and byte.

Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60

and b = 13; now in binary format they will be as follows −

a = 0011 1100

b = 0000 1101

Page 24 of 63
a&b = 0000 1100

a|b = 0011 1101

a^b = 0011 0001

~a = 1100 0011

The following table lists the bitwise operators −

Assume integer variable A holds 60 and variable B holds 13 then −

Operator Description Example

& (bitwise Binary AND Operator copies a bit to (A & B) will give 12 which

and) the result if it exists in both operands. is 0000 1100

Binary OR Operator copies a bit if it (A | B) will give 61 which is


| (bitwise or)
exists in either operand. 0011 1101

^ (bitwise Binary XOR Operator copies the bit if it (A ^ B) will give 49 which

XOR) is set in one operand but not both. is 0011 0001

(~A ) will give -61 which is


Binary Ones Complement Operator is
~ (bitwise 1100 0011 in 2's
unary and has the effect of 'flipping'
compliment) complement form due to a
bits.
signed binary number.

Page 25 of 63
Binary Left Shift Operator. The left

operands value is moved left by the A << 2 will give 240 which
<< (left shift)
number of bits specified by the right is 1111 0000

operand.

Binary Right Shift Operator. The left

operands value is moved right by the A >> 2 will give 15 which


>> (right shift)
number of bits specified by the right is 1111

operand.

Shift right zero fill operator. The left

operands value is moved right by the


>>> (zero fill A >>>2 will give 15 which
number of bits specified by the right
right shift) is 0000 1111
operand and shifted values are filled

up with zeros.

The Logical Operators

The following table lists the logical operators −

Assume Boolean variables A holds true and variable B holds false, then −

Operator Description Example

Page 26 of 63
&& (logical Called Logical AND operator. If both the operands are (A && B) is

and) non-zero, then the condition becomes true. false

|| (logical Called Logical OR Operator. If any of the two operands (A || B) is

or) are non-zero, then the condition becomes true. true

Called Logical NOT Operator. Use to reverses the


! (logical !(A && B) is
logical state of its operand. If a condition is true then
not) true
Logical NOT operator will make false.

The Assignment Operators

Following are the assignment operators supported by Java language −

Operator Description Example

Simple assignment operator. Assigns values from C = A + B will assign


=
right side operands to left side operand. value of A + B into C

Add AND assignment operator. It adds right


C += A is equivalent
+= operand to the left operand and assign the result
to C = C + A
to left operand.

Page 27 of 63
Subtract AND assignment operator. It subtracts
C -= A is equivalent
-= right operand from the left operand and assign
to C = C – A
the result to left operand.

Multiply AND assignment operator. It multiplies


C *= A is equivalent
*= right operand with the left operand and assign the
to C = C * A
result to left operand.

/= Divide AND assignment operator. It divides left


C /= A is equivalent
operand with the right operand and assign the
to C = C / A
result to left operand.

Modulus AND assignment operator. It takes


C %= A is equivalent
%= modulus using two operands and assign the
to C = C % A
result to left operand.

C <<= 2 is same as
<<= Left shift AND assignment operator.
C = C << 2

C >>= 2 is same as
>>= Right shift AND assignment operator.
C = C >> 2

C &= 2 is same as C
&= Bitwise AND assignment operator.
=C&2

Page 28 of 63
bitwise exclusive OR and assignment operator. C ^= 2 is same as C
^=
=C^2

bitwise inclusive OR and assignment operator. C |= 2 is same as C


|=
=C|2

Miscellaneous Operators

There are few other operators supported by Java Language.

Conditional Operator ( ? : )

Conditional operator is also known as the ternary operator. This operator consists

of three operands and is used to evaluate Boolean expressions. The goal of the

operator is to decide, which value should be assigned to the variable. The operator

is written as −

variable x = (expression) ? value if true : value if false

Following is an example −

Example

public class Test {

public static void main(String args[]) {

int a, b;

a = 10;

b = (a == 1) ? 20: 30;

Page 29 of 63
System.out.println( "Value of b is : " + b );

b = (a == 10) ? 20: 30;

System.out.println( "Value of b is : " + b );

This will produce the following result −

Output

Value of b is : 30

Value of b is : 20

instanceof Operator

 This operator is used only for object reference variables.

 The operator checks whether the object is of a particular type (class type or interface

type).

 instanceof operator is written as −

( Object reference variable ) instanceof (class/interface type)

If the object referred by the variable on the left side of the operator passes the IS-A

check for the class/interface type on the right side, then the result will be true.

Following is an example −

Example

public class Test {

Pagepublic
30 of 63 static void main(String args[]) {
String name = "James";

// following will return true since name is type of String

boolean result = name instanceof String;

System.out.println( result );

This will produce the following result −

Output

true

This operator will still return true, if the object being compared is the assignment

compatible with the type on the right. Following is one more example −

Example

class Vehicle {}

public class Car extends Vehicle {

public static void main(String args[]) {

Vehicle a = new Car();

boolean result = a instanceof Car;

System.out.println( result );

Page 31 of 63
This will produce the following result −

Output

True

Page 32 of 63
Having a semicolon at the end of class is optional in Java.

Let's see the simple code.

1. class A{
2. static public void main(String... args){
3. System.out.println("hello java4");
4. }
5. };

Valid Java main() method signature


1. public static void main(String[] args)
2. public static void main(String []args)
3. public static void main(String args[])
4. public static void main(String... args)
5. static public void main(String[] args)
6. public static final void main(String[] args)
7. final public static void main(String[] args)
8. final strictfp public static void main(String[] args)

Invalid Java main() method signature


1. public void main(String[] args)
2. static void main(String[] args)
3. public void static main(String[] args)
4. abstract public static void main(String[] args)

Page 33 of 63
Java 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.

List of Java Keywords


A list of Java keywords or reserved words are given below:

1. abstract: Java abstract keyword is used to declare an abstract class. An abstract class
can provide the implementation of the interface. It can have abstract and non-
abstract methods.
2. boolean:Java boolean keyword is used to declare a variable as a boolean type. It can
hold True and False values only.

3. break: Java break keyword is used to break the loop or switch statement. It breaks
the current flow of the program at specified conditions.
4. byte: Java byte keyword is used to declare a variable that can hold 8-bit data values.
5. case: Java case keyword is used with the switch statements to mark blocks of text.

6. catch: Java catch keyword is used to catch the exceptions generated by try
statements. It must be used after the try block only.
7. char: Java char keyword is used to declare a variable that can hold unsigned 16 -bit
Unicode characters

8. class: Java class keyword is used to declare a class.


9. continue: Java continue keyword is used to continue the loop. It continues the
current flow of the program and skips the remaining code at the specified condition.

10. default: Java default keyword is used to specify the default block of code in a switch
statement.
11. do: Java do keyword is used in the control statement to declare a loop. I t can iterate
a part of the program several times.
12. double: Java double keyword is used to declare a variable that can hold 64 -bit
floating-point number.

13. else: Java else keyword is used to indicate the alternative branches in an if statement.
14. enum: Java enum keyword is used to define a fixed set of constants. Enum
constructors are always private or default.

Page 34 of 63
15. extends: Java extends keyword is used to indicate that a class is derived from
another class or interface.

16. final: Java final keyword is used to indicate that a variable holds a constant value. It is
used with a variable. It is used to restrict the user from updating the value of the
variable.
17. finally: Java finally keyword indicates a block of code in a try-catch structure. This
block is always executed whether an exception is handled or not.

18. float: Java float keyword is used to declare a variable that can hold a 32 -bit floating-
point number.
19. for: Java for keyword is used to start a for loop. It is used to execute a set of
instructions/functions repeatedly when some condition becomes true. If the number
of iteration is fixed, it is recommended to use for loop.
20. if: Java if keyword tests the condition. It executes the if block if the condition is true.
21. implements: Java implements keyword is used to implement an interface.

22. import: Java import keyword makes classes and interfaces available and accessible to
the current source code.
23. instanceof: Java instanceof keyword is used to test whether the object is an instance
of the specified class or implements an interface.

24. int: Java int keyword is used to declare a variable that can hold a 32 -bit signed
integer.

25. interface: Java interface keyword is used to declare an interface. It can have only
abstract methods.
26. long: Java long keyword is used to declare a variable that can hold a 64-bit integer.
27. native: Java native keyword is used to specify that a method is implemented in native
code using JNI (Java Native Interface).
28. new: Java new keyword is used to create new objects.
29. null: Java null keyword is used to indicate that a reference does not refer to anything.
It removes the garbage value.

30. package: Java package keyword is used to declare a Java package that includes the
classes.
31. private: Java private keyword is an access modifier. It is used to indicate that a
method or variable may be accessed only in the class in which it is declared.

Page 35 of 63
32. protected: Java protected keyword is an access modifier. It can be accessible within
the package and outside the package but through inheritance only. It can't be
applied with the class.
33. public: Java public keyword is an access modifier. It is used to indicate that an item is
accessible anywhere. It has the widest scope among all other modifiers.
34. return: Java return keyword is used to return from a method when its execution is
complete.

35. short: Java short keyword is used to declare a variable that can hold a 16 -bit integer.
36. static: Java static keyword is used to indicate that a variable or method is a class
method. The static keyword in Java is mainly used for memory management.
37. strictfp: Java strictfp is used to restrict the floating-point calculations to ensure
portability.
38. super: Java super keyword is a reference variable that is used to refer to parent class
objects. It can be used to invoke the immediate parent class method.

39. switch: The Java switch keyword contains a switch statement that executes code
based on test value. The switch statement tests the equality of a variable against
multiple values.

40. synchronized: Java synchronized keyword is used to specify the critical sections or
methods in multithreaded code.
41. this: Java this keyword can be used to refer the current object in a method or
constructor.
42. throw: The Java throw keyword is used to explicitly throw an exception. The throw
keyword is mainly used to throw custom exceptions. It is followed by an instance.

43. throws: The Java throws keyword is used to declare an exception. Checked
exceptions can be propagated with throws.
44. transient: Java transient keyword is used in serialization. If you define any data
member as transient, it will not be serialized.

45. try: Java try keyword is used to start a block of code that will be tested for
exceptions. The try block must be followed by either catch or finally block.
46. void: Java void keyword is used to specify that a method does not have a return
value.
47. volatile: Java volatile keyword is used to indicate that a variable may change
asynchronously.

Page 36 of 63
48. while: Java while keyword is used to start a while loop. This loop iterates a part of the
program several times. If the number of iteration is not fixed, it is recommended to
use the while loop.

Page 37 of 63
Java Command Line Arguments
The java command-line argument is an argument i.e. passed at the time of running
the java program.

The arguments passed from the console can be received in the java program and it
can be used as an input.

Simple example of command-line argument in java


In this example, we are receiving only one argument and printing it. To run this java
program, you must pass at least one argument from the command prompt.

class CommandLineExample{
public static void main(String args[]){
System.out.println("Your first argument is: "+args[0]);}}

1. compile by > javac CommandLineExample.java


2. run by > java CommandLineExample sonoo

Example of command-line argument that prints all the values


In this example, we are printing all the arguments passed from the command-line.
For this purpose, we have traversed the array using for loop.

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

Page 38 of 63
1. compile by > javac A.java
2. run by > java A sonoo jaiswal 1 3 abc

Page 39 of 63
Java User Input (Scanner)
Java User Input
The Scanner class is used to get user input, and it is found in
the java.util package.

To use the Scanner class, create an object of the class and use any of the
available methods found in the Scanner class documentation. In our example,
we will use the nextLine() method, which is used to read Strings:

Example
import java.util.Scanner; // Import the Scanner class

class Main {

public static void main(String[] args) {

Scanner myObj = new Scanner(System.in); // Create a Scanner object

System.out.println("Enter username");

String userName = myObj.nextLine(); // Read user input

System.out.println("Username is: " + userName); // Output user


input

Input Types
In the example above, we used the nextLine() method, which is used to read
Strings. To read other types, look at the table below:

Method Description

Page 40 of 63
nextBoolean() Reads a boolean value from the user

nextByte() Reads a byte value from the user

nextDouble() Reads a double value from the user

nextFloat() Reads a float value from the user

nextInt() Reads a int value from the user

nextLine() Reads a String value from the user

nextLong() Reads a long value from the user

nextShort() Reads a short value from the user

In the example below, we use different methods to read data of various


types:

Example
import java.util.Scanner;

class Main {

public static void main(String[] args) {

Scanner myObj = new Scanner(System.in);

Page 41 of 63
System.out.println("Enter name, age and salary:");

// String input

String name = myObj.nextLine();

// Numerical input

int age = myObj.nextInt();

double salary = myObj.nextDouble();

// Output input by user

System.out.println("Name: " + name);

System.out.println("Age: " + age);

System.out.println("Salary: " + salary);

Note: If you enter wrong input (e.g. text in a numerical input), you will get
an exception/error message (like "InputMismatchException").

Page 42 of 63
Java Control Statements | Control Flow in
Java
Java compiler executes the code from top to bottom. The statements in the code are
executed according to the order in which they appear. However, Java provides
statements that can be used to control the flow of Java code. Such statements are called
control flow statements. Java provides three types of control flow statements.

1. Decision Making statements

o if statements
o switch statement
2. Loop statements
o do while loop
o while loop
o for loop
o for-each loop
3. Jump statements
o break statement
o continue statement

Decision-Making statements:
As the name suggests, decision-making statements decide which statement to
execute and when. Decision-making statements evaluate the Boolean expression and
control the program flow depending upon the result of the condition provided.
There are two types of decision-making statements in Java, i.e., If statement and
switch statement.

1) If Statement:
In Java, the "if" statement is used to evaluate a condition. The control of the program
is diverted depending upon the specific condition. The condition of the If statement
gives a Boolean value, either true or false. In Java, there are four types of if-
statements given below.

Page 43 of 63
1. Simple if statement
2. if-else statement

3. if-else-if ladder
4. Nested if-statement

Let's understand the if-statements one by one.

1) Simple if statement:

It is the most basic statement among all control flow statements in Java. It evaluates
a Boolean expression and enables the program to enter a block of code if the
expression evaluates to true.

Syntax of if statement is given below.

if(condition) {
statement 1; //executes when condition is true }

Consider the following example in which we have used the if statement in the java
code.

Student.java

Student.java

public class Student {


public static void main(String[] args) {
int x = 10;
int y = 12;
5. if(x+y > 20) {
6. System.out.println("x + y is greater than 20");

}} }

Output:

x + y is greater than 20

Page 44 of 63
2) if-else statement

The if-else statement is an extension to the if-statement, which uses another block of code,
i.e., else block. The else block is executed if the condition of the if-block is evaluated as false.

Syntax:

if(condition) {
statement 1; //executes when condition is true }
else{
statement 2; //executes when condition is false }

Consider the following example.

Student.java

public class Student {


public static void main(String[] args) {
int x = 10;
int y = 12;
5. if(x+y < 10) {
System.out.println("x + y is less than10");
} else {
System.out.println("x + y is greater than 20"); }
}}

Output:

x + y is greater than 20

3) if-else-if ladder:

The if-else-if statement contains the if-statement followed by multiple else-if


statements. In other words, we can say that it is the chain of if -else statements that
create a decision tree where the program may enter in the block of code where the
condition is true. We can also define an else statement at the end of the chain.

Syntax of if-else-if statement is given below.

Page 45 of 63
if(condition 1) {
statement 1; //executes when condition 1 is true }
else if(condition 2) {
statement 2; //executes when condition 2 is true}
else {
statement 2; //executes when all the conditions are false }

Consider the following example.

Student.java

public class Student {


public static void main(String[] args) {
String city = "Delhi";
if(city == "Meerut") {
System.out.println("city is meerut");
}else if (city == "Noida") {
System.out.println("city is noida");
}else if(city == "Agra") {
System.out.println("city is agra");
}else {
System.out.println(city);
}}}

Output:

Delhi

4. Nested if-statement

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


another if or else-if statement.

Syntax of Nested if-statement is given below.

Page 46 of 63
if(condition 1) {
statement 1; //executes when condition 1 is true
if(condition 2) {
statement 2; //executes when condition 2 is true }
else{
statement 2; //executes when condition 2 is false}
}

Consider the following example.

Student.java

public class Student {


public static void main(String[] args) {
String address = "Delhi, India";
if(address.endsWith("India")) {
if(address.contains("Meerut")) {
System.out.println("Your city is Meerut");
}else if(address.contains("Noida")) {
System.out.println("Your city is Noida");
}else {
System.out.println(address.split(",")[0]);
}
}else {
System.out.println("You are not living in India");
}
}
}

Output:

Delhi

Switch Statement:
In Java, Switch statements are similar to if-else-if statements. The switch statement
contains multiple blocks of code called cases and a single case is executed based on the

Page 47 of 63
Variable which is being switched. The switch statement is easier to use instead of if-else-if
statements. It also enhances the readability of the program.

Points to be noted about switch statement:

o The case variables can be int, short, byte, char, or enumeration. String type is also
supported since version 7 of Java
o Cases cannot be duplicate

o Default statement is executed when any of the case doesn't match the value of
expression. It is optional.
o Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, next case is executed.

o While using switch statements, we must notice that the case expression will be of the
same type as the variable. However, it will also be a constant value.

The syntax to use the switch statement is given below.

switch (expression){
case value1:
statement1;
break;
5. .
6. .
7. .
case valueN:
statementN;
break;
default:
default statement;
}

Consider the following example to understand the flow of the switch statement.

Student.java

public class Student implements Cloneable {


public static void main(String[] args) {
int num = 2;
switch (num){

Page 48 of 63
case 0:
System.out.println("number is 0");
break;
case 1:
System.out.println("number is 1");
break;
default:
System.out.println(num);
}}}

Output:

While using switch statements, we must notice that the case expression will be of the
same type as the variable. However, it will also be a constant value. The switch
permits only int, string, and Enum type variables to be used.

Loop Statements
In programming, sometimes we need to execute the block of code repeatedly while
some condition evaluates to true. However, loop statements are used to execute the
set of instructions in a repeated order. The execution of the set of instructions
depends upon a particular condition.

In Java, we have three types of loops that execute similarly. However, there are
differences in their syntax and condition checking time.

1. for loop
2. while loop
3. do-while loop

Let's understand the loop statements one by one.

Java for loop


In Java, for loop is similar to C and C++. It enables us to initialize the loop variable, check
the condition, and increment/decrement in a single line of code. We use the for loop only
when we exactly know the number of times, we want to execute the block of code.

Page 49 of 63
for(initialization, condition, increment/decrement) {
//block of statements }

The flow chart for the for-loop is given below.

Consider the following example to understand the proper functioning of the for loop
in java.

Calculation.java

public class Calculattion {


public static void main(String[] args) {
// TODO Auto-generated method stub
int sum = 0;
for(int j = 1; j<=10; j++) {
sum = sum + j;
}
System.out.println("The sum of first 10 natural numbers is " + sum); }
}

Output:

The sum of first 10 natural numbers is 55

Java for-each loop


Java provides an enhanced for loop to traverse the data structures like array or
collection. In the for-each loop, we don't need to update the loop variable. The
syntax to use the for-each loop in java is given below.

Page 50 of 63
for(data_type var : array_name/collection_name){
//statements }

Consider the following example to understand the functioning of the for-each loop
in Java.

Calculation.java

public class Calculation {


public static void main(String[] args) {
// TODO Auto-generated method stub
String[] names = {"Java","C","C++","Python","JavaScript"};
System.out.println("Printing the content of the array names:\n");
for(String name:names) {
System.out.println(name); }
}
}

Output:

Printing the content of the array names:

Java
C
C++
Python
JavaScript

Java while loop


The while loop is also used to iterate over the number of statements multiple times.
However, if we don't know the number of iterations in advance, it is recommended to use a
while loop. Unlike for loop, the initialization and increment/decrement doesn't take place
inside the loop statement in while loop.

It is also known as the entry-controlled loop since the condition is checked at the
start of the loop. If the condition is true, then the loop body will be executed;
otherwise, the statements after the loop will be executed.

The syntax of the while loop is given below.

Page 51 of 63
1. while(condition){
2. //looping statements
3. }

The flow chart for the while loop is given in the following image.

Consider the following example.

Calculation .java

public class Calculation {


public static void main(String[] args) {
// TODO Auto-generated method stub
int i = 0;
System.out.println("Printing the list of first 10 even numbers \n");
while(i<=10) {
System.out.println(i);
i = i + 2;
}
}
}

Output:

Printing the list of first 10 even numbers

0
2

Page 52 of 63
4
6
8
10

Java do-while loop


The do-while loop checks the condition at the end of the loop after executing the loop
statements. When the number of iteration is not known and we have to execute the loop at
least once, we can use do-while loop.

It is also known as the exit-controlled loop since the condition is not checked in
advance. The syntax of the do-while loop is given below.

1. do
2. {
3. //statements
4. } while (condition);

The flow chart of the do-while loop is given in the following image.

Consider the following example to understand the functioning of the do-while loop
in Java.

Calculation.java

Page 53 of 63
1. public class Calculation {
2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. int i = 0;
5. System.out.println("Printing the list of first 10 even numbers \n");
6. do {
7. System.out.println(i);
8. i = i + 2;
9. }while(i<=10);
10. }
11. }

Output:

Printing the list of first 10 even numbers


0
2
4
6
8
10

Jump Statements
Jump statements are used to transfer the control of the program to the specific
statements. In other words, jump statements transfer the execution control to the
other part of the program. There are two types of jump statements in Java, i.e., break
and continue.

Java break statement


As the name suggests, the break statement is used to break the current flow of the
program and transfer the control to the next statement outside a loop or switch statement.
However, it breaks only the inner loop in the case of the nested loop.

The break statement cannot be used independently in the Java program, i.e., it can
only be written inside the loop or switch statement.

The break statement example with for loop

Consider the following example in which we have used the break statement with the
for loop.

BreakExample.java

Page 54 of 63
1. public class BreakExample {
2.
3. public static void main(String[] args) {
4. // TODO Auto-generated method stub
5. for(int i = 0; i<= 10; i++) {
6. System.out.println(i);
7. if(i==6) {
8. break;
9. }
10. }
11. }
12. }

Output:

0
1
2
3
4
5
6

break statement example with labeled for loop

Calculation.java

public class Calculation {

public static void main(String[] args) {

// TODO Auto-generated method stub

a:

for(int i = 0; i<= 10; i++) {

b:

for(int j = 0; j<=15;j++) {

c:

for (int k = 0; k<=20; k++) {


Page 55 of 63
System.out.println(k);

if(k==5) {

break a;

}}} }} }

Output:

0
1
2
3
4
5

Java continue statement


Unlike break statement, the continue statement doesn't break the loop, whereas, it skips
the specific part of the loop and jumps to the next iteration of the loop immediately.

Consider the following example to understand the functioning of the continue


statement in Java.

public class ContinueExample {2.


public static void main(String[] args) {
// TODO Auto-generated method stub5.
for(int i = 0; i<= 2; i++) {
7.
for (int j = i; j<=5; j++) {9
if(j == 4) {
continue;
}
System.out.println(j);
}

Page 56 of 63
}
}
}

Output:

0
1
2
3
5
1
2
3
5
2
3
5

Page 57 of 63

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