Java Basics
Java Basics
Java Basics
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.
1) Standalone Application
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
4) JavaFX
Page 2 of 63
4. J2SE 1.2 (8th Dec 1998)
5. J2SE 1.3 (8th May 2000)
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.
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
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.
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.
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.
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:
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.
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.
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.
class localprogram {
public static void main(String[] args)
{
// Declared a Local Variable
int var = 10;
class sample {
// Declared static variable
public static String name = "Laxmi";
// 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.
Page 12 of 63
Data Type Default Value Default size
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
The Boolean data type specifies one bit of information, but its "size" can't be defined
precisely.
Example:
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:
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:
The int data type is generally used as a default data type for integral values unless if
there is no problem about memory.
Example:
Example:
Page 14 of 63
1. long a = 100000L, long b = -200000L
Example:
1. float f1 = 234.5f
Example:
1. double d1 = 12.3
Example:
Page 15 of 63
}
public static void main(String args[])
{
int data=50;//instance variable
}
}//end of class
Output:
20
Output:
10
10.0
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
Output:
130
-126
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
Arithmetic Operators
Relational Operators
Bitwise Operators
Logical Operators
Assignment Operators
Misc 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 −
Page 19 of 63
operand. -10
(Multiplication) 200
operators.
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) );
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
Page 22 of 63
becomes true.
operators.
Example
int a = 10;
int b = 20;
System.out.println("a == b = " + (a == b) );
System.out.println("a != b = " + (a != b) );
Page 23 of 63
System.out.println("b <= a = " + (b <= a) );
Output
a == b = false
a != b = true
a > b = false
a < b = true
b >= a = true
b <= a = false
Java defines several bitwise operators, which can be applied to the integer types,
a = 0011 1100
b = 0000 1101
Page 24 of 63
a&b = 0000 1100
~a = 1100 0011
& (bitwise Binary AND Operator copies a bit to (A & B) will give 12 which
^ (bitwise Binary XOR Operator copies the bit if it (A ^ B) will give 49 which
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.
operand.
up with zeros.
Assume Boolean variables A holds true and variable B holds false, then −
Page 26 of 63
&& (logical Called Logical AND operator. If both the operands are (A && B) is
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.
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
Miscellaneous Operators
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 −
Following is an example −
Example
int a, b;
a = 10;
b = (a == 1) ? 20: 30;
Page 29 of 63
System.out.println( "Value of b is : " + b );
Output
Value of b is : 30
Value of b is : 20
instanceof Operator
The operator checks whether the object is of a particular type (class type or 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
Pagepublic
30 of 63 static void main(String args[]) {
String name = "James";
System.out.println( 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 {}
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.
1. class A{
2. static public void main(String... args){
3. System.out.println("hello java4");
4. }
5. };
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.
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
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.
class CommandLineExample{
public static void main(String args[]){
System.out.println("Your first argument is: "+args[0]);}}
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 {
System.out.println("Enter username");
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
Example
import java.util.Scanner;
class Main {
Page 41 of 63
System.out.println("Enter name, age and salary:");
// String input
// Numerical input
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.
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
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.
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
}} }
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 }
Student.java
Output:
x + y is greater than 20
3) if-else-if ladder:
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 }
Student.java
Output:
Delhi
4. Nested if-statement
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}
}
Student.java
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.
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.
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
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
Page 49 of 63
for(initialization, condition, increment/decrement) {
//block of statements }
Consider the following example to understand the proper functioning of the for loop
in java.
Calculation.java
Output:
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
Output:
Java
C
C++
Python
JavaScript
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.
Page 51 of 63
1. while(condition){
2. //looping statements
3. }
The flow chart for the while loop is given in the following image.
Calculation .java
Output:
0
2
Page 52 of 63
4
6
8
10
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:
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.
The break statement cannot be used independently in the Java program, i.e., it can
only be written inside the loop or switch statement.
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
Calculation.java
a:
b:
for(int j = 0; j<=15;j++) {
c:
if(k==5) {
break a;
}}} }} }
Output:
0
1
2
3
4
5
Page 56 of 63
}
}
}
Output:
0
1
2
3
5
1
2
3
5
2
3
5
Page 57 of 63